blob: a6e53649740e7b8d67f34d3284045ee482f0a72c [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremenek79b50cb2008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000025#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000026#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000028#include "llvm/System/Path.h"
Steve Naroff3c7b9a02008-04-14 22:53:48 +000029#include <sstream>
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include <fstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000046 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner569faa62007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000051
Ted Kremenek42730c52008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000060 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000061
Steve Naroff47e7fa22008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000075
Steve Naroff0add5d22007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000079
Fariborz Jahanian22277422008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff764c1ae2007-11-15 10:28:18 +000083 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000084 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000087
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Narofffef037c2008-03-27 22:29:16 +000094 std::string Preamble;
95
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000096 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000097 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +000098 virtual void Initialize(ASTContext &context);
99
100 virtual void InitializeTU(TranslationUnit &TU) {
101 TU.SetOwnsDecls(false);
102 Initialize(TU.getContext());
103 }
Chris Lattner12499682008-01-31 19:38:44 +0000104
Chris Lattner569faa62007-10-11 18:38:32 +0000105
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000106 // Top Level Driver code.
107 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000108 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000109 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000110 Diagnostic &D, const LangOptions &LOpts);
Steve Naroff44e81222008-04-14 22:03:09 +0000111 ~RewriteObjC();
Chris Lattnerb1548372008-01-31 19:37:57 +0000112
113 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000114 // If replacement succeeded or warning disabled return with no warning.
115 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000116 return;
117
Chris Lattnerb1548372008-01-31 19:37:57 +0000118 SourceRange Range = Old->getSourceRange();
119 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
120 0, 0, &Range, 1);
121 }
122
Steve Narofffef037c2008-03-27 22:29:16 +0000123 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
124 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000125 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000126 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000127 SilenceRewriteMacroWarning)
128 return;
129
130 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
131 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000132
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000133 void RemoveText(SourceLocation Loc, unsigned StrLen) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
136 return;
137
138 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
139 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000141 void ReplaceText(SourceLocation Start, unsigned OrigLength,
142 const char *NewStr, unsigned NewLength) {
143 // If removal succeeded or warning disabled return with no warning.
144 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
145 SilenceRewriteMacroWarning)
146 return;
147
148 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
149 }
150
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000151 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000152 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000153 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000154 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000155 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
156 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000157 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000158 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
159 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
160 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
161 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
162 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000163 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000164 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000165 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000166 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000167 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000168 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000169 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000170 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000171 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000172
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000173 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000174 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000175 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000176 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000177 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000178 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000179 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000180 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000181 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000182 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000183 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
184 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
185 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000186 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
187 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000188 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
189 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000190 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000191 Stmt *RewriteBreakStmt(BreakStmt *S);
192 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000193 void SynthCountByEnumWithState(std::string &buf);
194
Steve Naroff02a82aa2007-10-30 23:14:51 +0000195 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000196 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000197 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000198 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000199 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000200 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000201 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000202 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000203 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000204 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000205
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000206 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000207 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000208 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000209
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000211 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000212
Ted Kremenek42730c52008-01-07 19:49:32 +0000213 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
214 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000215 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000216 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000217 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000218 const char *ClassName,
219 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000220
Chris Lattner0be08822008-07-21 21:32:27 +0000221 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
222 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000223 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000224 const char *ClassName,
225 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000226 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000227 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
229 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000230 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000231 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000232 };
233}
234
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000235static bool IsHeaderFile(const std::string &Filename) {
236 std::string::size_type DotPos = Filename.rfind('.');
237
238 if (DotPos == std::string::npos) {
239 // no file extension
240 return false;
241 }
242
243 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
244 // C header: .h
245 // C++ header: .hh or .H;
246 return Ext == "h" || Ext == "hh" || Ext == "H";
247}
248
Steve Naroff44e81222008-04-14 22:03:09 +0000249RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000250 Diagnostic &D, const LangOptions &LOpts)
251 : Diags(D), LangOpts(LOpts) {
252 IsHeader = IsHeaderFile(inFile);
253 InFileName = inFile;
254 OutFileName = outFile;
255 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
256 "rewriting sub-expression within a macro (may not be correct)");
257}
258
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000259ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000260 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000261 Diagnostic &Diags,
262 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000263 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000264}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000265
Steve Naroff44e81222008-04-14 22:03:09 +0000266void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000267 Context = &context;
268 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000269 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000270 MsgSendFunctionDecl = 0;
271 MsgSendSuperFunctionDecl = 0;
272 MsgSendStretFunctionDecl = 0;
273 MsgSendSuperStretFunctionDecl = 0;
274 MsgSendFpretFunctionDecl = 0;
275 GetClassFunctionDecl = 0;
276 GetMetaClassFunctionDecl = 0;
277 SelGetUidFunctionDecl = 0;
278 CFStringFunctionDecl = 0;
279 GetProtocolFunctionDecl = 0;
280 ConstantStringClassReference = 0;
281 NSStringRecord = 0;
282 CurMethodDecl = 0;
283 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000284 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000285 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000286 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000287 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000288
289 // Get the ID and start/end of the main file.
290 MainFileID = SM->getMainFileID();
291 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
292 MainFileStart = MainBuf->getBufferStart();
293 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000294
Chris Lattner12499682008-01-31 19:38:44 +0000295 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000296
Chris Lattner12499682008-01-31 19:38:44 +0000297 // declaring objc_selector outside the parameter list removes a silly
298 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000299 if (IsHeader)
300 Preamble = "#pragma once\n";
301 Preamble += "struct objc_selector; struct objc_class;\n";
302 Preamble += "#ifndef OBJC_SUPER\n";
303 Preamble += "struct objc_super { struct objc_object *object; ";
304 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000305 if (LangOpts.Microsoft) {
306 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000307 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
308 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000309 }
Steve Narofffef037c2008-03-27 22:29:16 +0000310 Preamble += "};\n";
311 Preamble += "#define OBJC_SUPER\n";
312 Preamble += "#endif\n";
313 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
314 Preamble += "typedef struct objc_object Protocol;\n";
315 Preamble += "#define _REWRITER_typedef_Protocol\n";
316 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000317 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000318 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
319 else
320 Preamble += "#define __OBJC_RW_EXTERN extern\n";
321 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000322 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000324 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000326 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000328 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000329 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000330 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000331 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000332 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000333 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000334 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000335 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
336 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
337 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
338 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
339 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000340 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000341 // @synchronized hooks.
342 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
343 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000344 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000345 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
346 Preamble += "struct __objcFastEnumerationState {\n\t";
347 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000348 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000349 Preamble += "unsigned long *mutationsPtr;\n\t";
350 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000351 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000352 Preamble += "#define __FASTENUMERATIONSTATE\n";
353 Preamble += "#endif\n";
354 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
355 Preamble += "struct __NSConstantStringImpl {\n";
356 Preamble += " int *isa;\n";
357 Preamble += " int flags;\n";
358 Preamble += " char *str;\n";
359 Preamble += " long length;\n";
360 Preamble += "};\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000361 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000362 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
363 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000364 if (LangOpts.Microsoft) {
365 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000366 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000367 }
Chris Lattner12499682008-01-31 19:38:44 +0000368}
369
370
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000371//===----------------------------------------------------------------------===//
372// Top Level Driver Code
373//===----------------------------------------------------------------------===//
374
Steve Naroff44e81222008-04-14 22:03:09 +0000375void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000376 // Two cases: either the decl could be in the main file, or it could be in a
377 // #included file. If the former, rewrite it now. If the later, check to see
378 // if we rewrote the #include/#import.
379 SourceLocation Loc = D->getLocation();
380 Loc = SM->getLogicalLoc(Loc);
381
382 // If this is for a builtin, ignore it.
383 if (Loc.isInvalid()) return;
384
Steve Naroffe9780582007-10-23 23:50:29 +0000385 // Look for built-in declarations that we need to refer during the rewrite.
386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000387 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000388 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000389 // declared in <Foundation/NSString.h>
390 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
391 ConstantStringClassReference = FVD;
392 return;
393 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000394 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000395 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000396 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000397 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000398 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000399 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000400 } else if (ObjCForwardProtocolDecl *FP =
401 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000402 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000403 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000404 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000405 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000406 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000407}
408
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000409/// HandleDeclInMainFile - This is called for each top-level decl defined in the
410/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000411void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000412 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
413 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000414 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000415
Ted Kremenek42730c52008-01-07 19:49:32 +0000416 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000417 if (Stmt *Body = MD->getBody()) {
418 //Body->dump();
419 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000420 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000421 CurMethodDecl = 0;
422 }
Steve Naroff18c83382007-11-13 23:01:27 +0000423 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000424 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000425 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000426 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000427 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000428 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000429 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000430 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000431 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000432 if (VD->getInit())
433 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
434 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000435 // Nothing yet.
436}
437
Steve Naroff44e81222008-04-14 22:03:09 +0000438RewriteObjC::~RewriteObjC() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000439 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000440
441 // Rewrite tabs if we care.
442 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000443
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000444 if (Diags.hasErrorOccurred())
445 return;
446
447 // Create the output file.
448
449 std::ostream *OutFile;
450 if (OutFileName == "-") {
451 OutFile = llvm::cout.stream();
452 } else if (!OutFileName.empty()) {
453 OutFile = new std::ofstream(OutFileName.c_str(),
454 std::ios_base::binary|std::ios_base::out);
455 } else if (InFileName == "-") {
456 OutFile = llvm::cout.stream();
457 } else {
458 llvm::sys::Path Path(InFileName);
459 Path.eraseSuffix();
460 Path.appendSuffix("cpp");
461 OutFile = new std::ofstream(Path.toString().c_str(),
462 std::ios_base::binary|std::ios_base::out);
463 }
464
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000465 RewriteInclude();
466
Steve Narofffef037c2008-03-27 22:29:16 +0000467 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
468 Preamble.c_str(), Preamble.size(), false);
469
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000470 // Rewrite Objective-c meta data*
471 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000472 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000473
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000474 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
475 // we are done.
476 if (const RewriteBuffer *RewriteBuf =
477 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000478 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000479 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000480 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000481 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000482 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000483 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000484 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000485}
486
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000487//===----------------------------------------------------------------------===//
488// Syntactic (non-AST) Rewriting Code
489//===----------------------------------------------------------------------===//
490
Steve Naroff44e81222008-04-14 22:03:09 +0000491void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000492 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
493 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
494 const char *MainBufStart = MainBuf.first;
495 const char *MainBufEnd = MainBuf.second;
496 size_t ImportLen = strlen("import");
497 size_t IncludeLen = strlen("include");
498
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000499 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000500 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
501 if (*BufPtr == '#') {
502 if (++BufPtr == MainBufEnd)
503 return;
504 while (*BufPtr == ' ' || *BufPtr == '\t')
505 if (++BufPtr == MainBufEnd)
506 return;
507 if (!strncmp(BufPtr, "import", ImportLen)) {
508 // replace import with include
509 SourceLocation ImportLoc =
510 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000511 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000512 BufPtr += ImportLen;
513 }
514 }
515 }
Chris Lattner74db1682007-10-16 21:07:07 +0000516}
517
Steve Naroff44e81222008-04-14 22:03:09 +0000518void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000519 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
520 const char *MainBufStart = MainBuf.first;
521 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000522
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000523 // Loop over the whole file, looking for tabs.
524 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
525 if (*BufPtr != '\t')
526 continue;
527
528 // Okay, we found a tab. This tab will turn into at least one character,
529 // but it depends on which 'virtual column' it is in. Compute that now.
530 unsigned VCol = 0;
531 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
532 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
533 ++VCol;
534
535 // Okay, now that we know the virtual column, we know how many spaces to
536 // insert. We assume 8-character tab-stops.
537 unsigned Spaces = 8-(VCol & 7);
538
539 // Get the location of the tab.
540 SourceLocation TabLoc =
541 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
542
543 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000544 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000545 }
Chris Lattner569faa62007-10-11 18:38:32 +0000546}
547
548
Steve Naroff44e81222008-04-14 22:03:09 +0000549void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000550 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000551 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000552
553 // Get the start location and compute the semi location.
554 SourceLocation startLoc = ClassDecl->getLocation();
555 const char *startBuf = SM->getCharacterData(startLoc);
556 const char *semiPtr = strchr(startBuf, ';');
557
558 // Translate to typedef's that forward reference structs with the same name
559 // as the class. As a convenience, we include the original declaration
560 // as a comment.
561 std::string typedefString;
562 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000563 typedefString.append(startBuf, semiPtr-startBuf+1);
564 typedefString += "\n";
565 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000566 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000567 typedefString += "#ifndef _REWRITER_typedef_";
568 typedefString += ForwardDecl->getName();
569 typedefString += "\n";
570 typedefString += "#define _REWRITER_typedef_";
571 typedefString += ForwardDecl->getName();
572 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000573 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000574 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000575 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000576 }
577
578 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000579 ReplaceText(startLoc, semiPtr-startBuf+1,
580 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000581}
582
Steve Naroff44e81222008-04-14 22:03:09 +0000583void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000584 SourceLocation LocStart = Method->getLocStart();
585 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000586
Steve Naroff2ce399a2007-12-14 23:37:57 +0000587 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000588 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000589 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000590 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000591 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000592 }
593}
594
Steve Naroff44e81222008-04-14 22:03:09 +0000595void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000596{
Chris Lattnercffe3662008-03-16 21:23:50 +0000597 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000598 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000599 SourceLocation Loc = Property->getLocation();
600
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000601 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000602
603 // FIXME: handle properties that are declared across multiple lines.
604 }
605}
606
Steve Naroff44e81222008-04-14 22:03:09 +0000607void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000608 SourceLocation LocStart = CatDecl->getLocStart();
609
610 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000611 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000612
Ted Kremenek42730c52008-01-07 19:49:32 +0000613 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000614 E = CatDecl->instmeth_end(); I != E; ++I)
615 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000616 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000617 E = CatDecl->classmeth_end(); I != E; ++I)
618 RewriteMethodDeclaration(*I);
619
Steve Naroff667f1682007-10-30 13:30:57 +0000620 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000621 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000622}
623
Steve Naroff44e81222008-04-14 22:03:09 +0000624void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000625 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000626
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000627 SourceLocation LocStart = PDecl->getLocStart();
628
629 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000630 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000631
Ted Kremenek42730c52008-01-07 19:49:32 +0000632 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000633 E = PDecl->instmeth_end(); I != E; ++I)
634 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000635 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000636 E = PDecl->classmeth_end(); I != E; ++I)
637 RewriteMethodDeclaration(*I);
638
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000639 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000640 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000641 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000642
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000643 // Must comment out @optional/@required
644 const char *startBuf = SM->getCharacterData(LocStart);
645 const char *endBuf = SM->getCharacterData(LocEnd);
646 for (const char *p = startBuf; p < endBuf; p++) {
647 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
648 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000649 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000650 ReplaceText(OptionalLoc, strlen("@optional"),
651 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000652
653 }
654 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
655 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000656 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000657 ReplaceText(OptionalLoc, strlen("@required"),
658 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000659
660 }
661 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000662}
663
Steve Naroff44e81222008-04-14 22:03:09 +0000664void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000665 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000666 if (LocStart.isInvalid())
667 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000668 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000669 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000670}
671
Steve Naroff44e81222008-04-14 22:03:09 +0000672void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000673 std::string &ResultStr) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000674 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000675 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000676 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000677 ResultStr += "id";
Steve Naroff91044cf2008-07-16 14:40:40 +0000678 else if (OMD->getResultType()->isFunctionPointerType()) {
679 // needs special handling, since pointer-to-functions have special
680 // syntax (where a decaration models use).
681 QualType retType = OMD->getResultType();
682 if (const PointerType* PT = retType->getAsPointerType()) {
683 QualType PointeeTy = PT->getPointeeType();
684 if ((FPRetType = PointeeTy->getAsFunctionType())) {
685 ResultStr += FPRetType->getResultType().getAsString();
686 ResultStr += "(*";
687 }
688 }
689 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000690 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000691 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000692
693 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000694 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000695
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000696 if (OMD->isInstance())
697 NameStr += "_I_";
698 else
699 NameStr += "_C_";
700
701 NameStr += OMD->getClassInterface()->getName();
702 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000703
704 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 if (ObjCCategoryImplDecl *CID =
706 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000707 NameStr += CID->getName();
708 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000709 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000710 // Append selector names, replacing ':' with '_'
711 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000712 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000713 else {
714 std::string selString = OMD->getSelector().getName();
715 int len = selString.size();
716 for (int i = 0; i < len; i++)
717 if (selString[i] == ':')
718 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000719 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000720 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000721 // Remember this name for metadata emission
722 MethodInternalNames[OMD] = NameStr;
723 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724
725 // Rewrite arguments
726 ResultStr += "(";
727
728 // invisible arguments
729 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000730 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000731 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000732 if (!LangOpts.Microsoft) {
733 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
734 ResultStr += "struct ";
735 }
736 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000737 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000738 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000739 }
740 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000741 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000742
743 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000744 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000745 ResultStr += " _cmd";
746
747 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000748 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000749 ParmVarDecl *PDecl = OMD->getParamDecl(i);
750 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000751 if (PDecl->getType()->isObjCQualifiedIdType()) {
752 ResultStr += "id ";
753 ResultStr += PDecl->getName();
754 } else {
755 std::string Name = PDecl->getName();
756 PDecl->getType().getAsStringInternal(Name);
757 ResultStr += Name;
758 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000759 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000760 if (OMD->isVariadic())
761 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000762 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000763
Steve Naroff91044cf2008-07-16 14:40:40 +0000764 if (FPRetType) {
765 ResultStr += ")"; // close the precedence "scope" for "*".
766
767 // Now, emit the argument types (if any).
768 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
769 ResultStr += "(";
770 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
771 if (i) ResultStr += ", ";
772 std::string ParamStr = FT->getArgType(i).getAsString();
773 ResultStr += ParamStr;
774 }
775 if (FT->isVariadic()) {
776 if (FT->getNumArgs()) ResultStr += ", ";
777 ResultStr += "...";
778 }
779 ResultStr += ")";
780 } else {
781 ResultStr += "()";
782 }
783 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000784}
Steve Naroff44e81222008-04-14 22:03:09 +0000785void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000786 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
787 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000788
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000789 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000790 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000791 else
Chris Lattner6216f292008-01-31 19:42:41 +0000792 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000793
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000795 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
796 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000797 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000798 ObjCMethodDecl *OMD = *I;
799 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000800 SourceLocation LocStart = OMD->getLocStart();
801 SourceLocation LocEnd = OMD->getBody()->getLocStart();
802
803 const char *startBuf = SM->getCharacterData(LocStart);
804 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000805 ReplaceText(LocStart, endBuf-startBuf,
806 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000807 }
808
Ted Kremenek42730c52008-01-07 19:49:32 +0000809 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000810 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
811 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000812 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 ObjCMethodDecl *OMD = *I;
814 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000815 SourceLocation LocStart = OMD->getLocStart();
816 SourceLocation LocEnd = OMD->getBody()->getLocStart();
817
818 const char *startBuf = SM->getCharacterData(LocStart);
819 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000820 ReplaceText(LocStart, endBuf-startBuf,
821 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000822 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000823 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000824 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000825 else
Chris Lattner6216f292008-01-31 19:42:41 +0000826 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000827}
828
Steve Naroff44e81222008-04-14 22:03:09 +0000829void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000830 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000831 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000832 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000833 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000834 ResultStr += ClassDecl->getName();
835 ResultStr += "\n";
836 ResultStr += "#define _REWRITER_typedef_";
837 ResultStr += ClassDecl->getName();
838 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000839 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000840 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000841 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000842 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000843 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000844 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000845 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000846
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000847 RewriteProperties(ClassDecl->getNumPropertyDecl(),
848 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000849 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000850 E = ClassDecl->instmeth_end(); I != E; ++I)
851 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000852 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000853 E = ClassDecl->classmeth_end(); I != E; ++I)
854 RewriteMethodDeclaration(*I);
855
Steve Naroff1ccf4632007-10-30 03:43:13 +0000856 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000857 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000858}
859
Chris Lattner343c82b2008-05-23 20:40:52 +0000860Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
861 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000862 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000863 if (CurMethodDecl) {
864 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000865 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
866 // lookup which class implements the instance variable.
867 ObjCInterfaceDecl *clsDeclared = 0;
868 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
869 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
870
871 // Synthesize an explicit cast to gain access to the ivar.
872 std::string RecName = clsDeclared->getIdentifier()->getName();
873 RecName += "_IMPL";
874 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000875 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffa9636222008-05-08 17:52:16 +0000876 SourceLocation(), II, 0);
877 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
878 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
879 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
880 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000881 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
882 IV->getBase()->getLocEnd(),
883 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000884 if (IV->isFreeIvar() &&
885 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000886 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
887 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000888 ReplaceStmt(IV, ME);
889 delete IV;
890 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000891 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000892
893 ReplaceStmt(IV->getBase(), PE);
894 // Cannot delete IV->getBase(), since PE points to it.
895 // Replace the old base with the cast. This is important when doing
896 // embedded rewrites. For example, [newInv->_container addObject:0].
897 IV->setBase(PE);
898 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000899 }
Steve Naroffe6155362008-04-18 21:55:08 +0000900 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000901 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
902
903 // Explicit ivar refs need to have a cast inserted.
904 // FIXME: consider sharing some of this code with the code above.
905 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000906 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000907 // lookup which class implements the instance variable.
908 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000909 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000910 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
911
912 // Synthesize an explicit cast to gain access to the ivar.
913 std::string RecName = clsDeclared->getIdentifier()->getName();
914 RecName += "_IMPL";
915 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000916 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroffd8d30b92008-05-06 23:20:07 +0000917 SourceLocation(), II, 0);
918 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
919 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
920 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
921 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000922 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
923 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000924 ReplaceStmt(IV->getBase(), PE);
925 // Cannot delete IV->getBase(), since PE points to it.
926 // Replace the old base with the cast. This is important when doing
927 // embedded rewrites. For example, [newInv->_container addObject:0].
928 IV->setBase(PE);
929 return IV;
930 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000931 }
Steve Naroffe6155362008-04-18 21:55:08 +0000932 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000933}
934
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000935//===----------------------------------------------------------------------===//
936// Function Body / Expression rewriting
937//===----------------------------------------------------------------------===//
938
Steve Naroff44e81222008-04-14 22:03:09 +0000939Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000940 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
941 isa<DoStmt>(S) || isa<ForStmt>(S))
942 Stmts.push_back(S);
943 else if (isa<ObjCForCollectionStmt>(S)) {
944 Stmts.push_back(S);
945 ObjCBcLabelNo.push_back(++BcLabelCount);
946 }
947
Chris Lattner343c82b2008-05-23 20:40:52 +0000948 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000949
950 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000951 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
952 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000953 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000954 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000955 if (newStmt)
956 *CI = newStmt;
957 }
Steve Naroffe9780582007-10-23 23:50:29 +0000958
959 // Handle specific things.
960 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
961 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000962
963 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000964 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000965
966 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
967 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000968
Steve Naroff0add5d22007-11-03 11:27:19 +0000969 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
970 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000971
Steve Naroff71226032007-10-24 22:48:43 +0000972 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
973 // Before we rewrite it, put the original message expression in a comment.
974 SourceLocation startLoc = MessExpr->getLocStart();
975 SourceLocation endLoc = MessExpr->getLocEnd();
976
977 const char *startBuf = SM->getCharacterData(startLoc);
978 const char *endBuf = SM->getCharacterData(endLoc);
979
980 std::string messString;
981 messString += "// ";
982 messString.append(startBuf, endBuf-startBuf+1);
983 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000984
Chris Lattner6216f292008-01-31 19:42:41 +0000985 // FIXME: Missing definition of
986 // InsertText(clang::SourceLocation, char const*, unsigned int).
987 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000988 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000989 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000990 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000991 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000992
Ted Kremenek42730c52008-01-07 19:49:32 +0000993 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
994 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000995
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000996 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
997 return RewriteObjCSynchronizedStmt(StmtTry);
998
Ted Kremenek42730c52008-01-07 19:49:32 +0000999 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1000 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001001
1002 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1003 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001004
1005 if (ObjCForCollectionStmt *StmtForCollection =
1006 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +00001007 return RewriteObjCForCollectionStmt(StmtForCollection,
1008 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001009 if (BreakStmt *StmtBreakStmt =
1010 dyn_cast<BreakStmt>(S))
1011 return RewriteBreakStmt(StmtBreakStmt);
1012 if (ContinueStmt *StmtContinueStmt =
1013 dyn_cast<ContinueStmt>(S))
1014 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001015
1016 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls and cast exprs.
1017 if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
1018 RewriteObjCQualifiedInterfaceTypes(DS->getDecl());
1019 if (CastExpr *CE = dyn_cast<CastExpr>(S))
1020 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001021
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001022 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1023 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1024 assert(!Stmts.empty() && "Statement stack is empty");
1025 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1026 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1027 && "Statement stack mismatch");
1028 Stmts.pop_back();
1029 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001030#if 0
1031 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1032 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1033 // Get the new text.
1034 std::ostringstream Buf;
1035 Replacement->printPretty(Buf);
1036 const std::string &Str = Buf.str();
1037
1038 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +00001039 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001040 delete S;
1041 return Replacement;
1042 }
1043#endif
Chris Lattner0021f452007-10-24 16:57:36 +00001044 // Return this stmt unmodified.
1045 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001046}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001047
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001048/// SynthCountByEnumWithState - To print:
1049/// ((unsigned int (*)
1050/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1051/// (void *)objc_msgSend)((id)l_collection,
1052/// sel_registerName(
1053/// "countByEnumeratingWithState:objects:count:"),
1054/// &enumState,
1055/// (id *)items, (unsigned int)16)
1056///
Steve Naroff44e81222008-04-14 22:03:09 +00001057void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001058 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1059 "id *, unsigned int))(void *)objc_msgSend)";
1060 buf += "\n\t\t";
1061 buf += "((id)l_collection,\n\t\t";
1062 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1063 buf += "\n\t\t";
1064 buf += "&enumState, "
1065 "(id *)items, (unsigned int)16)";
1066}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001067
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001068/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1069/// statement to exit to its outer synthesized loop.
1070///
Steve Naroff44e81222008-04-14 22:03:09 +00001071Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001072 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1073 return S;
1074 // replace break with goto __break_label
1075 std::string buf;
1076
1077 SourceLocation startLoc = S->getLocStart();
1078 buf = "goto __break_label_";
1079 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001080 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001081
1082 return 0;
1083}
1084
1085/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1086/// statement to continue with its inner synthesized loop.
1087///
Steve Naroff44e81222008-04-14 22:03:09 +00001088Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001089 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1090 return S;
1091 // replace continue with goto __continue_label
1092 std::string buf;
1093
1094 SourceLocation startLoc = S->getLocStart();
1095 buf = "goto __continue_label_";
1096 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001097 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001098
1099 return 0;
1100}
1101
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001102/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001103/// It rewrites:
1104/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001105
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001106/// Into:
1107/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001108/// type elem;
1109/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001110/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001111/// id l_collection = (id)collection;
1112/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1113/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001114/// if (limit) {
1115/// unsigned long startMutations = *enumState.mutationsPtr;
1116/// do {
1117/// unsigned long counter = 0;
1118/// do {
1119/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001121/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001122/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001123/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001124/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001125/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1126/// objects:items count:16]);
1127/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001128/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001129/// }
1130/// else
1131/// elem = nil;
1132/// }
1133///
Steve Naroff44e81222008-04-14 22:03:09 +00001134Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001135 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001136 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1137 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1138 "ObjCForCollectionStmt Statement stack mismatch");
1139 assert(!ObjCBcLabelNo.empty() &&
1140 "ObjCForCollectionStmt - Label No stack empty");
1141
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001142 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001143 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001144 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001145 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001146 std::string buf;
1147 buf = "\n{\n\t";
1148 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1149 // type elem;
1150 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001151 elementTypeAsString = ElementType.getAsString();
1152 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001153 buf += " ";
1154 elementName = DS->getDecl()->getName();
1155 buf += elementName;
1156 buf += ";\n\t";
1157 }
Chris Lattner690c2872008-04-08 05:52:18 +00001158 else {
1159 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001160 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001161 elementTypeAsString = DR->getDecl()->getType().getAsString();
1162 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001163
1164 // struct __objcFastEnumerationState enumState = { 0 };
1165 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1166 // id items[16];
1167 buf += "id items[16];\n\t";
1168 // id l_collection = (id)
1169 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001170 // Find start location of 'collection' the hard way!
1171 const char *startCollectionBuf = startBuf;
1172 startCollectionBuf += 3; // skip 'for'
1173 startCollectionBuf = strchr(startCollectionBuf, '(');
1174 startCollectionBuf++; // skip '('
1175 // find 'in' and skip it.
1176 while (*startCollectionBuf != ' ' ||
1177 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1178 (*(startCollectionBuf+3) != ' ' &&
1179 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1180 startCollectionBuf++;
1181 startCollectionBuf += 3;
1182
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001183 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001184 ReplaceText(startLoc, startCollectionBuf - startBuf,
1185 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001186 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001187 SourceLocation rightParenLoc = S->getRParenLoc();
1188 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1189 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001190 buf = ";\n\t";
1191
1192 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1193 // objects:items count:16];
1194 // which is synthesized into:
1195 // unsigned int limit =
1196 // ((unsigned int (*)
1197 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1198 // (void *)objc_msgSend)((id)l_collection,
1199 // sel_registerName(
1200 // "countByEnumeratingWithState:objects:count:"),
1201 // (struct __objcFastEnumerationState *)&state,
1202 // (id *)items, (unsigned int)16);
1203 buf += "unsigned long limit =\n\t\t";
1204 SynthCountByEnumWithState(buf);
1205 buf += ";\n\t";
1206 /// if (limit) {
1207 /// unsigned long startMutations = *enumState.mutationsPtr;
1208 /// do {
1209 /// unsigned long counter = 0;
1210 /// do {
1211 /// if (startMutations != *enumState.mutationsPtr)
1212 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001213 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001214 buf += "if (limit) {\n\t";
1215 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1216 buf += "do {\n\t\t";
1217 buf += "unsigned long counter = 0;\n\t\t";
1218 buf += "do {\n\t\t\t";
1219 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1220 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1221 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001222 buf += " = (";
1223 buf += elementTypeAsString;
1224 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001225 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001226 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001227
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001228 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001229 /// } while (counter < limit);
1230 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1231 /// objects:items count:16]);
1232 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001233 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001234 /// }
1235 /// else
1236 /// elem = nil;
1237 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001238 ///
1239 buf = ";\n\t";
1240 buf += "__continue_label_";
1241 buf += utostr(ObjCBcLabelNo.back());
1242 buf += ": ;";
1243 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001244 buf += "} while (counter < limit);\n\t";
1245 buf += "} while (limit = ";
1246 SynthCountByEnumWithState(buf);
1247 buf += ");\n\t";
1248 buf += elementName;
1249 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001250 buf += "__break_label_";
1251 buf += utostr(ObjCBcLabelNo.back());
1252 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001253 buf += "}\n\t";
1254 buf += "else\n\t\t";
1255 buf += elementName;
1256 buf += " = nil;\n";
1257 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001258
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001259 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001260 if (isa<CompoundStmt>(S->getBody())) {
1261 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1262 InsertText(endBodyLoc, buf.c_str(), buf.size());
1263 } else {
1264 /* Need to treat single statements specially. For example:
1265 *
1266 * for (A *a in b) if (stuff()) break;
1267 * for (A *a in b) xxxyy;
1268 *
1269 * The following code simply scans ahead to the semi to find the actual end.
1270 */
1271 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1272 const char *semiBuf = strchr(stmtBuf, ';');
1273 assert(semiBuf && "Can't find ';'");
1274 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1275 InsertText(endBodyLoc, buf.c_str(), buf.size());
1276 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001277 Stmts.pop_back();
1278 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001279 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001280}
1281
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001282/// RewriteObjCSynchronizedStmt -
1283/// This routine rewrites @synchronized(expr) stmt;
1284/// into:
1285/// objc_sync_enter(expr);
1286/// @try stmt @finally { objc_sync_exit(expr); }
1287///
Steve Naroff44e81222008-04-14 22:03:09 +00001288Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001289 // Get the start location and compute the semi location.
1290 SourceLocation startLoc = S->getLocStart();
1291 const char *startBuf = SM->getCharacterData(startLoc);
1292
1293 assert((*startBuf == '@') && "bogus @synchronized location");
1294
1295 std::string buf;
1296 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001297 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001298 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1299 const char *endBuf = SM->getCharacterData(endLoc);
1300 endBuf++;
1301 const char *rparenBuf = strchr(endBuf, ')');
1302 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1303 buf = ");\n";
1304 // declare a new scope with two variables, _stack and _rethrow.
1305 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1306 buf += "int buf[18/*32-bit i386*/];\n";
1307 buf += "char *pointers[4];} _stack;\n";
1308 buf += "id volatile _rethrow = 0;\n";
1309 buf += "objc_exception_try_enter(&_stack);\n";
1310 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001311 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001312 startLoc = S->getSynchBody()->getLocEnd();
1313 startBuf = SM->getCharacterData(startLoc);
1314
1315 assert((*startBuf == '}') && "bogus @try block");
1316 SourceLocation lastCurlyLoc = startLoc;
1317 buf = "}\nelse {\n";
1318 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1319 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001320 buf += " objc_sync_exit(";
1321 std::ostringstream syncExprBuf;
1322 S->getSynchExpr()->printPretty(syncExprBuf);
1323 buf += syncExprBuf.str();
1324 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001325 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1326 buf += "}\n";
1327 buf += "}";
1328
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001329 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001330 return 0;
1331}
1332
Steve Naroff44e81222008-04-14 22:03:09 +00001333Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001334 // Get the start location and compute the semi location.
1335 SourceLocation startLoc = S->getLocStart();
1336 const char *startBuf = SM->getCharacterData(startLoc);
1337
1338 assert((*startBuf == '@') && "bogus @try location");
1339
1340 std::string buf;
1341 // declare a new scope with two variables, _stack and _rethrow.
1342 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1343 buf += "int buf[18/*32-bit i386*/];\n";
1344 buf += "char *pointers[4];} _stack;\n";
1345 buf += "id volatile _rethrow = 0;\n";
1346 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001347 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001348
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001349 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001350
1351 startLoc = S->getTryBody()->getLocEnd();
1352 startBuf = SM->getCharacterData(startLoc);
1353
1354 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001355
Steve Naroffe9f69842007-11-07 04:08:17 +00001356 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001357 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1358 if (catchList) {
1359 startLoc = startLoc.getFileLocWithOffset(1);
1360 buf = " /* @catch begin */ else {\n";
1361 buf += " id _caught = objc_exception_extract(&_stack);\n";
1362 buf += " objc_exception_try_enter (&_stack);\n";
1363 buf += " if (_setjmp(_stack.buf))\n";
1364 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1365 buf += " else { /* @catch continue */";
1366
1367 InsertText(startLoc, buf.c_str(), buf.size());
1368 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001369 bool sawIdTypedCatch = false;
1370 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001371 while (catchList) {
1372 Stmt *catchStmt = catchList->getCatchParamStmt();
1373
1374 if (catchList == S->getCatchStmts())
1375 buf = "if ("; // we are generating code for the first catch clause
1376 else
1377 buf = "else if (";
1378 startLoc = catchList->getLocStart();
1379 startBuf = SM->getCharacterData(startLoc);
1380
1381 assert((*startBuf == '@') && "bogus @catch location");
1382
1383 const char *lParenLoc = strchr(startBuf, '(');
1384
Steve Naroff397c4ce2008-02-01 22:08:12 +00001385 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001386 // Now rewrite the body...
1387 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001388 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1389 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001390 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1391 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001392 assert((*bodyBuf == '{') && "bogus @catch body location");
1393
1394 buf += "1) { id _tmp = _caught;";
1395 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1396 buf.c_str(), buf.size());
1397 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001398 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001399 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001400 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001401 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001402 sawIdTypedCatch = true;
1403 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001404 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001405
Ted Kremenek42730c52008-01-07 19:49:32 +00001406 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001407 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001408 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001409 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001410 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001411 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001412 }
1413 }
1414 // Now rewrite the body...
1415 lastCatchBody = catchList->getCatchBody();
1416 SourceLocation rParenLoc = catchList->getRParenLoc();
1417 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1418 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1419 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1420 assert((*rParenBuf == ')') && "bogus @catch paren location");
1421 assert((*bodyBuf == '{') && "bogus @catch body location");
1422
1423 buf = " = _caught;";
1424 // Here we replace ") {" with "= _caught;" (which initializes and
1425 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001426 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001427 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001428 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001429 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001430 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001431 catchList = catchList->getNextCatchStmt();
1432 }
1433 // Complete the catch list...
1434 if (lastCatchBody) {
1435 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001436 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1437 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001438 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1439 buf = " } } /* @catch end */\n";
1440
Chris Lattner6216f292008-01-31 19:42:41 +00001441 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001442
1443 // Set lastCurlyLoc
1444 lastCurlyLoc = lastCatchBody->getLocEnd();
1445 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001446 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001447 startLoc = finalStmt->getLocStart();
1448 startBuf = SM->getCharacterData(startLoc);
1449 assert((*startBuf == '@') && "bogus @finally start");
1450
1451 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001452 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001453
1454 Stmt *body = finalStmt->getFinallyBody();
1455 SourceLocation startLoc = body->getLocStart();
1456 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001457 assert(*SM->getCharacterData(startLoc) == '{' &&
1458 "bogus @finally body location");
1459 assert(*SM->getCharacterData(endLoc) == '}' &&
1460 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001461
1462 startLoc = startLoc.getFileLocWithOffset(1);
1463 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001464 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001465 endLoc = endLoc.getFileLocWithOffset(-1);
1466 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001467 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001468
1469 // Set lastCurlyLoc
1470 lastCurlyLoc = body->getLocEnd();
1471 }
1472 // Now emit the final closing curly brace...
1473 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1474 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001475 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001476 return 0;
1477}
1478
Steve Naroff44e81222008-04-14 22:03:09 +00001479Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001480 return 0;
1481}
1482
Steve Naroff44e81222008-04-14 22:03:09 +00001483Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001484 return 0;
1485}
1486
Chris Lattnerb1548372008-01-31 19:37:57 +00001487// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001488// the throw expression is typically a message expression that's already
1489// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001490Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001491 // Get the start location and compute the semi location.
1492 SourceLocation startLoc = S->getLocStart();
1493 const char *startBuf = SM->getCharacterData(startLoc);
1494
1495 assert((*startBuf == '@') && "bogus @throw location");
1496
1497 std::string buf;
1498 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001499 if (S->getThrowExpr())
1500 buf = "objc_exception_throw(";
1501 else // add an implicit argument
1502 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001503
1504 // handle "@ throw" correctly.
1505 const char *wBuf = strchr(startBuf, 'w');
1506 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1507 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1508
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001509 const char *semiBuf = strchr(startBuf, ';');
1510 assert((*semiBuf == ';') && "@throw: can't find ';'");
1511 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1512 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001513 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001514 return 0;
1515}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001516
Steve Naroff44e81222008-04-14 22:03:09 +00001517Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001518 // Create a new string expression.
1519 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001520 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001521 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1522 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001523 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1524 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001525 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001526 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001527
Chris Lattner4478db92007-11-30 22:53:43 +00001528 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001529 delete Exp;
1530 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001531}
1532
Steve Naroff44e81222008-04-14 22:03:09 +00001533Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001534 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1535 // Create a call to sel_registerName("selName").
1536 llvm::SmallVector<Expr*, 8> SelExprs;
1537 QualType argType = Context->getPointerType(Context->CharTy);
1538 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1539 Exp->getSelector().getName().size(),
1540 false, argType, SourceLocation(),
1541 SourceLocation()));
1542 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1543 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001544 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001545 delete Exp;
1546 return SelExp;
1547}
1548
Steve Naroff44e81222008-04-14 22:03:09 +00001549CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001550 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001551 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001552 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001553
1554 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001555 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001556
1557 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001558 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001559 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1560
1561 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001562
Steve Naroff71226032007-10-24 22:48:43 +00001563 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1564}
1565
Steve Naroffc8a92d12007-11-01 13:24:47 +00001566static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1567 const char *&startRef, const char *&endRef) {
1568 while (startBuf < endBuf) {
1569 if (*startBuf == '<')
1570 startRef = startBuf; // mark the start.
1571 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001572 if (startRef && *startRef == '<') {
1573 endRef = startBuf; // mark the end.
1574 return true;
1575 }
1576 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001577 }
1578 startBuf++;
1579 }
1580 return false;
1581}
1582
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001583static void scanToNextArgument(const char *&argRef) {
1584 int angle = 0;
1585 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1586 if (*argRef == '<')
1587 angle++;
1588 else if (*argRef == '>')
1589 angle--;
1590 argRef++;
1591 }
1592 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1593}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001594
Steve Naroff44e81222008-04-14 22:03:09 +00001595bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001596
Ted Kremenek42730c52008-01-07 19:49:32 +00001597 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001598 return true;
1599
Steve Naroffc8a92d12007-11-01 13:24:47 +00001600 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001601 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001602 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001603 return true; // we have "Class <Protocol> *".
1604 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001605 return false;
1606}
1607
Steve Naroffd06c88d2008-07-29 18:15:38 +00001608void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1609 QualType Type = E->getType();
1610 if (needToScanForQualifiers(Type)) {
1611 SourceLocation Loc = E->getLocStart();
1612 const char *startBuf = SM->getCharacterData(Loc);
1613 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1614 const char *startRef = 0, *endRef = 0;
1615 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1616 // Get the locations of the startRef, endRef.
1617 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1618 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1619 // Comment out the protocol references.
1620 InsertText(LessLoc, "/*", 2);
1621 InsertText(GreaterLoc, "*/", 2);
1622 }
1623 }
1624}
1625
Steve Naroff44e81222008-04-14 22:03:09 +00001626void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001627 SourceLocation Loc;
1628 QualType Type;
1629 const FunctionTypeProto *proto = 0;
1630 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1631 Loc = VD->getLocation();
1632 Type = VD->getType();
1633 }
1634 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1635 Loc = FD->getLocation();
1636 // Check for ObjC 'id' and class types that have been adorned with protocol
1637 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1638 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1639 assert(funcType && "missing function type");
1640 proto = dyn_cast<FunctionTypeProto>(funcType);
1641 if (!proto)
1642 return;
1643 Type = proto->getResultType();
1644 }
1645 else
1646 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001647
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001648 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001649 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001650
1651 const char *endBuf = SM->getCharacterData(Loc);
1652 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001653 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001654 startBuf--; // scan backward (from the decl location) for return type.
1655 const char *startRef = 0, *endRef = 0;
1656 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1657 // Get the locations of the startRef, endRef.
1658 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1659 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1660 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001661 InsertText(LessLoc, "/*", 2);
1662 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001663 }
1664 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001665 if (!proto)
1666 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001667 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001668 const char *startBuf = SM->getCharacterData(Loc);
1669 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001670 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1671 if (needToScanForQualifiers(proto->getArgType(i))) {
1672 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001673
Steve Naroffc8a92d12007-11-01 13:24:47 +00001674 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001675 // scan forward (from the decl location) for argument types.
1676 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001677 const char *startRef = 0, *endRef = 0;
1678 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1679 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001680 SourceLocation LessLoc =
1681 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1682 SourceLocation GreaterLoc =
1683 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001684 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001685 InsertText(LessLoc, "/*", 2);
1686 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001687 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001688 startBuf = ++endBuf;
1689 }
1690 else {
1691 while (*startBuf != ')' && *startBuf != ',')
1692 startBuf++; // scan forward (from the decl location) for argument types.
1693 startBuf++;
1694 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001695 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001696}
1697
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001698// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001699void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001700 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1701 llvm::SmallVector<QualType, 16> ArgTys;
1702 ArgTys.push_back(Context->getPointerType(
1703 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001704 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001705 &ArgTys[0], ArgTys.size(),
1706 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001707 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001708 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001709 SelGetUidIdent, getFuncType,
1710 FunctionDecl::Extern, false, 0);
1711}
1712
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001713// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001714void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001715 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1716 llvm::SmallVector<QualType, 16> ArgTys;
1717 ArgTys.push_back(Context->getPointerType(
1718 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001719 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001720 &ArgTys[0], ArgTys.size(),
1721 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001722 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001723 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001724 SelGetProtoIdent, getFuncType,
1725 FunctionDecl::Extern, false, 0);
1726}
1727
Steve Naroff44e81222008-04-14 22:03:09 +00001728void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001729 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001730 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001731 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001732 return;
1733 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001734 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001735}
1736
Steve Naroffbec4bf52008-03-11 17:37:02 +00001737// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001738void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001739 if (SuperContructorFunctionDecl)
1740 return;
1741 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1742 llvm::SmallVector<QualType, 16> ArgTys;
1743 QualType argT = Context->getObjCIdType();
1744 assert(!argT.isNull() && "Can't find 'id' type");
1745 ArgTys.push_back(argT);
1746 ArgTys.push_back(argT);
1747 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1748 &ArgTys[0], ArgTys.size(),
1749 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001750 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001751 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001752 msgSendIdent, msgSendType,
1753 FunctionDecl::Extern, false, 0);
1754}
1755
Steve Naroff02a82aa2007-10-30 23:14:51 +00001756// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001757void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001758 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1759 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001760 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001761 assert(!argT.isNull() && "Can't find 'id' type");
1762 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001763 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001764 assert(!argT.isNull() && "Can't find 'SEL' type");
1765 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001766 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001767 &ArgTys[0], ArgTys.size(),
1768 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001769 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001770 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001771 msgSendIdent, msgSendType,
1772 FunctionDecl::Extern, false, 0);
1773}
1774
Steve Naroff764c1ae2007-11-15 10:28:18 +00001775// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001776void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001777 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1778 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001779 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001780 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001781 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001782 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1783 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1784 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001785 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001786 assert(!argT.isNull() && "Can't find 'SEL' type");
1787 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001788 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001789 &ArgTys[0], ArgTys.size(),
1790 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001791 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001792 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001793 msgSendIdent, msgSendType,
1794 FunctionDecl::Extern, false, 0);
1795}
1796
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001797// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001798void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001799 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1800 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001801 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001802 assert(!argT.isNull() && "Can't find 'id' type");
1803 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001804 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001805 assert(!argT.isNull() && "Can't find 'SEL' type");
1806 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001808 &ArgTys[0], ArgTys.size(),
1809 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001810 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001811 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001812 msgSendIdent, msgSendType,
1813 FunctionDecl::Extern, false, 0);
1814}
1815
1816// SynthMsgSendSuperStretFunctionDecl -
1817// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001818void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001819 IdentifierInfo *msgSendIdent =
1820 &Context->Idents.get("objc_msgSendSuper_stret");
1821 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001822 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001823 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001824 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001825 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1826 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1827 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001828 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001829 assert(!argT.isNull() && "Can't find 'SEL' type");
1830 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001831 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001832 &ArgTys[0], ArgTys.size(),
1833 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001834 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001835 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001836 msgSendIdent, msgSendType,
1837 FunctionDecl::Extern, false, 0);
1838}
1839
Steve Naroff31316a12008-05-08 22:02:18 +00001840// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001841void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001842 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1843 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001844 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001845 assert(!argT.isNull() && "Can't find 'id' type");
1846 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001847 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001848 assert(!argT.isNull() && "Can't find 'SEL' type");
1849 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001850 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001851 &ArgTys[0], ArgTys.size(),
1852 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001853 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001854 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001855 msgSendIdent, msgSendType,
1856 FunctionDecl::Extern, false, 0);
1857}
1858
Steve Naroff02a82aa2007-10-30 23:14:51 +00001859// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001860void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001861 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1862 llvm::SmallVector<QualType, 16> ArgTys;
1863 ArgTys.push_back(Context->getPointerType(
1864 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001865 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001866 &ArgTys[0], ArgTys.size(),
1867 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001868 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001869 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001870 getClassIdent, getClassType,
1871 FunctionDecl::Extern, false, 0);
1872}
1873
Steve Naroff3b1caac2007-12-07 03:50:46 +00001874// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001875void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001876 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1877 llvm::SmallVector<QualType, 16> ArgTys;
1878 ArgTys.push_back(Context->getPointerType(
1879 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001880 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001881 &ArgTys[0], ArgTys.size(),
1882 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001883 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001884 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001885 getClassIdent, getClassType,
1886 FunctionDecl::Extern, false, 0);
1887}
1888
Steve Naroff44e81222008-04-14 22:03:09 +00001889Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001890 QualType strType = getConstantStringStructType();
1891
1892 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001893
1894 std::string tmpName = InFileName;
1895 unsigned i;
1896 for (i=0; i < tmpName.length(); i++) {
1897 char c = tmpName.at(i);
1898 // replace any non alphanumeric characters with '_'.
1899 if (!isalpha(c) && (c < '0' || c > '9'))
1900 tmpName[i] = '_';
1901 }
1902 S += tmpName;
1903 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001904 S += utostr(NumObjCStringLiterals++);
1905
Steve Narofffef037c2008-03-27 22:29:16 +00001906 Preamble += "static __NSConstantStringImpl " + S;
1907 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1908 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001909 // The pretty printer for StringLiteral handles escape characters properly.
1910 std::ostringstream prettyBuf;
1911 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001912 Preamble += prettyBuf.str();
1913 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001914 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001915 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001916
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001917 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001918 &Context->Idents.get(S.c_str()), strType,
1919 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001920 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1921 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1922 Context->getPointerType(DRE->getType()),
1923 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001924 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001925 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001926 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001927 delete Exp;
1928 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001929}
1930
Steve Naroff44e81222008-04-14 22:03:09 +00001931ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001932 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001933 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1934
Chris Lattner4423d372008-06-21 18:04:54 +00001935 if (PreDefinedExpr *PDE = dyn_cast<PreDefinedExpr>(recExpr))
1936 if (PDE->getIdentType() == PreDefinedExpr::ObjCSuper) {
1937 const PointerType *PT = PDE->getType()->getAsPointerType();
1938 assert(PT);
1939 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1940 return IT->getDecl();
1941 }
1942 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001943}
1944
1945// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001946QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001947 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001948 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001949 SourceLocation(),
1950 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001951 QualType FieldTypes[2];
1952
1953 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001954 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001955 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001956 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001957 // Create fields
1958 FieldDecl *FieldDecls[2];
1959
1960 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001961 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001962 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001963
1964 SuperStructDecl->defineBody(FieldDecls, 4);
1965 }
1966 return Context->getTagDeclType(SuperStructDecl);
1967}
1968
Steve Naroff44e81222008-04-14 22:03:09 +00001969QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001970 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001971 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001972 SourceLocation(),
1973 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001974 QualType FieldTypes[4];
1975
1976 // struct objc_object *receiver;
1977 FieldTypes[0] = Context->getObjCIdType();
1978 // int flags;
1979 FieldTypes[1] = Context->IntTy;
1980 // char *str;
1981 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1982 // long length;
1983 FieldTypes[3] = Context->LongTy;
1984 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001985 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001986
1987 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001988 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001989 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001990
1991 ConstantStringDecl->defineBody(FieldDecls, 4);
1992 }
1993 return Context->getTagDeclType(ConstantStringDecl);
1994}
1995
Steve Naroff44e81222008-04-14 22:03:09 +00001996Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001997 if (!SelGetUidFunctionDecl)
1998 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001999 if (!MsgSendFunctionDecl)
2000 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002001 if (!MsgSendSuperFunctionDecl)
2002 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002003 if (!MsgSendStretFunctionDecl)
2004 SynthMsgSendStretFunctionDecl();
2005 if (!MsgSendSuperStretFunctionDecl)
2006 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002007 if (!MsgSendFpretFunctionDecl)
2008 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002009 if (!GetClassFunctionDecl)
2010 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002011 if (!GetMetaClassFunctionDecl)
2012 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002013
Steve Naroff764c1ae2007-11-15 10:28:18 +00002014 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002015 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2016 // May need to use objc_msgSend_stret() as well.
2017 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00002018 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002019 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002020 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002021 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002022 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002023 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002024 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002025
Steve Naroff71226032007-10-24 22:48:43 +00002026 // Synthesize a call to objc_msgSend().
2027 llvm::SmallVector<Expr*, 8> MsgExprs;
2028 IdentifierInfo *clsName = Exp->getClassName();
2029
2030 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2031 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002032 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2033 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002034 if (!strcmp(clsName->getName(), "super")) {
2035 MsgSendFlavor = MsgSendSuperFunctionDecl;
2036 if (MsgSendStretFlavor)
2037 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2038 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2039
Ted Kremenek42730c52008-01-07 19:49:32 +00002040 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00002041 CurMethodDecl->getClassInterface()->getSuperClass();
2042
2043 llvm::SmallVector<Expr*, 4> InitExprs;
2044
2045 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002046 InitExprs.push_back(new DeclRefExpr(
2047 CurMethodDecl->getSelfDecl(),
2048 Context->getObjCIdType(),
2049 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002050 llvm::SmallVector<Expr*, 8> ClsExprs;
2051 QualType argType = Context->getPointerType(Context->CharTy);
2052 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2053 SuperDecl->getIdentifier()->getLength(),
2054 false, argType, SourceLocation(),
2055 SourceLocation()));
2056 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2057 &ClsExprs[0],
2058 ClsExprs.size());
2059 // To turn off a warning, type-cast to 'id'
2060 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002061 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002062 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2063 // struct objc_super
2064 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002065 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002066
Steve Naroffdee066b2008-03-11 18:14:26 +00002067 if (LangOpts.Microsoft) {
2068 SynthSuperContructorFunctionDecl();
2069 // Simulate a contructor call...
2070 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2071 superType, SourceLocation());
2072 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2073 superType, SourceLocation());
2074 } else {
2075 // (struct objc_super) { <exprs from above> }
2076 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2077 &InitExprs[0], InitExprs.size(),
2078 SourceLocation());
2079 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2080 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002081 // struct objc_super *
2082 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2083 Context->getPointerType(SuperRep->getType()),
2084 SourceLocation());
2085 MsgExprs.push_back(Unop);
2086 } else {
2087 llvm::SmallVector<Expr*, 8> ClsExprs;
2088 QualType argType = Context->getPointerType(Context->CharTy);
2089 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2090 clsName->getLength(),
2091 false, argType, SourceLocation(),
2092 SourceLocation()));
2093 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2094 &ClsExprs[0],
2095 ClsExprs.size());
2096 MsgExprs.push_back(Cls);
2097 }
Steve Naroff885e2122007-11-14 23:54:14 +00002098 } else { // instance message.
2099 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002100
Ted Kremenek42730c52008-01-07 19:49:32 +00002101 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002102 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002103 if (MsgSendStretFlavor)
2104 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002105 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2106
2107 llvm::SmallVector<Expr*, 4> InitExprs;
2108
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002109 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002110 new CastExpr(Context->getObjCIdType(),
Steve Naroff23528612008-07-16 22:35:27 +00002111 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2112 Context->getObjCIdType(),
2113 SourceLocation()),
2114 SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002115
2116 llvm::SmallVector<Expr*, 8> ClsExprs;
2117 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002118 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2119 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002120 false, argType, SourceLocation(),
2121 SourceLocation()));
2122 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002123 &ClsExprs[0],
2124 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002125 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002126 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002127 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002128 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002129 // struct objc_super
2130 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002131 Expr *SuperRep;
2132
2133 if (LangOpts.Microsoft) {
2134 SynthSuperContructorFunctionDecl();
2135 // Simulate a contructor call...
2136 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2137 superType, SourceLocation());
2138 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2139 superType, SourceLocation());
2140 } else {
2141 // (struct objc_super) { <exprs from above> }
2142 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2143 &InitExprs[0], InitExprs.size(),
2144 SourceLocation());
2145 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2146 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002147 // struct objc_super *
2148 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2149 Context->getPointerType(SuperRep->getType()),
2150 SourceLocation());
2151 MsgExprs.push_back(Unop);
2152 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002153 // Remove all type-casts because it may contain objc-style types; e.g.
2154 // Foo<Proto> *.
2155 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2156 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002157 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002158 MsgExprs.push_back(recExpr);
2159 }
Steve Naroff885e2122007-11-14 23:54:14 +00002160 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002161 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002162 llvm::SmallVector<Expr*, 8> SelExprs;
2163 QualType argType = Context->getPointerType(Context->CharTy);
2164 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2165 Exp->getSelector().getName().size(),
2166 false, argType, SourceLocation(),
2167 SourceLocation()));
2168 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2169 &SelExprs[0], SelExprs.size());
2170 MsgExprs.push_back(SelExp);
2171
2172 // Now push any user supplied arguments.
2173 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002174 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002175 // Make all implicit casts explicit...ICE comes in handy:-)
2176 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2177 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002178 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2179 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002180 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002181 }
2182 // Make id<P...> cast into an 'id' cast.
2183 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002184 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002185 while ((CE = dyn_cast<CastExpr>(userExpr)))
2186 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002187 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002188 userExpr, SourceLocation());
2189 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002190 }
Steve Naroff885e2122007-11-14 23:54:14 +00002191 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002192 // We've transferred the ownership to MsgExprs. Null out the argument in
2193 // the original expression, since we will delete it below.
2194 Exp->setArg(i, 0);
2195 }
Steve Naroff0744c472007-11-04 22:37:50 +00002196 // Generate the funky cast.
2197 CastExpr *cast;
2198 llvm::SmallVector<QualType, 8> ArgTypes;
2199 QualType returnType;
2200
2201 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002202 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2203 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2204 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002205 ArgTypes.push_back(Context->getObjCIdType());
2206 ArgTypes.push_back(Context->getObjCSelType());
2207 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002208 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002209 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002210 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2211 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002212 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002213 ArgTypes.push_back(t);
2214 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002215 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2216 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002217 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002218 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002219 }
2220 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002221 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002222
2223 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002224 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2225 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002226
2227 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2228 // If we don't do this cast, we get the following bizarre warning/note:
2229 // xx.m:13: warning: function called through a non-compatible type
2230 // xx.m:13: note: if this code is reached, the program will abort
2231 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2232 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002233
Steve Naroff0744c472007-11-04 22:37:50 +00002234 // Now do the "normal" pointer to function cast.
2235 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002236 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002237 // If we don't have a method decl, force a variadic cast.
2238 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002239 castType = Context->getPointerType(castType);
2240 cast = new CastExpr(castType, cast, SourceLocation());
2241
2242 // Don't forget the parens to enforce the proper binding.
2243 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2244
2245 const FunctionType *FT = msgSendType->getAsFunctionType();
2246 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2247 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002248 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002249 if (MsgSendStretFlavor) {
2250 // We have the method which returns a struct/union. Must also generate
2251 // call to objc_msgSend_stret and hang both varieties on a conditional
2252 // expression which dictate which one to envoke depending on size of
2253 // method's return type.
2254
2255 // Create a reference to the objc_msgSend_stret() declaration.
2256 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2257 SourceLocation());
2258 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2259 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2260 SourceLocation());
2261 // Now do the "normal" pointer to function cast.
2262 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002263 &ArgTypes[0], ArgTypes.size(),
2264 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002265 castType = Context->getPointerType(castType);
2266 cast = new CastExpr(castType, cast, SourceLocation());
2267
2268 // Don't forget the parens to enforce the proper binding.
2269 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2270
2271 FT = msgSendType->getAsFunctionType();
2272 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2273 FT->getResultType(), SourceLocation());
2274
2275 // Build sizeof(returnType)
2276 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2277 returnType, Context->getSizeType(),
2278 SourceLocation(), SourceLocation());
2279 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2280 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2281 // For X86 it is more complicated and some kind of target specific routine
2282 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002283 unsigned IntSize =
2284 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002285 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2286 Context->IntTy,
2287 SourceLocation());
2288 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2289 BinaryOperator::LE,
2290 Context->IntTy,
2291 SourceLocation());
2292 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2293 ConditionalOperator *CondExpr =
2294 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002295 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002296 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002297 return ReplacingStmt;
2298}
2299
Steve Naroff44e81222008-04-14 22:03:09 +00002300Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002301 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002302 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002303 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002304
Chris Lattner0021f452007-10-24 16:57:36 +00002305 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002306 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002307}
2308
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002309/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2310/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002311Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002312 if (!GetProtocolFunctionDecl)
2313 SynthGetProtocolFunctionDecl();
2314 // Create a call to objc_getProtocol("ProtocolName").
2315 llvm::SmallVector<Expr*, 8> ProtoExprs;
2316 QualType argType = Context->getPointerType(Context->CharTy);
2317 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2318 strlen(Exp->getProtocol()->getName()),
2319 false, argType, SourceLocation(),
2320 SourceLocation()));
2321 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2322 &ProtoExprs[0],
2323 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002324 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002325 delete Exp;
2326 return ProtoExp;
2327
2328}
2329
Steve Naroffef82b742008-05-31 14:15:04 +00002330bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2331 const char *endBuf) {
2332 while (startBuf < endBuf) {
2333 if (*startBuf == '#') {
2334 // Skip whitespace.
2335 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2336 ;
2337 if (!strncmp(startBuf, "if", strlen("if")) ||
2338 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2339 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2340 !strncmp(startBuf, "define", strlen("define")) ||
2341 !strncmp(startBuf, "undef", strlen("undef")) ||
2342 !strncmp(startBuf, "else", strlen("else")) ||
2343 !strncmp(startBuf, "elif", strlen("elif")) ||
2344 !strncmp(startBuf, "endif", strlen("endif")) ||
2345 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2346 !strncmp(startBuf, "include", strlen("include")) ||
2347 !strncmp(startBuf, "import", strlen("import")) ||
2348 !strncmp(startBuf, "include_next", strlen("include_next")))
2349 return true;
2350 }
2351 startBuf++;
2352 }
2353 return false;
2354}
2355
Ted Kremenek42730c52008-01-07 19:49:32 +00002356/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002357/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002358void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002359 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002360 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2361 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002362 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002363 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002364 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002365 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002366 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002367 SourceLocation LocStart = CDecl->getLocStart();
2368 SourceLocation LocEnd = CDecl->getLocEnd();
2369
2370 const char *startBuf = SM->getCharacterData(LocStart);
2371 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002372
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002373 // If no ivars and no root or if its root, directly or indirectly,
2374 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002375 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2376 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002377 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002378 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002379 return;
2380 }
2381
2382 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002383 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002384 Result += "\nstruct ";
2385 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002386 if (LangOpts.Microsoft)
2387 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002388
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002389 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002390 const char *cursor = strchr(startBuf, '{');
2391 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002392 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002393 // If the buffer contains preprocessor directives, we do more fine-grained
2394 // rewrites. This is intended to fix code that looks like (which occurs in
2395 // NSURL.h, for example):
2396 //
2397 // #ifdef XYZ
2398 // @interface Foo : NSObject
2399 // #else
2400 // @interface FooBar : NSObject
2401 // #endif
2402 // {
2403 // int i;
2404 // }
2405 // @end
2406 //
2407 // This clause is segregated to avoid breaking the common case.
2408 if (BufferContainsPPDirectives(startBuf, cursor)) {
2409 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2410 CDecl->getClassLoc();
2411 const char *endHeader = SM->getCharacterData(L);
2412 endHeader += Lexer::MeasureTokenLength(L, *SM);
2413
Chris Lattner8bcb5252008-07-21 18:19:38 +00002414 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002415 // advance to the end of the referenced protocols.
2416 while (endHeader < cursor && *endHeader != '>') endHeader++;
2417 endHeader++;
2418 }
2419 // rewrite the original header
2420 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2421 } else {
2422 // rewrite the original header *without* disturbing the '{'
2423 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2424 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002425 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002426 Result = "\n struct ";
2427 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002428 Result += "_IMPL ";
2429 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002430 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002431
2432 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002433 SourceLocation OnePastCurly =
2434 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2435 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002436 }
2437 cursor++; // past '{'
2438
2439 // Now comment out any visibility specifiers.
2440 while (cursor < endBuf) {
2441 if (*cursor == '@') {
2442 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002443 // Skip whitespace.
2444 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2445 /*scan*/;
2446
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002447 // FIXME: presence of @public, etc. inside comment results in
2448 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002449 if (!strncmp(cursor, "public", strlen("public")) ||
2450 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002451 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002452 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002453 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002454 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002455 // FIXME: If there are cases where '<' is used in ivar declaration part
2456 // of user code, then scan the ivar list and use needToScanForQualifiers
2457 // for type checking.
2458 else if (*cursor == '<') {
2459 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002460 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002461 cursor = strchr(cursor, '>');
2462 cursor++;
2463 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002464 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002465 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002466 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002467 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002468 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002469 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002470 } else { // we don't have any instance variables - insert super struct.
2471 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2472 Result += " {\n struct ";
2473 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002474 Result += "_IMPL ";
2475 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002476 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002477 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002478 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002479 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002480 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002481 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002482}
2483
Ted Kremenek42730c52008-01-07 19:49:32 +00002484// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002485/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002486void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002487 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002488 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002489 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002490 const char *ClassName,
2491 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002492 if (MethodBegin == MethodEnd) return;
2493
Fariborz Jahanian04455192007-10-22 21:41:37 +00002494 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002495 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002496 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002497 SEL _cmd;
2498 char *method_types;
2499 void *_imp;
2500 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002501 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002502 Result += "\nstruct _objc_method {\n";
2503 Result += "\tSEL _cmd;\n";
2504 Result += "\tchar *method_types;\n";
2505 Result += "\tvoid *_imp;\n";
2506 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002507
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002508 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002509 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002510
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002511 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002512
2513 /* struct {
2514 struct _objc_method_list *next_method;
2515 int method_count;
2516 struct _objc_method method_list[];
2517 }
2518 */
2519 Result += "\nstatic struct {\n";
2520 Result += "\tstruct _objc_method_list *next_method;\n";
2521 Result += "\tint method_count;\n";
2522 Result += "\tstruct _objc_method method_list[";
2523 Result += utostr(MethodEnd-MethodBegin);
2524 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002525 Result += prefix;
2526 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2527 Result += "_METHODS_";
2528 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002529 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002530 Result += IsInstanceMethod ? "inst" : "cls";
2531 Result += "_meth\")))= ";
2532 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002533
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002534 Result += "\t,{{(SEL)\"";
2535 Result += (*MethodBegin)->getSelector().getName().c_str();
2536 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002537 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002538 Result += "\", \"";
2539 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002540 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002541 Result += MethodInternalNames[*MethodBegin];
2542 Result += "}\n";
2543 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2544 Result += "\t ,{(SEL)\"";
2545 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002546 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002547 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002548 Result += "\", \"";
2549 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002550 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002551 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002552 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002553 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002554 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002555}
2556
Ted Kremenek42730c52008-01-07 19:49:32 +00002557/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002558void RewriteObjC::
2559RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2560 const char *prefix,
2561 const char *ClassName,
2562 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002563 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002564 if (Protocols.empty()) return;
2565
2566 for (unsigned i = 0; i != Protocols.size(); i++) {
2567 ObjCProtocolDecl *PDecl = Protocols[i];
2568 // Output struct protocol_methods holder of method selector and type.
2569 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2570 /* struct protocol_methods {
2571 SEL _cmd;
2572 char *method_types;
2573 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002574 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002575 Result += "\nstruct protocol_methods {\n";
2576 Result += "\tSEL _cmd;\n";
2577 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002578 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002579
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002580 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002581 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002582 // Do not synthesize the protocol more than once.
2583 if (ObjCSynthesizedProtocols.count(PDecl))
2584 continue;
2585
2586 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2587 unsigned NumMethods = PDecl->getNumInstanceMethods();
2588 /* struct _objc_protocol_method_list {
2589 int protocol_method_count;
2590 struct protocol_methods protocols[];
2591 }
2592 */
2593 Result += "\nstatic struct {\n";
2594 Result += "\tint protocol_method_count;\n";
2595 Result += "\tstruct protocol_methods protocols[";
2596 Result += utostr(NumMethods);
2597 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2598 Result += PDecl->getName();
2599 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2600 "{\n\t" + utostr(NumMethods) + "\n";
2601
2602 // Output instance methods declared in this protocol.
2603 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2604 E = PDecl->instmeth_end(); I != E; ++I) {
2605 if (I == PDecl->instmeth_begin())
2606 Result += "\t ,{{(SEL)\"";
2607 else
2608 Result += "\t ,{(SEL)\"";
2609 Result += (*I)->getSelector().getName().c_str();
2610 std::string MethodTypeString;
2611 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2612 Result += "\", \"";
2613 Result += MethodTypeString;
2614 Result += "\"}\n";
2615 }
2616 Result += "\t }\n};\n";
2617 }
2618
2619 // Output class methods declared in this protocol.
2620 int NumMethods = PDecl->getNumClassMethods();
2621 if (NumMethods > 0) {
2622 /* struct _objc_protocol_method_list {
2623 int protocol_method_count;
2624 struct protocol_methods protocols[];
2625 }
2626 */
2627 Result += "\nstatic struct {\n";
2628 Result += "\tint protocol_method_count;\n";
2629 Result += "\tstruct protocol_methods protocols[";
2630 Result += utostr(NumMethods);
2631 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2632 Result += PDecl->getName();
2633 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2634 "{\n\t";
2635 Result += utostr(NumMethods);
2636 Result += "\n";
2637
2638 // Output instance methods declared in this protocol.
2639 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2640 E = PDecl->classmeth_end(); I != E; ++I) {
2641 if (I == PDecl->classmeth_begin())
2642 Result += "\t ,{{(SEL)\"";
2643 else
2644 Result += "\t ,{(SEL)\"";
2645 Result += (*I)->getSelector().getName().c_str();
2646 std::string MethodTypeString;
2647 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2648 Result += "\", \"";
2649 Result += MethodTypeString;
2650 Result += "\"}\n";
2651 }
2652 Result += "\t }\n};\n";
2653 }
2654
2655 // Output:
2656 /* struct _objc_protocol {
2657 // Objective-C 1.0 extensions
2658 struct _objc_protocol_extension *isa;
2659 char *protocol_name;
2660 struct _objc_protocol **protocol_list;
2661 struct _objc_protocol_method_list *instance_methods;
2662 struct _objc_protocol_method_list *class_methods;
2663 };
Steve Naroff27429432008-03-12 01:06:30 +00002664 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002665 static bool objc_protocol = false;
2666 if (!objc_protocol) {
2667 Result += "\nstruct _objc_protocol {\n";
2668 Result += "\tstruct _objc_protocol_extension *isa;\n";
2669 Result += "\tchar *protocol_name;\n";
2670 Result += "\tstruct _objc_protocol **protocol_list;\n";
2671 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2672 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2673 Result += "};\n";
2674
2675 objc_protocol = true;
2676 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002677
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002678 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2679 Result += PDecl->getName();
2680 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2681 "{\n\t0, \"";
2682 Result += PDecl->getName();
2683 Result += "\", 0, ";
2684 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2685 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2686 Result += PDecl->getName();
2687 Result += ", ";
2688 }
2689 else
2690 Result += "0, ";
2691 if (PDecl->getNumClassMethods() > 0) {
2692 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2693 Result += PDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002694 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002695 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002696 else
2697 Result += "0\n";
2698 Result += "};\n";
2699
2700 // Mark this protocol as having been generated.
2701 if (!ObjCSynthesizedProtocols.insert(PDecl))
2702 assert(false && "protocol already synthesized");
2703 }
2704 // Output the top lovel protocol meta-data for the class.
2705 /* struct _objc_protocol_list {
2706 struct _objc_protocol_list *next;
2707 int protocol_count;
2708 struct _objc_protocol *class_protocols[];
2709 }
2710 */
2711 Result += "\nstatic struct {\n";
2712 Result += "\tstruct _objc_protocol_list *next;\n";
2713 Result += "\tint protocol_count;\n";
2714 Result += "\tstruct _objc_protocol *class_protocols[";
2715 Result += utostr(Protocols.size());
2716 Result += "];\n} _OBJC_";
2717 Result += prefix;
2718 Result += "_PROTOCOLS_";
2719 Result += ClassName;
2720 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2721 "{\n\t0, ";
2722 Result += utostr(Protocols.size());
2723 Result += "\n";
2724
2725 Result += "\t,{&_OBJC_PROTOCOL_";
2726 Result += Protocols[0]->getName();
2727 Result += " \n";
2728
2729 for (unsigned i = 1; i != Protocols.size(); i++) {
2730 Result += "\t ,&_OBJC_PROTOCOL_";
2731 Result += Protocols[i]->getName();
2732 Result += "\n";
2733 }
2734 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002735}
2736
Ted Kremenek42730c52008-01-07 19:49:32 +00002737/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002738/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002739void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002740 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002741 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002742 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002743 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002744 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2745 CDecl = CDecl->getNextClassCategory())
2746 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2747 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002748
Chris Lattnera661a4d2007-12-23 01:40:15 +00002749 std::string FullCategoryName = ClassDecl->getName();
2750 FullCategoryName += '_';
2751 FullCategoryName += IDecl->getName();
2752
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002753 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002754 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002755 true, "CATEGORY_", FullCategoryName.c_str(),
2756 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002757
2758 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002759 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002760 false, "CATEGORY_", FullCategoryName.c_str(),
2761 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002762
2763 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002764 // Null CDecl is case of a category implementation with no category interface
2765 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002766 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002767 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002768
2769 /* struct _objc_category {
2770 char *category_name;
2771 char *class_name;
2772 struct _objc_method_list *instance_methods;
2773 struct _objc_method_list *class_methods;
2774 struct _objc_protocol_list *protocols;
2775 // Objective-C 1.0 extensions
2776 uint32_t size; // sizeof (struct _objc_category)
2777 struct _objc_property_list *instance_properties; // category's own
2778 // @property decl.
2779 };
2780 */
2781
2782 static bool objc_category = false;
2783 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002784 Result += "\nstruct _objc_category {\n";
2785 Result += "\tchar *category_name;\n";
2786 Result += "\tchar *class_name;\n";
2787 Result += "\tstruct _objc_method_list *instance_methods;\n";
2788 Result += "\tstruct _objc_method_list *class_methods;\n";
2789 Result += "\tstruct _objc_protocol_list *protocols;\n";
2790 Result += "\tunsigned int size;\n";
2791 Result += "\tstruct _objc_property_list *instance_properties;\n";
2792 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002793 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002794 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002795 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2796 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002797 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002798 Result += IDecl->getName();
2799 Result += "\"\n\t, \"";
2800 Result += ClassDecl->getName();
2801 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002802
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002803 if (IDecl->getNumInstanceMethods() > 0) {
2804 Result += "\t, (struct _objc_method_list *)"
2805 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2806 Result += FullCategoryName;
2807 Result += "\n";
2808 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002809 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002810 Result += "\t, 0\n";
2811 if (IDecl->getNumClassMethods() > 0) {
2812 Result += "\t, (struct _objc_method_list *)"
2813 "&_OBJC_CATEGORY_CLASS_METHODS_";
2814 Result += FullCategoryName;
2815 Result += "\n";
2816 }
2817 else
2818 Result += "\t, 0\n";
2819
Chris Lattner0be08822008-07-21 21:32:27 +00002820 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002821 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2822 Result += FullCategoryName;
2823 Result += "\n";
2824 }
2825 else
2826 Result += "\t, 0\n";
2827 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002828}
2829
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002830/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2831/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002832void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002833 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002834 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002835 if (ivar->isBitField()) {
2836 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2837 // place all bitfields at offset 0.
2838 Result += "0";
2839 } else {
2840 Result += "__OFFSETOFIVAR__(struct ";
2841 Result += IDecl->getName();
2842 if (LangOpts.Microsoft)
2843 Result += "_IMPL";
2844 Result += ", ";
2845 Result += ivar->getName();
2846 Result += ")";
2847 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002848}
2849
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002850//===----------------------------------------------------------------------===//
2851// Meta Data Emission
2852//===----------------------------------------------------------------------===//
2853
Steve Naroff44e81222008-04-14 22:03:09 +00002854void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002855 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002856 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002857
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002858 // Explictly declared @interface's are already synthesized.
2859 if (CDecl->ImplicitInterfaceDecl()) {
2860 // FIXME: Implementation of a class with no @interface (legacy) doese not
2861 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002862 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002863 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002864
Chris Lattnerc7b06752007-12-12 07:56:42 +00002865 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002866 unsigned NumIvars = !IDecl->ivar_empty()
2867 ? IDecl->ivar_size()
2868 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002869 if (NumIvars > 0) {
2870 static bool objc_ivar = false;
2871 if (!objc_ivar) {
2872 /* struct _objc_ivar {
2873 char *ivar_name;
2874 char *ivar_type;
2875 int ivar_offset;
2876 };
2877 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002878 Result += "\nstruct _objc_ivar {\n";
2879 Result += "\tchar *ivar_name;\n";
2880 Result += "\tchar *ivar_type;\n";
2881 Result += "\tint ivar_offset;\n";
2882 Result += "};\n";
2883
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002884 objc_ivar = true;
2885 }
2886
Steve Naroffc723eec2008-03-11 00:12:29 +00002887 /* struct {
2888 int ivar_count;
2889 struct _objc_ivar ivar_list[nIvars];
2890 };
2891 */
2892 Result += "\nstatic struct {\n";
2893 Result += "\tint ivar_count;\n";
2894 Result += "\tstruct _objc_ivar ivar_list[";
2895 Result += utostr(NumIvars);
2896 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002897 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002898 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002899 "{\n\t";
2900 Result += utostr(NumIvars);
2901 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002902
Ted Kremenek42730c52008-01-07 19:49:32 +00002903 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002904 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002905 IVI = IDecl->ivar_begin();
2906 IVE = IDecl->ivar_end();
2907 } else {
2908 IVI = CDecl->ivar_begin();
2909 IVE = CDecl->ivar_end();
2910 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002911 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002912 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002913 Result += "\", \"";
2914 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002915 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2916 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002917 Result += StrEncoding;
2918 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002919 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002920 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002921 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002922 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002923 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002924 Result += "\", \"";
2925 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002926 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2927 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002928 Result += StrEncoding;
2929 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002930 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002931 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002932 }
2933
2934 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002935 }
2936
2937 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002938 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002939 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002940
2941 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002942 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002943 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002944
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002945 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00002946 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002947 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002948
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002949
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002950 // Declaration of class/meta-class metadata
2951 /* struct _objc_class {
2952 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002953 const char *super_class_name;
2954 char *name;
2955 long version;
2956 long info;
2957 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002958 struct _objc_ivar_list *ivars;
2959 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002960 struct objc_cache *cache;
2961 struct objc_protocol_list *protocols;
2962 const char *ivar_layout;
2963 struct _objc_class_ext *ext;
2964 };
2965 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002966 static bool objc_class = false;
2967 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002968 Result += "\nstruct _objc_class {\n";
2969 Result += "\tstruct _objc_class *isa;\n";
2970 Result += "\tconst char *super_class_name;\n";
2971 Result += "\tchar *name;\n";
2972 Result += "\tlong version;\n";
2973 Result += "\tlong info;\n";
2974 Result += "\tlong instance_size;\n";
2975 Result += "\tstruct _objc_ivar_list *ivars;\n";
2976 Result += "\tstruct _objc_method_list *methods;\n";
2977 Result += "\tstruct objc_cache *cache;\n";
2978 Result += "\tstruct _objc_protocol_list *protocols;\n";
2979 Result += "\tconst char *ivar_layout;\n";
2980 Result += "\tstruct _objc_class_ext *ext;\n";
2981 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002982 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002983 }
2984
2985 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002986 ObjCInterfaceDecl *RootClass = 0;
2987 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002988 while (SuperClass) {
2989 RootClass = SuperClass;
2990 SuperClass = SuperClass->getSuperClass();
2991 }
2992 SuperClass = CDecl->getSuperClass();
2993
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002994 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2995 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002996 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002997 "{\n\t(struct _objc_class *)\"";
2998 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2999 Result += "\"";
3000
3001 if (SuperClass) {
3002 Result += ", \"";
3003 Result += SuperClass->getName();
3004 Result += "\", \"";
3005 Result += CDecl->getName();
3006 Result += "\"";
3007 }
3008 else {
3009 Result += ", 0, \"";
3010 Result += CDecl->getName();
3011 Result += "\"";
3012 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003013 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003014 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003015 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00003016 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003017 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00003018 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003019 Result += "\n";
3020 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003021 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003022 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003023 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003024 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003025 Result += CDecl->getName();
3026 Result += ",0,0\n";
3027 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003028 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003029 Result += "\t,0,0,0,0\n";
3030 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003031
3032 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003033 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3034 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003035 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003036 "{\n\t&_OBJC_METACLASS_";
3037 Result += CDecl->getName();
3038 if (SuperClass) {
3039 Result += ", \"";
3040 Result += SuperClass->getName();
3041 Result += "\", \"";
3042 Result += CDecl->getName();
3043 Result += "\"";
3044 }
3045 else {
3046 Result += ", 0, \"";
3047 Result += CDecl->getName();
3048 Result += "\"";
3049 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003050 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003051 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003052 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003053 Result += ",0";
3054 else {
3055 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003056 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003057 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003058 if (LangOpts.Microsoft)
3059 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003060 Result += ")";
3061 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003062 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003063 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003064 Result += CDecl->getName();
3065 Result += "\n\t";
3066 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003067 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003068 Result += ",0";
3069 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003070 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003071 Result += CDecl->getName();
3072 Result += ", 0\n\t";
3073 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003074 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003075 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003076 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003077 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003078 Result += CDecl->getName();
3079 Result += ", 0,0\n";
3080 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003081 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003082 Result += ",0,0,0\n";
3083 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003084}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003085
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003086/// RewriteImplementations - This routine rewrites all method implementations
3087/// and emits meta-data.
3088
Steve Naroff44e81222008-04-14 22:03:09 +00003089void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003090 int ClsDefCount = ClassImplementation.size();
3091 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003092
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003093 if (ClsDefCount == 0 && CatDefCount == 0)
3094 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003095 // Rewrite implemented methods
3096 for (int i = 0; i < ClsDefCount; i++)
3097 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003098
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003099 for (int i = 0; i < CatDefCount; i++)
3100 RewriteImplementationDecl(CategoryImplementation[i]);
3101
Steve Naroff5bf10222008-05-07 21:23:49 +00003102 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003103 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003104 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003105 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003106 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003107
3108 // For each implemented category, write out all its meta data.
3109 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003110 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003111
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003112 // Write objc_symtab metadata
3113 /*
3114 struct _objc_symtab
3115 {
3116 long sel_ref_cnt;
3117 SEL *refs;
3118 short cls_def_cnt;
3119 short cat_def_cnt;
3120 void *defs[cls_def_cnt + cat_def_cnt];
3121 };
3122 */
3123
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003124 Result += "\nstruct _objc_symtab {\n";
3125 Result += "\tlong sel_ref_cnt;\n";
3126 Result += "\tSEL *refs;\n";
3127 Result += "\tshort cls_def_cnt;\n";
3128 Result += "\tshort cat_def_cnt;\n";
3129 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3130 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003131
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003132 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003133 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003134 Result += "\t0, 0, " + utostr(ClsDefCount)
3135 + ", " + utostr(CatDefCount) + "\n";
3136 for (int i = 0; i < ClsDefCount; i++) {
3137 Result += "\t,&_OBJC_CLASS_";
3138 Result += ClassImplementation[i]->getName();
3139 Result += "\n";
3140 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003141
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003142 for (int i = 0; i < CatDefCount; i++) {
3143 Result += "\t,&_OBJC_CATEGORY_";
3144 Result += CategoryImplementation[i]->getClassInterface()->getName();
3145 Result += "_";
3146 Result += CategoryImplementation[i]->getName();
3147 Result += "\n";
3148 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003149
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003150 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003151
3152 // Write objc_module metadata
3153
3154 /*
3155 struct _objc_module {
3156 long version;
3157 long size;
3158 const char *name;
3159 struct _objc_symtab *symtab;
3160 }
3161 */
3162
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003163 Result += "\nstruct _objc_module {\n";
3164 Result += "\tlong version;\n";
3165 Result += "\tlong size;\n";
3166 Result += "\tconst char *name;\n";
3167 Result += "\tstruct _objc_symtab *symtab;\n";
3168 Result += "};\n\n";
3169 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003170 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003171 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3172 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003173 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003174
3175 if (LangOpts.Microsoft) {
3176 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003177 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003178 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3179 Result += "&_OBJC_MODULES;\n";
3180 Result += "#pragma data_seg(pop)\n\n";
3181 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003182}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003183
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003184
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003185
3186