blob: f679e554d092d4a962c12e693e05a46f8ef84be9 [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 Naroffc8a92d12007-11-01 13:24:47 +0000166 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000167 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000168 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000169 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000170 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000171
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000172 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000173 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000174 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000175 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000176 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000177 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000178 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000179 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000180 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000181 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000182 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
183 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
184 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000185 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
186 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000187 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
188 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000189 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000190 Stmt *RewriteBreakStmt(BreakStmt *S);
191 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000192 void SynthCountByEnumWithState(std::string &buf);
193
Steve Naroff02a82aa2007-10-30 23:14:51 +0000194 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000195 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000196 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000197 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000198 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000199 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000200 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000201 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000202 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000203 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000204
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000205 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000206 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000207 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000208
Ted Kremenek42730c52008-01-07 19:49:32 +0000209 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000210 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000211
Ted Kremenek42730c52008-01-07 19:49:32 +0000212 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
213 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000214 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000215 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000216 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000217 const char *ClassName,
218 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000219
Ted Kremenek42730c52008-01-07 19:49:32 +0000220 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000221 int NumProtocols,
222 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000223 const char *ClassName,
224 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000226 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
228 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000229 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000230 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000231 };
232}
233
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000234static bool IsHeaderFile(const std::string &Filename) {
235 std::string::size_type DotPos = Filename.rfind('.');
236
237 if (DotPos == std::string::npos) {
238 // no file extension
239 return false;
240 }
241
242 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
243 // C header: .h
244 // C++ header: .hh or .H;
245 return Ext == "h" || Ext == "hh" || Ext == "H";
246}
247
Steve Naroff44e81222008-04-14 22:03:09 +0000248RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000249 Diagnostic &D, const LangOptions &LOpts)
250 : Diags(D), LangOpts(LOpts) {
251 IsHeader = IsHeaderFile(inFile);
252 InFileName = inFile;
253 OutFileName = outFile;
254 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
255 "rewriting sub-expression within a macro (may not be correct)");
256}
257
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000258ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000259 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000260 Diagnostic &Diags,
261 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000262 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000263}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000264
Steve Naroff44e81222008-04-14 22:03:09 +0000265void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000266 Context = &context;
267 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000268 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000269 MsgSendFunctionDecl = 0;
270 MsgSendSuperFunctionDecl = 0;
271 MsgSendStretFunctionDecl = 0;
272 MsgSendSuperStretFunctionDecl = 0;
273 MsgSendFpretFunctionDecl = 0;
274 GetClassFunctionDecl = 0;
275 GetMetaClassFunctionDecl = 0;
276 SelGetUidFunctionDecl = 0;
277 CFStringFunctionDecl = 0;
278 GetProtocolFunctionDecl = 0;
279 ConstantStringClassReference = 0;
280 NSStringRecord = 0;
281 CurMethodDecl = 0;
282 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000283 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000284 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000285 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000286 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000287
288 // Get the ID and start/end of the main file.
289 MainFileID = SM->getMainFileID();
290 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
291 MainFileStart = MainBuf->getBufferStart();
292 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000293
Chris Lattner12499682008-01-31 19:38:44 +0000294 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000295
Chris Lattner12499682008-01-31 19:38:44 +0000296 // declaring objc_selector outside the parameter list removes a silly
297 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000298 if (IsHeader)
299 Preamble = "#pragma once\n";
300 Preamble += "struct objc_selector; struct objc_class;\n";
301 Preamble += "#ifndef OBJC_SUPER\n";
302 Preamble += "struct objc_super { struct objc_object *object; ";
303 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000304 if (LangOpts.Microsoft) {
305 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000306 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
307 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000308 }
Steve Narofffef037c2008-03-27 22:29:16 +0000309 Preamble += "};\n";
310 Preamble += "#define OBJC_SUPER\n";
311 Preamble += "#endif\n";
312 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
313 Preamble += "typedef struct objc_object Protocol;\n";
314 Preamble += "#define _REWRITER_typedef_Protocol\n";
315 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000316 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000317 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
318 else
319 Preamble += "#define __OBJC_RW_EXTERN extern\n";
320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000322 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000323 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000325 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000327 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000328 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000329 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000331 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000332 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000333 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000334 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
335 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
336 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
337 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
338 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000339 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000340 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000341 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
342 Preamble += "struct __objcFastEnumerationState {\n\t";
343 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000344 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000345 Preamble += "unsigned long *mutationsPtr;\n\t";
346 Preamble += "unsigned long extra[5];\n};\n";
347 Preamble += "#define __FASTENUMERATIONSTATE\n";
348 Preamble += "#endif\n";
349 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
350 Preamble += "struct __NSConstantStringImpl {\n";
351 Preamble += " int *isa;\n";
352 Preamble += " int flags;\n";
353 Preamble += " char *str;\n";
354 Preamble += " long length;\n";
355 Preamble += "};\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000356 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000357 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
358 Preamble += "#endif\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000359 if (LangOpts.Microsoft) {
360 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000361 Preamble += "#define __attribute__(X)\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000362 }
Chris Lattner12499682008-01-31 19:38:44 +0000363}
364
365
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000366//===----------------------------------------------------------------------===//
367// Top Level Driver Code
368//===----------------------------------------------------------------------===//
369
Steve Naroff44e81222008-04-14 22:03:09 +0000370void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000371 // Two cases: either the decl could be in the main file, or it could be in a
372 // #included file. If the former, rewrite it now. If the later, check to see
373 // if we rewrote the #include/#import.
374 SourceLocation Loc = D->getLocation();
375 Loc = SM->getLogicalLoc(Loc);
376
377 // If this is for a builtin, ignore it.
378 if (Loc.isInvalid()) return;
379
Steve Naroffe9780582007-10-23 23:50:29 +0000380 // Look for built-in declarations that we need to refer during the rewrite.
381 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000382 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000383 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000384 // declared in <Foundation/NSString.h>
385 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
386 ConstantStringClassReference = FVD;
387 return;
388 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000389 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000390 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000391 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000392 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000393 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000394 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000395 } else if (ObjCForwardProtocolDecl *FP =
396 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000397 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000398 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000399 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000400 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000401 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000402}
403
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000404/// HandleDeclInMainFile - This is called for each top-level decl defined in the
405/// main file of the input.
Steve Naroff44e81222008-04-14 22:03:09 +0000406void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000407 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
408 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000409 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000410
Ted Kremenek42730c52008-01-07 19:49:32 +0000411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000412 if (Stmt *Body = MD->getBody()) {
413 //Body->dump();
414 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000415 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000416 CurMethodDecl = 0;
417 }
Steve Naroff18c83382007-11-13 23:01:27 +0000418 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000419 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000420 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000421 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000422 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000423 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000424 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000425 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000426 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000427 if (VD->getInit())
428 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
429 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 // Nothing yet.
431}
432
Steve Naroff44e81222008-04-14 22:03:09 +0000433RewriteObjC::~RewriteObjC() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000434 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000435
436 // Rewrite tabs if we care.
437 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000438
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000439 if (Diags.hasErrorOccurred())
440 return;
441
442 // Create the output file.
443
444 std::ostream *OutFile;
445 if (OutFileName == "-") {
446 OutFile = llvm::cout.stream();
447 } else if (!OutFileName.empty()) {
448 OutFile = new std::ofstream(OutFileName.c_str(),
449 std::ios_base::binary|std::ios_base::out);
450 } else if (InFileName == "-") {
451 OutFile = llvm::cout.stream();
452 } else {
453 llvm::sys::Path Path(InFileName);
454 Path.eraseSuffix();
455 Path.appendSuffix("cpp");
456 OutFile = new std::ofstream(Path.toString().c_str(),
457 std::ios_base::binary|std::ios_base::out);
458 }
459
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000460 RewriteInclude();
461
Steve Narofffef037c2008-03-27 22:29:16 +0000462 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
463 Preamble.c_str(), Preamble.size(), false);
464
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000465 // Rewrite Objective-c meta data*
466 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000467 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000468
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000469 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
470 // we are done.
471 if (const RewriteBuffer *RewriteBuf =
472 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000473 //printf("Changed:\n");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000474 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000475 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000476 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000477 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000478 // Emit metadata.
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000479 *OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000480}
481
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000482//===----------------------------------------------------------------------===//
483// Syntactic (non-AST) Rewriting Code
484//===----------------------------------------------------------------------===//
485
Steve Naroff44e81222008-04-14 22:03:09 +0000486void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000487 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
488 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
489 const char *MainBufStart = MainBuf.first;
490 const char *MainBufEnd = MainBuf.second;
491 size_t ImportLen = strlen("import");
492 size_t IncludeLen = strlen("include");
493
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000494 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000495 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
496 if (*BufPtr == '#') {
497 if (++BufPtr == MainBufEnd)
498 return;
499 while (*BufPtr == ' ' || *BufPtr == '\t')
500 if (++BufPtr == MainBufEnd)
501 return;
502 if (!strncmp(BufPtr, "import", ImportLen)) {
503 // replace import with include
504 SourceLocation ImportLoc =
505 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000506 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000507 BufPtr += ImportLen;
508 }
509 }
510 }
Chris Lattner74db1682007-10-16 21:07:07 +0000511}
512
Steve Naroff44e81222008-04-14 22:03:09 +0000513void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000514 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
515 const char *MainBufStart = MainBuf.first;
516 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000517
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000518 // Loop over the whole file, looking for tabs.
519 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
520 if (*BufPtr != '\t')
521 continue;
522
523 // Okay, we found a tab. This tab will turn into at least one character,
524 // but it depends on which 'virtual column' it is in. Compute that now.
525 unsigned VCol = 0;
526 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
527 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
528 ++VCol;
529
530 // Okay, now that we know the virtual column, we know how many spaces to
531 // insert. We assume 8-character tab-stops.
532 unsigned Spaces = 8-(VCol & 7);
533
534 // Get the location of the tab.
535 SourceLocation TabLoc =
536 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
537
538 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000539 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000540 }
Chris Lattner569faa62007-10-11 18:38:32 +0000541}
542
543
Steve Naroff44e81222008-04-14 22:03:09 +0000544void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000545 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000546 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000547
548 // Get the start location and compute the semi location.
549 SourceLocation startLoc = ClassDecl->getLocation();
550 const char *startBuf = SM->getCharacterData(startLoc);
551 const char *semiPtr = strchr(startBuf, ';');
552
553 // Translate to typedef's that forward reference structs with the same name
554 // as the class. As a convenience, we include the original declaration
555 // as a comment.
556 std::string typedefString;
557 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000558 typedefString.append(startBuf, semiPtr-startBuf+1);
559 typedefString += "\n";
560 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000561 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000562 typedefString += "#ifndef _REWRITER_typedef_";
563 typedefString += ForwardDecl->getName();
564 typedefString += "\n";
565 typedefString += "#define _REWRITER_typedef_";
566 typedefString += ForwardDecl->getName();
567 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000568 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000569 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000570 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000571 }
572
573 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000574 ReplaceText(startLoc, semiPtr-startBuf+1,
575 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000576}
577
Steve Naroff44e81222008-04-14 22:03:09 +0000578void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000579 SourceLocation LocStart = Method->getLocStart();
580 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000581
Steve Naroff2ce399a2007-12-14 23:37:57 +0000582 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000583 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000584 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000585 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000586 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000587 }
588}
589
Steve Naroff44e81222008-04-14 22:03:09 +0000590void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000591{
Chris Lattnercffe3662008-03-16 21:23:50 +0000592 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000593 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000594 SourceLocation Loc = Property->getLocation();
595
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000596 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000597
598 // FIXME: handle properties that are declared across multiple lines.
599 }
600}
601
Steve Naroff44e81222008-04-14 22:03:09 +0000602void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000603 SourceLocation LocStart = CatDecl->getLocStart();
604
605 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000606 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000607
Ted Kremenek42730c52008-01-07 19:49:32 +0000608 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000609 E = CatDecl->instmeth_end(); I != E; ++I)
610 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000611 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000612 E = CatDecl->classmeth_end(); I != E; ++I)
613 RewriteMethodDeclaration(*I);
614
Steve Naroff667f1682007-10-30 13:30:57 +0000615 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000616 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000617}
618
Steve Naroff44e81222008-04-14 22:03:09 +0000619void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000620 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000621
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000622 SourceLocation LocStart = PDecl->getLocStart();
623
624 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000625 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000626
Ted Kremenek42730c52008-01-07 19:49:32 +0000627 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000628 E = PDecl->instmeth_end(); I != E; ++I)
629 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000630 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000631 E = PDecl->classmeth_end(); I != E; ++I)
632 RewriteMethodDeclaration(*I);
633
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000634 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000635 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000636 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000637
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000638 // Must comment out @optional/@required
639 const char *startBuf = SM->getCharacterData(LocStart);
640 const char *endBuf = SM->getCharacterData(LocEnd);
641 for (const char *p = startBuf; p < endBuf; p++) {
642 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
643 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000644 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000645 ReplaceText(OptionalLoc, strlen("@optional"),
646 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000647
648 }
649 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
650 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000651 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000652 ReplaceText(OptionalLoc, strlen("@required"),
653 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000654
655 }
656 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000657}
658
Steve Naroff44e81222008-04-14 22:03:09 +0000659void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000660 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000661 if (LocStart.isInvalid())
662 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000663 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000664 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000665}
666
Steve Naroff44e81222008-04-14 22:03:09 +0000667void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000668 std::string &ResultStr) {
669 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000670 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000671 ResultStr += "id";
672 else
673 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000674 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000675
676 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000677 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000678
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000679 if (OMD->isInstance())
680 NameStr += "_I_";
681 else
682 NameStr += "_C_";
683
684 NameStr += OMD->getClassInterface()->getName();
685 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000686
687 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000688 if (ObjCCategoryImplDecl *CID =
689 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000690 NameStr += CID->getName();
691 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000692 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000693 // Append selector names, replacing ':' with '_'
694 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000695 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000696 else {
697 std::string selString = OMD->getSelector().getName();
698 int len = selString.size();
699 for (int i = 0; i < len; i++)
700 if (selString[i] == ':')
701 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000702 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000703 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000704 // Remember this name for metadata emission
705 MethodInternalNames[OMD] = NameStr;
706 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000707
708 // Rewrite arguments
709 ResultStr += "(";
710
711 // invisible arguments
712 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000713 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000714 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000715 if (!LangOpts.Microsoft) {
716 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
717 ResultStr += "struct ";
718 }
719 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000720 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000721 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000722 }
723 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000724 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000725
726 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000727 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000728 ResultStr += " _cmd";
729
730 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000731 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000732 ParmVarDecl *PDecl = OMD->getParamDecl(i);
733 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000734 if (PDecl->getType()->isObjCQualifiedIdType()) {
735 ResultStr += "id ";
736 ResultStr += PDecl->getName();
737 } else {
738 std::string Name = PDecl->getName();
739 PDecl->getType().getAsStringInternal(Name);
740 ResultStr += Name;
741 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000742 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000743 if (OMD->isVariadic())
744 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000745 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000746
747}
Steve Naroff44e81222008-04-14 22:03:09 +0000748void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000749 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
750 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000751
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000752 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000753 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000754 else
Chris Lattner6216f292008-01-31 19:42:41 +0000755 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000756
Ted Kremenek42730c52008-01-07 19:49:32 +0000757 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000758 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
759 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000760 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000761 ObjCMethodDecl *OMD = *I;
762 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000763 SourceLocation LocStart = OMD->getLocStart();
764 SourceLocation LocEnd = OMD->getBody()->getLocStart();
765
766 const char *startBuf = SM->getCharacterData(LocStart);
767 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000768 ReplaceText(LocStart, endBuf-startBuf,
769 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000770 }
771
Ted Kremenek42730c52008-01-07 19:49:32 +0000772 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000773 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
774 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000775 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000776 ObjCMethodDecl *OMD = *I;
777 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000778 SourceLocation LocStart = OMD->getLocStart();
779 SourceLocation LocEnd = OMD->getBody()->getLocStart();
780
781 const char *startBuf = SM->getCharacterData(LocStart);
782 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000783 ReplaceText(LocStart, endBuf-startBuf,
784 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000785 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000786 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000787 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000788 else
Chris Lattner6216f292008-01-31 19:42:41 +0000789 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000790}
791
Steve Naroff44e81222008-04-14 22:03:09 +0000792void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000793 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000795 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000796 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000797 ResultStr += ClassDecl->getName();
798 ResultStr += "\n";
799 ResultStr += "#define _REWRITER_typedef_";
800 ResultStr += ClassDecl->getName();
801 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000802 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000803 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000804 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000805 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000806 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000807 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000808 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000809
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000810 RewriteProperties(ClassDecl->getNumPropertyDecl(),
811 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000812 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000813 E = ClassDecl->instmeth_end(); I != E; ++I)
814 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000815 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000816 E = ClassDecl->classmeth_end(); I != E; ++I)
817 RewriteMethodDeclaration(*I);
818
Steve Naroff1ccf4632007-10-30 03:43:13 +0000819 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000820 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000821}
822
Chris Lattner343c82b2008-05-23 20:40:52 +0000823Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
824 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000825 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000826 if (CurMethodDecl) {
827 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000828 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
829 // lookup which class implements the instance variable.
830 ObjCInterfaceDecl *clsDeclared = 0;
831 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
832 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
833
834 // Synthesize an explicit cast to gain access to the ivar.
835 std::string RecName = clsDeclared->getIdentifier()->getName();
836 RecName += "_IMPL";
837 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
838 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
839 SourceLocation(), II, 0);
840 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
841 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
842 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
843 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000844 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
845 IV->getBase()->getLocEnd(),
846 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000847 if (IV->isFreeIvar() &&
848 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000849 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
850 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000851 ReplaceStmt(IV, ME);
852 delete IV;
853 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000854 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000855
856 ReplaceStmt(IV->getBase(), PE);
857 // Cannot delete IV->getBase(), since PE points to it.
858 // Replace the old base with the cast. This is important when doing
859 // embedded rewrites. For example, [newInv->_container addObject:0].
860 IV->setBase(PE);
861 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000862 }
Steve Naroffe6155362008-04-18 21:55:08 +0000863 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000864 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
865
866 // Explicit ivar refs need to have a cast inserted.
867 // FIXME: consider sharing some of this code with the code above.
868 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000869 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000870 // lookup which class implements the instance variable.
871 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000872 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000873 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
874
875 // Synthesize an explicit cast to gain access to the ivar.
876 std::string RecName = clsDeclared->getIdentifier()->getName();
877 RecName += "_IMPL";
878 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
879 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
880 SourceLocation(), II, 0);
881 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
882 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
883 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
884 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000885 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
886 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000887 ReplaceStmt(IV->getBase(), PE);
888 // Cannot delete IV->getBase(), since PE points to it.
889 // Replace the old base with the cast. This is important when doing
890 // embedded rewrites. For example, [newInv->_container addObject:0].
891 IV->setBase(PE);
892 return IV;
893 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000894 }
Steve Naroffe6155362008-04-18 21:55:08 +0000895 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000896}
897
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000898//===----------------------------------------------------------------------===//
899// Function Body / Expression rewriting
900//===----------------------------------------------------------------------===//
901
Steve Naroff44e81222008-04-14 22:03:09 +0000902Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000903 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
904 isa<DoStmt>(S) || isa<ForStmt>(S))
905 Stmts.push_back(S);
906 else if (isa<ObjCForCollectionStmt>(S)) {
907 Stmts.push_back(S);
908 ObjCBcLabelNo.push_back(++BcLabelCount);
909 }
910
Chris Lattner343c82b2008-05-23 20:40:52 +0000911 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner2c022162008-01-31 05:10:40 +0000912
913 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000914 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
915 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000916 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000917 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000918 if (newStmt)
919 *CI = newStmt;
920 }
Steve Naroffe9780582007-10-23 23:50:29 +0000921
922 // Handle specific things.
923 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
924 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000925
926 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000927 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroff296b74f2007-11-05 14:50:49 +0000928
929 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
930 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000931
Steve Naroff0add5d22007-11-03 11:27:19 +0000932 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
933 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000934
Steve Naroff71226032007-10-24 22:48:43 +0000935 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
936 // Before we rewrite it, put the original message expression in a comment.
937 SourceLocation startLoc = MessExpr->getLocStart();
938 SourceLocation endLoc = MessExpr->getLocEnd();
939
940 const char *startBuf = SM->getCharacterData(startLoc);
941 const char *endBuf = SM->getCharacterData(endLoc);
942
943 std::string messString;
944 messString += "// ";
945 messString.append(startBuf, endBuf-startBuf+1);
946 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000947
Chris Lattner6216f292008-01-31 19:42:41 +0000948 // FIXME: Missing definition of
949 // InsertText(clang::SourceLocation, char const*, unsigned int).
950 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000951 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000952 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000953 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000954 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000955
Ted Kremenek42730c52008-01-07 19:49:32 +0000956 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
957 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000958
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000959 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
960 return RewriteObjCSynchronizedStmt(StmtTry);
961
Ted Kremenek42730c52008-01-07 19:49:32 +0000962 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
963 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000964
965 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
966 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000967
968 if (ObjCForCollectionStmt *StmtForCollection =
969 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner343c82b2008-05-23 20:40:52 +0000970 return RewriteObjCForCollectionStmt(StmtForCollection,
971 OrigStmtRange.getEnd());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000972 if (BreakStmt *StmtBreakStmt =
973 dyn_cast<BreakStmt>(S))
974 return RewriteBreakStmt(StmtBreakStmt);
975 if (ContinueStmt *StmtContinueStmt =
976 dyn_cast<ContinueStmt>(S))
977 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000978
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000979 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
980 isa<DoStmt>(S) || isa<ForStmt>(S)) {
981 assert(!Stmts.empty() && "Statement stack is empty");
982 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
983 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
984 && "Statement stack mismatch");
985 Stmts.pop_back();
986 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000987#if 0
988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
989 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
990 // Get the new text.
991 std::ostringstream Buf;
992 Replacement->printPretty(Buf);
993 const std::string &Str = Buf.str();
994
995 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000996 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000997 delete S;
998 return Replacement;
999 }
1000#endif
Chris Lattner0021f452007-10-24 16:57:36 +00001001 // Return this stmt unmodified.
1002 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001003}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001004
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001005/// SynthCountByEnumWithState - To print:
1006/// ((unsigned int (*)
1007/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1008/// (void *)objc_msgSend)((id)l_collection,
1009/// sel_registerName(
1010/// "countByEnumeratingWithState:objects:count:"),
1011/// &enumState,
1012/// (id *)items, (unsigned int)16)
1013///
Steve Naroff44e81222008-04-14 22:03:09 +00001014void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001015 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1016 "id *, unsigned int))(void *)objc_msgSend)";
1017 buf += "\n\t\t";
1018 buf += "((id)l_collection,\n\t\t";
1019 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1020 buf += "\n\t\t";
1021 buf += "&enumState, "
1022 "(id *)items, (unsigned int)16)";
1023}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001024
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001025/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1026/// statement to exit to its outer synthesized loop.
1027///
Steve Naroff44e81222008-04-14 22:03:09 +00001028Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001029 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1030 return S;
1031 // replace break with goto __break_label
1032 std::string buf;
1033
1034 SourceLocation startLoc = S->getLocStart();
1035 buf = "goto __break_label_";
1036 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001037 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001038
1039 return 0;
1040}
1041
1042/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1043/// statement to continue with its inner synthesized loop.
1044///
Steve Naroff44e81222008-04-14 22:03:09 +00001045Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001046 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1047 return S;
1048 // replace continue with goto __continue_label
1049 std::string buf;
1050
1051 SourceLocation startLoc = S->getLocStart();
1052 buf = "goto __continue_label_";
1053 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001054 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001055
1056 return 0;
1057}
1058
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001059/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001060/// It rewrites:
1061/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001062
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001063/// Into:
1064/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001065/// type elem;
1066/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001067/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001068/// id l_collection = (id)collection;
1069/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1070/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001071/// if (limit) {
1072/// unsigned long startMutations = *enumState.mutationsPtr;
1073/// do {
1074/// unsigned long counter = 0;
1075/// do {
1076/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001077/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001078/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001079/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001080/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001081/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001082/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1083/// objects:items count:16]);
1084/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001085/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001086/// }
1087/// else
1088/// elem = nil;
1089/// }
1090///
Steve Naroff44e81222008-04-14 22:03:09 +00001091Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001092 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001093 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1094 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1095 "ObjCForCollectionStmt Statement stack mismatch");
1096 assert(!ObjCBcLabelNo.empty() &&
1097 "ObjCForCollectionStmt - Label No stack empty");
1098
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001099 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001100 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001101 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001102 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001103 std::string buf;
1104 buf = "\n{\n\t";
1105 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1106 // type elem;
1107 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001108 elementTypeAsString = ElementType.getAsString();
1109 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001110 buf += " ";
1111 elementName = DS->getDecl()->getName();
1112 buf += elementName;
1113 buf += ";\n\t";
1114 }
Chris Lattner690c2872008-04-08 05:52:18 +00001115 else {
1116 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001117 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001118 elementTypeAsString = DR->getDecl()->getType().getAsString();
1119 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120
1121 // struct __objcFastEnumerationState enumState = { 0 };
1122 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1123 // id items[16];
1124 buf += "id items[16];\n\t";
1125 // id l_collection = (id)
1126 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001127 // Find start location of 'collection' the hard way!
1128 const char *startCollectionBuf = startBuf;
1129 startCollectionBuf += 3; // skip 'for'
1130 startCollectionBuf = strchr(startCollectionBuf, '(');
1131 startCollectionBuf++; // skip '('
1132 // find 'in' and skip it.
1133 while (*startCollectionBuf != ' ' ||
1134 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1135 (*(startCollectionBuf+3) != ' ' &&
1136 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1137 startCollectionBuf++;
1138 startCollectionBuf += 3;
1139
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001140 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001141 ReplaceText(startLoc, startCollectionBuf - startBuf,
1142 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001143 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001144 SourceLocation rightParenLoc = S->getRParenLoc();
1145 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1146 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001147 buf = ";\n\t";
1148
1149 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1150 // objects:items count:16];
1151 // which is synthesized into:
1152 // unsigned int limit =
1153 // ((unsigned int (*)
1154 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1155 // (void *)objc_msgSend)((id)l_collection,
1156 // sel_registerName(
1157 // "countByEnumeratingWithState:objects:count:"),
1158 // (struct __objcFastEnumerationState *)&state,
1159 // (id *)items, (unsigned int)16);
1160 buf += "unsigned long limit =\n\t\t";
1161 SynthCountByEnumWithState(buf);
1162 buf += ";\n\t";
1163 /// if (limit) {
1164 /// unsigned long startMutations = *enumState.mutationsPtr;
1165 /// do {
1166 /// unsigned long counter = 0;
1167 /// do {
1168 /// if (startMutations != *enumState.mutationsPtr)
1169 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001170 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001171 buf += "if (limit) {\n\t";
1172 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1173 buf += "do {\n\t\t";
1174 buf += "unsigned long counter = 0;\n\t\t";
1175 buf += "do {\n\t\t\t";
1176 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1177 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1178 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001179 buf += " = (";
1180 buf += elementTypeAsString;
1181 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001182 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001183 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001184
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001185 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001186 /// } while (counter < limit);
1187 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1188 /// objects:items count:16]);
1189 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001190 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001191 /// }
1192 /// else
1193 /// elem = nil;
1194 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001195 ///
1196 buf = ";\n\t";
1197 buf += "__continue_label_";
1198 buf += utostr(ObjCBcLabelNo.back());
1199 buf += ": ;";
1200 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001201 buf += "} while (counter < limit);\n\t";
1202 buf += "} while (limit = ";
1203 SynthCountByEnumWithState(buf);
1204 buf += ");\n\t";
1205 buf += elementName;
1206 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001207 buf += "__break_label_";
1208 buf += utostr(ObjCBcLabelNo.back());
1209 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001210 buf += "}\n\t";
1211 buf += "else\n\t\t";
1212 buf += elementName;
1213 buf += " = nil;\n";
1214 buf += "}\n";
1215 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001216 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001217 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001218 Stmts.pop_back();
1219 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001220 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001221}
1222
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001223/// RewriteObjCSynchronizedStmt -
1224/// This routine rewrites @synchronized(expr) stmt;
1225/// into:
1226/// objc_sync_enter(expr);
1227/// @try stmt @finally { objc_sync_exit(expr); }
1228///
Steve Naroff44e81222008-04-14 22:03:09 +00001229Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001230 // Get the start location and compute the semi location.
1231 SourceLocation startLoc = S->getLocStart();
1232 const char *startBuf = SM->getCharacterData(startLoc);
1233
1234 assert((*startBuf == '@') && "bogus @synchronized location");
1235
1236 std::string buf;
1237 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001238 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001239 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1240 const char *endBuf = SM->getCharacterData(endLoc);
1241 endBuf++;
1242 const char *rparenBuf = strchr(endBuf, ')');
1243 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1244 buf = ");\n";
1245 // declare a new scope with two variables, _stack and _rethrow.
1246 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1247 buf += "int buf[18/*32-bit i386*/];\n";
1248 buf += "char *pointers[4];} _stack;\n";
1249 buf += "id volatile _rethrow = 0;\n";
1250 buf += "objc_exception_try_enter(&_stack);\n";
1251 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001252 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001253 startLoc = S->getSynchBody()->getLocEnd();
1254 startBuf = SM->getCharacterData(startLoc);
1255
1256 assert((*startBuf == '}') && "bogus @try block");
1257 SourceLocation lastCurlyLoc = startLoc;
1258 buf = "}\nelse {\n";
1259 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1260 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1261 // FIXME: This must be objc_sync_exit(syncExpr);
1262 buf += " objc_sync_exit();\n";
1263 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1264 buf += "}\n";
1265 buf += "}";
1266
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001267 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001268 return 0;
1269}
1270
Steve Naroff44e81222008-04-14 22:03:09 +00001271Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001272 // Get the start location and compute the semi location.
1273 SourceLocation startLoc = S->getLocStart();
1274 const char *startBuf = SM->getCharacterData(startLoc);
1275
1276 assert((*startBuf == '@') && "bogus @try location");
1277
1278 std::string buf;
1279 // declare a new scope with two variables, _stack and _rethrow.
1280 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1281 buf += "int buf[18/*32-bit i386*/];\n";
1282 buf += "char *pointers[4];} _stack;\n";
1283 buf += "id volatile _rethrow = 0;\n";
1284 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001285 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001286
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001287 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001288
1289 startLoc = S->getTryBody()->getLocEnd();
1290 startBuf = SM->getCharacterData(startLoc);
1291
1292 assert((*startBuf == '}') && "bogus @try block");
1293
1294 SourceLocation lastCurlyLoc = startLoc;
1295
1296 startLoc = startLoc.getFileLocWithOffset(1);
1297 buf = " /* @catch begin */ else {\n";
1298 buf += " id _caught = objc_exception_extract(&_stack);\n";
1299 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001300 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001301 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1302 buf += " else { /* @catch continue */";
1303
Chris Lattner6216f292008-01-31 19:42:41 +00001304 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001305
1306 bool sawIdTypedCatch = false;
1307 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001308 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001309 while (catchList) {
1310 Stmt *catchStmt = catchList->getCatchParamStmt();
1311
1312 if (catchList == S->getCatchStmts())
1313 buf = "if ("; // we are generating code for the first catch clause
1314 else
1315 buf = "else if (";
1316 startLoc = catchList->getLocStart();
1317 startBuf = SM->getCharacterData(startLoc);
1318
1319 assert((*startBuf == '@') && "bogus @catch location");
1320
1321 const char *lParenLoc = strchr(startBuf, '(');
1322
Steve Naroff397c4ce2008-02-01 22:08:12 +00001323 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001324 // Now rewrite the body...
1325 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001326 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1327 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001328 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1329 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001330 assert((*bodyBuf == '{') && "bogus @catch body location");
1331
1332 buf += "1) { id _tmp = _caught;";
1333 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1334 buf.c_str(), buf.size());
1335 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001336 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001337 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001338 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001339 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001340 sawIdTypedCatch = true;
1341 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001342 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001343
Ted Kremenek42730c52008-01-07 19:49:32 +00001344 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001345 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001346 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001347 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001348 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001349 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001350 }
1351 }
1352 // Now rewrite the body...
1353 lastCatchBody = catchList->getCatchBody();
1354 SourceLocation rParenLoc = catchList->getRParenLoc();
1355 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1356 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1357 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1358 assert((*rParenBuf == ')') && "bogus @catch paren location");
1359 assert((*bodyBuf == '{') && "bogus @catch body location");
1360
1361 buf = " = _caught;";
1362 // Here we replace ") {" with "= _caught;" (which initializes and
1363 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001364 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001365 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001366 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001367 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001368 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001369 catchList = catchList->getNextCatchStmt();
1370 }
1371 // Complete the catch list...
1372 if (lastCatchBody) {
1373 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001374 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1375 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001376 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1377 buf = " } } /* @catch end */\n";
1378
Chris Lattner6216f292008-01-31 19:42:41 +00001379 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001380
1381 // Set lastCurlyLoc
1382 lastCurlyLoc = lastCatchBody->getLocEnd();
1383 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001384 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001385 startLoc = finalStmt->getLocStart();
1386 startBuf = SM->getCharacterData(startLoc);
1387 assert((*startBuf == '@') && "bogus @finally start");
1388
1389 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001390 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001391
1392 Stmt *body = finalStmt->getFinallyBody();
1393 SourceLocation startLoc = body->getLocStart();
1394 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001395 assert(*SM->getCharacterData(startLoc) == '{' &&
1396 "bogus @finally body location");
1397 assert(*SM->getCharacterData(endLoc) == '}' &&
1398 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001399
1400 startLoc = startLoc.getFileLocWithOffset(1);
1401 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001402 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001403 endLoc = endLoc.getFileLocWithOffset(-1);
1404 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001405 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001406
1407 // Set lastCurlyLoc
1408 lastCurlyLoc = body->getLocEnd();
1409 }
1410 // Now emit the final closing curly brace...
1411 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1412 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001413 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001414 return 0;
1415}
1416
Steve Naroff44e81222008-04-14 22:03:09 +00001417Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001418 return 0;
1419}
1420
Steve Naroff44e81222008-04-14 22:03:09 +00001421Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001422 return 0;
1423}
1424
Chris Lattnerb1548372008-01-31 19:37:57 +00001425// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001426// the throw expression is typically a message expression that's already
1427// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001428Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001429 // Get the start location and compute the semi location.
1430 SourceLocation startLoc = S->getLocStart();
1431 const char *startBuf = SM->getCharacterData(startLoc);
1432
1433 assert((*startBuf == '@') && "bogus @throw location");
1434
1435 std::string buf;
1436 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001437 if (S->getThrowExpr())
1438 buf = "objc_exception_throw(";
1439 else // add an implicit argument
1440 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001441 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001442 const char *semiBuf = strchr(startBuf, ';');
1443 assert((*semiBuf == ';') && "@throw: can't find ';'");
1444 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1445 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001446 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001447 return 0;
1448}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001449
Steve Naroff44e81222008-04-14 22:03:09 +00001450Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001451 // Create a new string expression.
1452 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001453 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001454 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1455 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001456 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1457 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001458 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001459 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001460
Chris Lattner4478db92007-11-30 22:53:43 +00001461 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001462 delete Exp;
1463 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001464}
1465
Steve Naroff44e81222008-04-14 22:03:09 +00001466Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001467 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1468 // Create a call to sel_registerName("selName").
1469 llvm::SmallVector<Expr*, 8> SelExprs;
1470 QualType argType = Context->getPointerType(Context->CharTy);
1471 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1472 Exp->getSelector().getName().size(),
1473 false, argType, SourceLocation(),
1474 SourceLocation()));
1475 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1476 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001477 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001478 delete Exp;
1479 return SelExp;
1480}
1481
Steve Naroff44e81222008-04-14 22:03:09 +00001482CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001483 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001484 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001485 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001486
1487 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001488 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001489
1490 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001491 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001492 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1493
1494 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001495
Steve Naroff71226032007-10-24 22:48:43 +00001496 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1497}
1498
Steve Naroffc8a92d12007-11-01 13:24:47 +00001499static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1500 const char *&startRef, const char *&endRef) {
1501 while (startBuf < endBuf) {
1502 if (*startBuf == '<')
1503 startRef = startBuf; // mark the start.
1504 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001505 if (startRef && *startRef == '<') {
1506 endRef = startBuf; // mark the end.
1507 return true;
1508 }
1509 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001510 }
1511 startBuf++;
1512 }
1513 return false;
1514}
1515
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001516static void scanToNextArgument(const char *&argRef) {
1517 int angle = 0;
1518 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1519 if (*argRef == '<')
1520 angle++;
1521 else if (*argRef == '>')
1522 angle--;
1523 argRef++;
1524 }
1525 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1526}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001527
Steve Naroff44e81222008-04-14 22:03:09 +00001528bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001529
Ted Kremenek42730c52008-01-07 19:49:32 +00001530 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001531 return true;
1532
Steve Naroffc8a92d12007-11-01 13:24:47 +00001533 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001534 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001535 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001536 return true; // we have "Class <Protocol> *".
1537 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001538 return false;
1539}
1540
Steve Naroff44e81222008-04-14 22:03:09 +00001541void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001542 SourceLocation Loc;
1543 QualType Type;
1544 const FunctionTypeProto *proto = 0;
1545 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1546 Loc = VD->getLocation();
1547 Type = VD->getType();
1548 }
1549 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1550 Loc = FD->getLocation();
1551 // Check for ObjC 'id' and class types that have been adorned with protocol
1552 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1553 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1554 assert(funcType && "missing function type");
1555 proto = dyn_cast<FunctionTypeProto>(funcType);
1556 if (!proto)
1557 return;
1558 Type = proto->getResultType();
1559 }
1560 else
1561 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001562
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001563 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001564 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001565
1566 const char *endBuf = SM->getCharacterData(Loc);
1567 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001568 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001569 startBuf--; // scan backward (from the decl location) for return type.
1570 const char *startRef = 0, *endRef = 0;
1571 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1572 // Get the locations of the startRef, endRef.
1573 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1574 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1575 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001576 InsertText(LessLoc, "/*", 2);
1577 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001578 }
1579 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001580 if (!proto)
1581 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001582 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001583 const char *startBuf = SM->getCharacterData(Loc);
1584 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001585 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1586 if (needToScanForQualifiers(proto->getArgType(i))) {
1587 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001588
Steve Naroffc8a92d12007-11-01 13:24:47 +00001589 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001590 // scan forward (from the decl location) for argument types.
1591 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001592 const char *startRef = 0, *endRef = 0;
1593 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1594 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001595 SourceLocation LessLoc =
1596 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1597 SourceLocation GreaterLoc =
1598 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001599 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001600 InsertText(LessLoc, "/*", 2);
1601 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001602 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001603 startBuf = ++endBuf;
1604 }
1605 else {
1606 while (*startBuf != ')' && *startBuf != ',')
1607 startBuf++; // scan forward (from the decl location) for argument types.
1608 startBuf++;
1609 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001610 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001611}
1612
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001613// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001614void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001615 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1616 llvm::SmallVector<QualType, 16> ArgTys;
1617 ArgTys.push_back(Context->getPointerType(
1618 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001619 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001620 &ArgTys[0], ArgTys.size(),
1621 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001622 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001623 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001624 SelGetUidIdent, getFuncType,
1625 FunctionDecl::Extern, false, 0);
1626}
1627
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001628// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001629void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001630 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1631 llvm::SmallVector<QualType, 16> ArgTys;
1632 ArgTys.push_back(Context->getPointerType(
1633 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001634 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001635 &ArgTys[0], ArgTys.size(),
1636 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001637 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001638 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001639 SelGetProtoIdent, getFuncType,
1640 FunctionDecl::Extern, false, 0);
1641}
1642
Steve Naroff44e81222008-04-14 22:03:09 +00001643void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001644 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001645 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001646 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001647 return;
1648 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001649 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001650}
1651
Steve Naroffbec4bf52008-03-11 17:37:02 +00001652// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001653void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001654 if (SuperContructorFunctionDecl)
1655 return;
1656 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1657 llvm::SmallVector<QualType, 16> ArgTys;
1658 QualType argT = Context->getObjCIdType();
1659 assert(!argT.isNull() && "Can't find 'id' type");
1660 ArgTys.push_back(argT);
1661 ArgTys.push_back(argT);
1662 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1663 &ArgTys[0], ArgTys.size(),
1664 false);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001665 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001666 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001667 msgSendIdent, msgSendType,
1668 FunctionDecl::Extern, false, 0);
1669}
1670
Steve Naroff02a82aa2007-10-30 23:14:51 +00001671// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001672void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001673 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1674 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001675 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001676 assert(!argT.isNull() && "Can't find 'id' type");
1677 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001678 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001679 assert(!argT.isNull() && "Can't find 'SEL' type");
1680 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001681 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001682 &ArgTys[0], ArgTys.size(),
1683 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001684 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001685 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001686 msgSendIdent, msgSendType,
1687 FunctionDecl::Extern, false, 0);
1688}
1689
Steve Naroff764c1ae2007-11-15 10:28:18 +00001690// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001691void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001692 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1693 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001694 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001695 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001696 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001697 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1698 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1699 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001700 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001701 assert(!argT.isNull() && "Can't find 'SEL' type");
1702 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001703 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001704 &ArgTys[0], ArgTys.size(),
1705 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001706 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001707 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001708 msgSendIdent, msgSendType,
1709 FunctionDecl::Extern, false, 0);
1710}
1711
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001712// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001713void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001714 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1715 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001716 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001717 assert(!argT.isNull() && "Can't find 'id' type");
1718 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001719 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001720 assert(!argT.isNull() && "Can't find 'SEL' type");
1721 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001722 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001723 &ArgTys[0], ArgTys.size(),
1724 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001725 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001726 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001727 msgSendIdent, msgSendType,
1728 FunctionDecl::Extern, false, 0);
1729}
1730
1731// SynthMsgSendSuperStretFunctionDecl -
1732// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001733void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001734 IdentifierInfo *msgSendIdent =
1735 &Context->Idents.get("objc_msgSendSuper_stret");
1736 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001737 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001738 SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001739 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001740 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1741 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1742 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001743 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001744 assert(!argT.isNull() && "Can't find 'SEL' type");
1745 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001746 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001747 &ArgTys[0], ArgTys.size(),
1748 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001749 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001750 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001751 msgSendIdent, msgSendType,
1752 FunctionDecl::Extern, false, 0);
1753}
1754
Steve Naroff31316a12008-05-08 22:02:18 +00001755// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001756void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001757 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1758 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001759 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001760 assert(!argT.isNull() && "Can't find 'id' type");
1761 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001762 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001763 assert(!argT.isNull() && "Can't find 'SEL' type");
1764 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001765 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001766 &ArgTys[0], ArgTys.size(),
1767 true /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001768 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001769 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001770 msgSendIdent, msgSendType,
1771 FunctionDecl::Extern, false, 0);
1772}
1773
Steve Naroff02a82aa2007-10-30 23:14:51 +00001774// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001775void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001776 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1777 llvm::SmallVector<QualType, 16> ArgTys;
1778 ArgTys.push_back(Context->getPointerType(
1779 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001780 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001781 &ArgTys[0], ArgTys.size(),
1782 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001783 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001784 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001785 getClassIdent, getClassType,
1786 FunctionDecl::Extern, false, 0);
1787}
1788
Steve Naroff3b1caac2007-12-07 03:50:46 +00001789// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001790void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001791 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1792 llvm::SmallVector<QualType, 16> ArgTys;
1793 ArgTys.push_back(Context->getPointerType(
1794 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001795 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001796 &ArgTys[0], ArgTys.size(),
1797 false /*isVariadic*/);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001798 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001799 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001800 getClassIdent, getClassType,
1801 FunctionDecl::Extern, false, 0);
1802}
1803
Steve Naroff44e81222008-04-14 22:03:09 +00001804Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001805 QualType strType = getConstantStringStructType();
1806
1807 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001808
1809 std::string tmpName = InFileName;
1810 unsigned i;
1811 for (i=0; i < tmpName.length(); i++) {
1812 char c = tmpName.at(i);
1813 // replace any non alphanumeric characters with '_'.
1814 if (!isalpha(c) && (c < '0' || c > '9'))
1815 tmpName[i] = '_';
1816 }
1817 S += tmpName;
1818 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001819 S += utostr(NumObjCStringLiterals++);
1820
Steve Narofffef037c2008-03-27 22:29:16 +00001821 Preamble += "static __NSConstantStringImpl " + S;
1822 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1823 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001824 // The pretty printer for StringLiteral handles escape characters properly.
1825 std::ostringstream prettyBuf;
1826 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001827 Preamble += prettyBuf.str();
1828 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001829 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001830 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001831
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001832 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001833 &Context->Idents.get(S.c_str()), strType,
1834 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001835 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1836 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1837 Context->getPointerType(DRE->getType()),
1838 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001839 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001840 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001841 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001842 delete Exp;
1843 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001844}
1845
Steve Naroff44e81222008-04-14 22:03:09 +00001846ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001847 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001848 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1849
1850 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1851 if (!CE) return 0;
1852
1853 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1854 if (!DRE) return 0;
1855
1856 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1857 if (!PVD) return 0;
1858
1859 if (strcmp(PVD->getName(), "self") != 0)
1860 return 0;
1861
1862 // is this id<P1..> type?
1863 if (CE->getType()->isObjCQualifiedIdType())
1864 return 0;
1865 const PointerType *PT = CE->getType()->getAsPointerType();
1866 if (!PT) return 0;
1867
1868 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1869 if (!IT) return 0;
1870
1871 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1872 return 0;
1873
1874 return IT->getDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001875}
1876
1877// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001878QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001879 if (!SuperStructDecl) {
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001880 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001881 SourceLocation(),
1882 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001883 QualType FieldTypes[2];
1884
1885 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001886 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001887 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001888 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001889 // Create fields
1890 FieldDecl *FieldDecls[2];
1891
1892 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001893 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001894 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001895
1896 SuperStructDecl->defineBody(FieldDecls, 4);
1897 }
1898 return Context->getTagDeclType(SuperStructDecl);
1899}
1900
Steve Naroff44e81222008-04-14 22:03:09 +00001901QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001902 if (!ConstantStringDecl) {
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001903 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001904 SourceLocation(),
1905 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001906 QualType FieldTypes[4];
1907
1908 // struct objc_object *receiver;
1909 FieldTypes[0] = Context->getObjCIdType();
1910 // int flags;
1911 FieldTypes[1] = Context->IntTy;
1912 // char *str;
1913 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1914 // long length;
1915 FieldTypes[3] = Context->LongTy;
1916 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001917 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001918
1919 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001920 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001921 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001922
1923 ConstantStringDecl->defineBody(FieldDecls, 4);
1924 }
1925 return Context->getTagDeclType(ConstantStringDecl);
1926}
1927
Steve Naroff44e81222008-04-14 22:03:09 +00001928Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001929 if (!SelGetUidFunctionDecl)
1930 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001931 if (!MsgSendFunctionDecl)
1932 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001933 if (!MsgSendSuperFunctionDecl)
1934 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001935 if (!MsgSendStretFunctionDecl)
1936 SynthMsgSendStretFunctionDecl();
1937 if (!MsgSendSuperStretFunctionDecl)
1938 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001939 if (!MsgSendFpretFunctionDecl)
1940 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001941 if (!GetClassFunctionDecl)
1942 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001943 if (!GetMetaClassFunctionDecl)
1944 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001945
Steve Naroff764c1ae2007-11-15 10:28:18 +00001946 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001947 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1948 // May need to use objc_msgSend_stret() as well.
1949 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001950 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001951 QualType resultType = mDecl->getResultType();
1952 if (resultType.getCanonicalType()->isStructureType()
1953 || resultType.getCanonicalType()->isUnionType())
1954 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001955 else if (resultType.getCanonicalType()->isRealFloatingType())
1956 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001957 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001958
Steve Naroff71226032007-10-24 22:48:43 +00001959 // Synthesize a call to objc_msgSend().
1960 llvm::SmallVector<Expr*, 8> MsgExprs;
1961 IdentifierInfo *clsName = Exp->getClassName();
1962
1963 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1964 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001965 if (!strcmp(clsName->getName(), "super")) {
1966 MsgSendFlavor = MsgSendSuperFunctionDecl;
1967 if (MsgSendStretFlavor)
1968 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1969 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1970
Ted Kremenek42730c52008-01-07 19:49:32 +00001971 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001972 CurMethodDecl->getClassInterface()->getSuperClass();
1973
1974 llvm::SmallVector<Expr*, 4> InitExprs;
1975
1976 // set the receiver to self, the first argument to all methods.
1977 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001978 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001979 SourceLocation()));
1980 llvm::SmallVector<Expr*, 8> ClsExprs;
1981 QualType argType = Context->getPointerType(Context->CharTy);
1982 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1983 SuperDecl->getIdentifier()->getLength(),
1984 false, argType, SourceLocation(),
1985 SourceLocation()));
1986 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1987 &ClsExprs[0],
1988 ClsExprs.size());
1989 // To turn off a warning, type-cast to 'id'
1990 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001992 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1993 // struct objc_super
1994 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001995 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001996
Steve Naroffdee066b2008-03-11 18:14:26 +00001997 if (LangOpts.Microsoft) {
1998 SynthSuperContructorFunctionDecl();
1999 // Simulate a contructor call...
2000 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2001 superType, SourceLocation());
2002 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2003 superType, SourceLocation());
2004 } else {
2005 // (struct objc_super) { <exprs from above> }
2006 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2007 &InitExprs[0], InitExprs.size(),
2008 SourceLocation());
2009 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2010 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002011 // struct objc_super *
2012 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2013 Context->getPointerType(SuperRep->getType()),
2014 SourceLocation());
2015 MsgExprs.push_back(Unop);
2016 } else {
2017 llvm::SmallVector<Expr*, 8> ClsExprs;
2018 QualType argType = Context->getPointerType(Context->CharTy);
2019 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2020 clsName->getLength(),
2021 false, argType, SourceLocation(),
2022 SourceLocation()));
2023 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2024 &ClsExprs[0],
2025 ClsExprs.size());
2026 MsgExprs.push_back(Cls);
2027 }
Steve Naroff885e2122007-11-14 23:54:14 +00002028 } else { // instance message.
2029 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002030
Ted Kremenek42730c52008-01-07 19:49:32 +00002031 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002032 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002033 if (MsgSendStretFlavor)
2034 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002035 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2036
2037 llvm::SmallVector<Expr*, 4> InitExprs;
2038
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002039 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002040 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002041 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002042
2043 llvm::SmallVector<Expr*, 8> ClsExprs;
2044 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002045 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2046 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002047 false, argType, SourceLocation(),
2048 SourceLocation()));
2049 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002050 &ClsExprs[0],
2051 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002052 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002053 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00002054 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002055 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00002056 // struct objc_super
2057 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002058 Expr *SuperRep;
2059
2060 if (LangOpts.Microsoft) {
2061 SynthSuperContructorFunctionDecl();
2062 // Simulate a contructor call...
2063 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2064 superType, SourceLocation());
2065 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2066 superType, SourceLocation());
2067 } else {
2068 // (struct objc_super) { <exprs from above> }
2069 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2070 &InitExprs[0], InitExprs.size(),
2071 SourceLocation());
2072 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2073 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002074 // struct objc_super *
2075 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2076 Context->getPointerType(SuperRep->getType()),
2077 SourceLocation());
2078 MsgExprs.push_back(Unop);
2079 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002080 // Remove all type-casts because it may contain objc-style types; e.g.
2081 // Foo<Proto> *.
2082 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2083 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002084 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002085 MsgExprs.push_back(recExpr);
2086 }
Steve Naroff885e2122007-11-14 23:54:14 +00002087 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002088 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002089 llvm::SmallVector<Expr*, 8> SelExprs;
2090 QualType argType = Context->getPointerType(Context->CharTy);
2091 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2092 Exp->getSelector().getName().size(),
2093 false, argType, SourceLocation(),
2094 SourceLocation()));
2095 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2096 &SelExprs[0], SelExprs.size());
2097 MsgExprs.push_back(SelExp);
2098
2099 // Now push any user supplied arguments.
2100 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002101 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002102 // Make all implicit casts explicit...ICE comes in handy:-)
2103 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2104 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002105 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2106 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002107 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002108 }
2109 // Make id<P...> cast into an 'id' cast.
2110 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002111 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002112 while ((CE = dyn_cast<CastExpr>(userExpr)))
2113 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002114 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002115 userExpr, SourceLocation());
2116 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002117 }
Steve Naroff885e2122007-11-14 23:54:14 +00002118 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002119 // We've transferred the ownership to MsgExprs. Null out the argument in
2120 // the original expression, since we will delete it below.
2121 Exp->setArg(i, 0);
2122 }
Steve Naroff0744c472007-11-04 22:37:50 +00002123 // Generate the funky cast.
2124 CastExpr *cast;
2125 llvm::SmallVector<QualType, 8> ArgTypes;
2126 QualType returnType;
2127
2128 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002129 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2130 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2131 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002132 ArgTypes.push_back(Context->getObjCIdType());
2133 ArgTypes.push_back(Context->getObjCSelType());
2134 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002135 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002136 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002137 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2138 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002139 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002140 ArgTypes.push_back(t);
2141 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002142 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2143 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002144 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002145 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002146 }
2147 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002148 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002149
2150 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002151 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2152 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002153
2154 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2155 // If we don't do this cast, we get the following bizarre warning/note:
2156 // xx.m:13: warning: function called through a non-compatible type
2157 // xx.m:13: note: if this code is reached, the program will abort
2158 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2159 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002160
Steve Naroff0744c472007-11-04 22:37:50 +00002161 // Now do the "normal" pointer to function cast.
2162 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002163 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002164 // If we don't have a method decl, force a variadic cast.
2165 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002166 castType = Context->getPointerType(castType);
2167 cast = new CastExpr(castType, cast, SourceLocation());
2168
2169 // Don't forget the parens to enforce the proper binding.
2170 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2171
2172 const FunctionType *FT = msgSendType->getAsFunctionType();
2173 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2174 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002175 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002176 if (MsgSendStretFlavor) {
2177 // We have the method which returns a struct/union. Must also generate
2178 // call to objc_msgSend_stret and hang both varieties on a conditional
2179 // expression which dictate which one to envoke depending on size of
2180 // method's return type.
2181
2182 // Create a reference to the objc_msgSend_stret() declaration.
2183 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2184 SourceLocation());
2185 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2186 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2187 SourceLocation());
2188 // Now do the "normal" pointer to function cast.
2189 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002190 &ArgTypes[0], ArgTypes.size(),
2191 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002192 castType = Context->getPointerType(castType);
2193 cast = new CastExpr(castType, cast, SourceLocation());
2194
2195 // Don't forget the parens to enforce the proper binding.
2196 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2197
2198 FT = msgSendType->getAsFunctionType();
2199 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2200 FT->getResultType(), SourceLocation());
2201
2202 // Build sizeof(returnType)
2203 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2204 returnType, Context->getSizeType(),
2205 SourceLocation(), SourceLocation());
2206 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2207 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2208 // For X86 it is more complicated and some kind of target specific routine
2209 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002210 unsigned IntSize =
2211 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002212 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2213 Context->IntTy,
2214 SourceLocation());
2215 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2216 BinaryOperator::LE,
2217 Context->IntTy,
2218 SourceLocation());
2219 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2220 ConditionalOperator *CondExpr =
2221 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002222 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002223 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002224 return ReplacingStmt;
2225}
2226
Steve Naroff44e81222008-04-14 22:03:09 +00002227Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002228 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002229 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002230 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002231
Chris Lattner0021f452007-10-24 16:57:36 +00002232 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002233 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002234}
2235
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002236/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2237/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002238Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002239 if (!GetProtocolFunctionDecl)
2240 SynthGetProtocolFunctionDecl();
2241 // Create a call to objc_getProtocol("ProtocolName").
2242 llvm::SmallVector<Expr*, 8> ProtoExprs;
2243 QualType argType = Context->getPointerType(Context->CharTy);
2244 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2245 strlen(Exp->getProtocol()->getName()),
2246 false, argType, SourceLocation(),
2247 SourceLocation()));
2248 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2249 &ProtoExprs[0],
2250 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002251 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002252 delete Exp;
2253 return ProtoExp;
2254
2255}
2256
Steve Naroffef82b742008-05-31 14:15:04 +00002257bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2258 const char *endBuf) {
2259 while (startBuf < endBuf) {
2260 if (*startBuf == '#') {
2261 // Skip whitespace.
2262 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2263 ;
2264 if (!strncmp(startBuf, "if", strlen("if")) ||
2265 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2266 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2267 !strncmp(startBuf, "define", strlen("define")) ||
2268 !strncmp(startBuf, "undef", strlen("undef")) ||
2269 !strncmp(startBuf, "else", strlen("else")) ||
2270 !strncmp(startBuf, "elif", strlen("elif")) ||
2271 !strncmp(startBuf, "endif", strlen("endif")) ||
2272 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2273 !strncmp(startBuf, "include", strlen("include")) ||
2274 !strncmp(startBuf, "import", strlen("import")) ||
2275 !strncmp(startBuf, "include_next", strlen("include_next")))
2276 return true;
2277 }
2278 startBuf++;
2279 }
2280 return false;
2281}
2282
Ted Kremenek42730c52008-01-07 19:49:32 +00002283/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002284/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002285void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002286 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002287 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2288 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002289 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002290 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002291 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002292 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002293 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002294 SourceLocation LocStart = CDecl->getLocStart();
2295 SourceLocation LocEnd = CDecl->getLocEnd();
2296
2297 const char *startBuf = SM->getCharacterData(LocStart);
2298 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002299
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002300 // If no ivars and no root or if its root, directly or indirectly,
2301 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002302 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2303 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002304 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002305 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002306 return;
2307 }
2308
2309 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002310 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002311 Result += "\nstruct ";
2312 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002313 if (LangOpts.Microsoft)
2314 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002315
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002316 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002317 const char *cursor = strchr(startBuf, '{');
2318 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002319 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002320 // If the buffer contains preprocessor directives, we do more fine-grained
2321 // rewrites. This is intended to fix code that looks like (which occurs in
2322 // NSURL.h, for example):
2323 //
2324 // #ifdef XYZ
2325 // @interface Foo : NSObject
2326 // #else
2327 // @interface FooBar : NSObject
2328 // #endif
2329 // {
2330 // int i;
2331 // }
2332 // @end
2333 //
2334 // This clause is segregated to avoid breaking the common case.
2335 if (BufferContainsPPDirectives(startBuf, cursor)) {
2336 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2337 CDecl->getClassLoc();
2338 const char *endHeader = SM->getCharacterData(L);
2339 endHeader += Lexer::MeasureTokenLength(L, *SM);
2340
2341 if (CDecl->getNumIntfRefProtocols()) {
2342 // advance to the end of the referenced protocols.
2343 while (endHeader < cursor && *endHeader != '>') endHeader++;
2344 endHeader++;
2345 }
2346 // rewrite the original header
2347 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2348 } else {
2349 // rewrite the original header *without* disturbing the '{'
2350 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2351 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002352 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002353 Result = "\n struct ";
2354 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002355 Result += "_IMPL ";
2356 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002357 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002358
2359 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002360 SourceLocation OnePastCurly =
2361 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2362 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002363 }
2364 cursor++; // past '{'
2365
2366 // Now comment out any visibility specifiers.
2367 while (cursor < endBuf) {
2368 if (*cursor == '@') {
2369 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002370 // Skip whitespace.
2371 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2372 /*scan*/;
2373
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002374 // FIXME: presence of @public, etc. inside comment results in
2375 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002376 if (!strncmp(cursor, "public", strlen("public")) ||
2377 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002378 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002379 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002380 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002381 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002382 // FIXME: If there are cases where '<' is used in ivar declaration part
2383 // of user code, then scan the ivar list and use needToScanForQualifiers
2384 // for type checking.
2385 else if (*cursor == '<') {
2386 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002387 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002388 cursor = strchr(cursor, '>');
2389 cursor++;
2390 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002391 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002392 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002393 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002394 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002395 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002396 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002397 } else { // we don't have any instance variables - insert super struct.
2398 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2399 Result += " {\n struct ";
2400 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002401 Result += "_IMPL ";
2402 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002403 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002404 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002405 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002406 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002407 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002408 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002409}
2410
Ted Kremenek42730c52008-01-07 19:49:32 +00002411// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002412/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002413void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002414 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002415 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002416 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002417 const char *ClassName,
2418 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002419 if (MethodBegin == MethodEnd) return;
2420
Fariborz Jahanian04455192007-10-22 21:41:37 +00002421 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002422 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002423 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002424 SEL _cmd;
2425 char *method_types;
2426 void *_imp;
2427 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002428 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002429 Result += "\nstruct _objc_method {\n";
2430 Result += "\tSEL _cmd;\n";
2431 Result += "\tchar *method_types;\n";
2432 Result += "\tvoid *_imp;\n";
2433 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002434
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002435 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002436 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002437
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002438 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002439
2440 /* struct {
2441 struct _objc_method_list *next_method;
2442 int method_count;
2443 struct _objc_method method_list[];
2444 }
2445 */
2446 Result += "\nstatic struct {\n";
2447 Result += "\tstruct _objc_method_list *next_method;\n";
2448 Result += "\tint method_count;\n";
2449 Result += "\tstruct _objc_method method_list[";
2450 Result += utostr(MethodEnd-MethodBegin);
2451 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002452 Result += prefix;
2453 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2454 Result += "_METHODS_";
2455 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002456 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002457 Result += IsInstanceMethod ? "inst" : "cls";
2458 Result += "_meth\")))= ";
2459 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002460
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002461 Result += "\t,{{(SEL)\"";
2462 Result += (*MethodBegin)->getSelector().getName().c_str();
2463 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002464 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002465 Result += "\", \"";
2466 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002467 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002468 Result += MethodInternalNames[*MethodBegin];
2469 Result += "}\n";
2470 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2471 Result += "\t ,{(SEL)\"";
2472 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002473 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002474 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002475 Result += "\", \"";
2476 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002477 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002478 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002479 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002480 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002481 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002482}
2483
Ted Kremenek42730c52008-01-07 19:49:32 +00002484/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroff44e81222008-04-14 22:03:09 +00002485void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002486 int NumProtocols,
2487 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002488 const char *ClassName,
2489 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002490 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002491 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002492 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002493 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002494 // Output struct protocol_methods holder of method selector and type.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002495 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002496 /* struct protocol_methods {
2497 SEL _cmd;
2498 char *method_types;
2499 }
2500 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002501 Result += "\nstruct protocol_methods {\n";
2502 Result += "\tSEL _cmd;\n";
2503 Result += "\tchar *method_types;\n";
2504 Result += "};\n";
2505
Steve Naroff27429432008-03-12 01:06:30 +00002506 objc_protocol_methods = true;
2507 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002508 // Do not synthesize the protocol more than once.
2509 if (ObjCSynthesizedProtocols.count(PDecl))
2510 continue;
2511
Chris Lattner7afba9c2008-03-16 20:19:15 +00002512 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2513 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002514 /* struct _objc_protocol_method_list {
2515 int protocol_method_count;
2516 struct protocol_methods protocols[];
2517 }
2518 */
Steve Naroff27429432008-03-12 01:06:30 +00002519 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002520 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002521 Result += "\tstruct protocol_methods protocols[";
2522 Result += utostr(NumMethods);
2523 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002524 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002525 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002526 "{\n\t" + utostr(NumMethods) + "\n";
2527
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002528 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002529 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002530 E = PDecl->instmeth_end(); I != E; ++I) {
2531 if (I == PDecl->instmeth_begin())
2532 Result += "\t ,{{(SEL)\"";
2533 else
2534 Result += "\t ,{(SEL)\"";
2535 Result += (*I)->getSelector().getName().c_str();
2536 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002537 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002538 Result += "\", \"";
2539 Result += MethodTypeString;
2540 Result += "\"}\n";
2541 }
2542 Result += "\t }\n};\n";
2543 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002544
2545 // Output class methods declared in this protocol.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002546 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahanian04455192007-10-22 21:41:37 +00002547 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002548 /* struct _objc_protocol_method_list {
2549 int protocol_method_count;
2550 struct protocol_methods protocols[];
2551 }
2552 */
2553 Result += "\nstatic struct {\n";
2554 Result += "\tint protocol_method_count;\n";
2555 Result += "\tstruct protocol_methods protocols[";
2556 Result += utostr(NumMethods);
2557 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002558 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002559 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002560 "{\n\t";
2561 Result += utostr(NumMethods);
2562 Result += "\n";
2563
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002564 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002565 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002566 E = PDecl->classmeth_end(); I != E; ++I) {
2567 if (I == PDecl->classmeth_begin())
2568 Result += "\t ,{{(SEL)\"";
2569 else
2570 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002571 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002572 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002573 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002574 Result += "\", \"";
2575 Result += MethodTypeString;
2576 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002577 }
2578 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002579 }
Steve Naroff04eaa192008-05-06 18:26:51 +00002580
Fariborz Jahanian04455192007-10-22 21:41:37 +00002581 // Output:
2582 /* struct _objc_protocol {
2583 // Objective-C 1.0 extensions
2584 struct _objc_protocol_extension *isa;
2585 char *protocol_name;
2586 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002587 struct _objc_protocol_method_list *instance_methods;
2588 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002589 };
2590 */
2591 static bool objc_protocol = false;
2592 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002593 Result += "\nstruct _objc_protocol {\n";
2594 Result += "\tstruct _objc_protocol_extension *isa;\n";
2595 Result += "\tchar *protocol_name;\n";
2596 Result += "\tstruct _objc_protocol **protocol_list;\n";
2597 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2598 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2599 Result += "};\n";
2600
Fariborz Jahanian04455192007-10-22 21:41:37 +00002601 objc_protocol = true;
2602 }
2603
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002604 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2605 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002606 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002607 "{\n\t0, \"";
2608 Result += PDecl->getName();
2609 Result += "\", 0, ";
Chris Lattner7afba9c2008-03-16 20:19:15 +00002610 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00002611 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002612 Result += PDecl->getName();
2613 Result += ", ";
2614 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002615 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002616 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002617 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002618 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002619 Result += PDecl->getName();
2620 Result += "\n";
2621 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002622 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002623 Result += "0\n";
2624 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002625
2626 // Mark this protocol as having been generated.
2627 if (!ObjCSynthesizedProtocols.insert(PDecl))
2628 assert(false && "protocol already synthesized");
Fariborz Jahanian04455192007-10-22 21:41:37 +00002629 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002630 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002631 /* struct _objc_protocol_list {
2632 struct _objc_protocol_list *next;
2633 int protocol_count;
2634 struct _objc_protocol *class_protocols[];
2635 }
2636 */
2637 Result += "\nstatic struct {\n";
2638 Result += "\tstruct _objc_protocol_list *next;\n";
2639 Result += "\tint protocol_count;\n";
2640 Result += "\tstruct _objc_protocol *class_protocols[";
2641 Result += utostr(NumProtocols);
2642 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002643 Result += prefix;
2644 Result += "_PROTOCOLS_";
2645 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002646 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002647 "{\n\t0, ";
2648 Result += utostr(NumProtocols);
2649 Result += "\n";
2650
2651 Result += "\t,{&_OBJC_PROTOCOL_";
2652 Result += Protocols[0]->getName();
2653 Result += " \n";
2654
2655 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002656 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroffb6ed80a2008-04-18 22:15:15 +00002657 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002658 Result += PDecl->getName();
2659 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002660 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002661 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002662 }
2663}
2664
Ted Kremenek42730c52008-01-07 19:49:32 +00002665/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002666/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002667void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002668 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002669 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002670 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002671 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002672 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2673 CDecl = CDecl->getNextClassCategory())
2674 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2675 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002676
Chris Lattnera661a4d2007-12-23 01:40:15 +00002677 std::string FullCategoryName = ClassDecl->getName();
2678 FullCategoryName += '_';
2679 FullCategoryName += IDecl->getName();
2680
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002681 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002682 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002683 true, "CATEGORY_", FullCategoryName.c_str(),
2684 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002685
2686 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002687 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002688 false, "CATEGORY_", FullCategoryName.c_str(),
2689 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002690
2691 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002692 // Null CDecl is case of a category implementation with no category interface
2693 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002694 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002695 CDecl->getNumReferencedProtocols(),
2696 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002697 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002698
2699 /* struct _objc_category {
2700 char *category_name;
2701 char *class_name;
2702 struct _objc_method_list *instance_methods;
2703 struct _objc_method_list *class_methods;
2704 struct _objc_protocol_list *protocols;
2705 // Objective-C 1.0 extensions
2706 uint32_t size; // sizeof (struct _objc_category)
2707 struct _objc_property_list *instance_properties; // category's own
2708 // @property decl.
2709 };
2710 */
2711
2712 static bool objc_category = false;
2713 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002714 Result += "\nstruct _objc_category {\n";
2715 Result += "\tchar *category_name;\n";
2716 Result += "\tchar *class_name;\n";
2717 Result += "\tstruct _objc_method_list *instance_methods;\n";
2718 Result += "\tstruct _objc_method_list *class_methods;\n";
2719 Result += "\tstruct _objc_protocol_list *protocols;\n";
2720 Result += "\tunsigned int size;\n";
2721 Result += "\tstruct _objc_property_list *instance_properties;\n";
2722 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002723 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002724 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002725 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2726 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002727 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002728 Result += IDecl->getName();
2729 Result += "\"\n\t, \"";
2730 Result += ClassDecl->getName();
2731 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002732
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002733 if (IDecl->getNumInstanceMethods() > 0) {
2734 Result += "\t, (struct _objc_method_list *)"
2735 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2736 Result += FullCategoryName;
2737 Result += "\n";
2738 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002739 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002740 Result += "\t, 0\n";
2741 if (IDecl->getNumClassMethods() > 0) {
2742 Result += "\t, (struct _objc_method_list *)"
2743 "&_OBJC_CATEGORY_CLASS_METHODS_";
2744 Result += FullCategoryName;
2745 Result += "\n";
2746 }
2747 else
2748 Result += "\t, 0\n";
2749
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002750 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002751 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2752 Result += FullCategoryName;
2753 Result += "\n";
2754 }
2755 else
2756 Result += "\t, 0\n";
2757 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002758}
2759
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002760/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2761/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002762void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002763 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002764 std::string &Result) {
Steve Naroff5bf10222008-05-07 21:23:49 +00002765 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002766 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002767 if (LangOpts.Microsoft)
2768 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002769 Result += ", ";
2770 Result += ivar->getName();
2771 Result += ")";
2772}
2773
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002774//===----------------------------------------------------------------------===//
2775// Meta Data Emission
2776//===----------------------------------------------------------------------===//
2777
Steve Naroff44e81222008-04-14 22:03:09 +00002778void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002779 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002780 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002781
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002782 // Explictly declared @interface's are already synthesized.
2783 if (CDecl->ImplicitInterfaceDecl()) {
2784 // FIXME: Implementation of a class with no @interface (legacy) doese not
2785 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002786 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002787 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002788
Chris Lattnerc7b06752007-12-12 07:56:42 +00002789 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002790 unsigned NumIvars = !IDecl->ivar_empty()
2791 ? IDecl->ivar_size()
2792 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002793 if (NumIvars > 0) {
2794 static bool objc_ivar = false;
2795 if (!objc_ivar) {
2796 /* struct _objc_ivar {
2797 char *ivar_name;
2798 char *ivar_type;
2799 int ivar_offset;
2800 };
2801 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002802 Result += "\nstruct _objc_ivar {\n";
2803 Result += "\tchar *ivar_name;\n";
2804 Result += "\tchar *ivar_type;\n";
2805 Result += "\tint ivar_offset;\n";
2806 Result += "};\n";
2807
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002808 objc_ivar = true;
2809 }
2810
Steve Naroffc723eec2008-03-11 00:12:29 +00002811 /* struct {
2812 int ivar_count;
2813 struct _objc_ivar ivar_list[nIvars];
2814 };
2815 */
2816 Result += "\nstatic struct {\n";
2817 Result += "\tint ivar_count;\n";
2818 Result += "\tstruct _objc_ivar ivar_list[";
2819 Result += utostr(NumIvars);
2820 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002821 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002822 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002823 "{\n\t";
2824 Result += utostr(NumIvars);
2825 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002826
Ted Kremenek42730c52008-01-07 19:49:32 +00002827 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002828 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002829 IVI = IDecl->ivar_begin();
2830 IVE = IDecl->ivar_end();
2831 } else {
2832 IVI = CDecl->ivar_begin();
2833 IVE = CDecl->ivar_end();
2834 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002835 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002836 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002837 Result += "\", \"";
2838 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002839 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2840 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002841 Result += StrEncoding;
2842 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002843 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002844 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002845 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002846 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002847 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002848 Result += "\", \"";
2849 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002850 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2851 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002852 Result += StrEncoding;
2853 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002854 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002855 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002856 }
2857
2858 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002859 }
2860
2861 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002862 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002863 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002864
2865 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002866 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002867 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002868
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002869 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002870 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002871 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002872 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002873
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002874
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002875 // Declaration of class/meta-class metadata
2876 /* struct _objc_class {
2877 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002878 const char *super_class_name;
2879 char *name;
2880 long version;
2881 long info;
2882 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002883 struct _objc_ivar_list *ivars;
2884 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002885 struct objc_cache *cache;
2886 struct objc_protocol_list *protocols;
2887 const char *ivar_layout;
2888 struct _objc_class_ext *ext;
2889 };
2890 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002891 static bool objc_class = false;
2892 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002893 Result += "\nstruct _objc_class {\n";
2894 Result += "\tstruct _objc_class *isa;\n";
2895 Result += "\tconst char *super_class_name;\n";
2896 Result += "\tchar *name;\n";
2897 Result += "\tlong version;\n";
2898 Result += "\tlong info;\n";
2899 Result += "\tlong instance_size;\n";
2900 Result += "\tstruct _objc_ivar_list *ivars;\n";
2901 Result += "\tstruct _objc_method_list *methods;\n";
2902 Result += "\tstruct objc_cache *cache;\n";
2903 Result += "\tstruct _objc_protocol_list *protocols;\n";
2904 Result += "\tconst char *ivar_layout;\n";
2905 Result += "\tstruct _objc_class_ext *ext;\n";
2906 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002907 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002908 }
2909
2910 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002911 ObjCInterfaceDecl *RootClass = 0;
2912 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002913 while (SuperClass) {
2914 RootClass = SuperClass;
2915 SuperClass = SuperClass->getSuperClass();
2916 }
2917 SuperClass = CDecl->getSuperClass();
2918
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002919 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2920 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002921 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002922 "{\n\t(struct _objc_class *)\"";
2923 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2924 Result += "\"";
2925
2926 if (SuperClass) {
2927 Result += ", \"";
2928 Result += SuperClass->getName();
2929 Result += "\", \"";
2930 Result += CDecl->getName();
2931 Result += "\"";
2932 }
2933 else {
2934 Result += ", 0, \"";
2935 Result += CDecl->getName();
2936 Result += "\"";
2937 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002938 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002939 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002940 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002941 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002942 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002943 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002944 Result += "\n";
2945 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002946 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002947 Result += ", 0\n";
2948 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002949 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002950 Result += CDecl->getName();
2951 Result += ",0,0\n";
2952 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002953 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002954 Result += "\t,0,0,0,0\n";
2955 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002956
2957 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002958 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2959 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002960 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002961 "{\n\t&_OBJC_METACLASS_";
2962 Result += CDecl->getName();
2963 if (SuperClass) {
2964 Result += ", \"";
2965 Result += SuperClass->getName();
2966 Result += "\", \"";
2967 Result += CDecl->getName();
2968 Result += "\"";
2969 }
2970 else {
2971 Result += ", 0, \"";
2972 Result += CDecl->getName();
2973 Result += "\"";
2974 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002975 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002976 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002977 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002978 Result += ",0";
2979 else {
2980 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002981 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002982 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002983 if (LangOpts.Microsoft)
2984 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002985 Result += ")";
2986 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002987 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002988 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002989 Result += CDecl->getName();
2990 Result += "\n\t";
2991 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002992 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002993 Result += ",0";
2994 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002995 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002996 Result += CDecl->getName();
2997 Result += ", 0\n\t";
2998 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002999 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003000 Result += ",0,0";
3001 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00003002 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003003 Result += CDecl->getName();
3004 Result += ", 0,0\n";
3005 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003006 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003007 Result += ",0,0,0\n";
3008 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003009}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003010
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003011/// RewriteImplementations - This routine rewrites all method implementations
3012/// and emits meta-data.
3013
Steve Naroff44e81222008-04-14 22:03:09 +00003014void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003015 int ClsDefCount = ClassImplementation.size();
3016 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003017
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003018 if (ClsDefCount == 0 && CatDefCount == 0)
3019 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003020 // Rewrite implemented methods
3021 for (int i = 0; i < ClsDefCount; i++)
3022 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003023
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003024 for (int i = 0; i < CatDefCount; i++)
3025 RewriteImplementationDecl(CategoryImplementation[i]);
3026
Steve Naroff5bf10222008-05-07 21:23:49 +00003027 // This is needed for determining instance variable offsets.
3028 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003029 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003030 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003031 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003032
3033 // For each implemented category, write out all its meta data.
3034 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003035 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003036
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003037 // Write objc_symtab metadata
3038 /*
3039 struct _objc_symtab
3040 {
3041 long sel_ref_cnt;
3042 SEL *refs;
3043 short cls_def_cnt;
3044 short cat_def_cnt;
3045 void *defs[cls_def_cnt + cat_def_cnt];
3046 };
3047 */
3048
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003049 Result += "\nstruct _objc_symtab {\n";
3050 Result += "\tlong sel_ref_cnt;\n";
3051 Result += "\tSEL *refs;\n";
3052 Result += "\tshort cls_def_cnt;\n";
3053 Result += "\tshort cat_def_cnt;\n";
3054 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3055 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003056
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003057 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003058 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003059 Result += "\t0, 0, " + utostr(ClsDefCount)
3060 + ", " + utostr(CatDefCount) + "\n";
3061 for (int i = 0; i < ClsDefCount; i++) {
3062 Result += "\t,&_OBJC_CLASS_";
3063 Result += ClassImplementation[i]->getName();
3064 Result += "\n";
3065 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003066
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003067 for (int i = 0; i < CatDefCount; i++) {
3068 Result += "\t,&_OBJC_CATEGORY_";
3069 Result += CategoryImplementation[i]->getClassInterface()->getName();
3070 Result += "_";
3071 Result += CategoryImplementation[i]->getName();
3072 Result += "\n";
3073 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003074
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003075 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003076
3077 // Write objc_module metadata
3078
3079 /*
3080 struct _objc_module {
3081 long version;
3082 long size;
3083 const char *name;
3084 struct _objc_symtab *symtab;
3085 }
3086 */
3087
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003088 Result += "\nstruct _objc_module {\n";
3089 Result += "\tlong version;\n";
3090 Result += "\tlong size;\n";
3091 Result += "\tconst char *name;\n";
3092 Result += "\tstruct _objc_symtab *symtab;\n";
3093 Result += "};\n\n";
3094 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003095 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003096 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3097 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003098 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003099
3100 if (LangOpts.Microsoft) {
3101 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003102 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003103 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3104 Result += "&_OBJC_MODULES;\n";
3105 Result += "#pragma data_seg(pop)\n\n";
3106 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003107}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003108
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003109