blob: 14f6ade5916ff0ab8ec566f95eaf60b79b1e5854 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000083 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
94
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000095 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000096 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +000097 virtual void Initialize(ASTContext &context);
98
99 virtual void InitializeTU(TranslationUnit &TU) {
100 TU.SetOwnsDecls(false);
101 Initialize(TU.getContext());
102 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000103
Chris Lattner8a12c272007-10-11 18:38:32 +0000104
Chris Lattnerf04da132007-10-24 17:06:59 +0000105 // Top Level Driver code.
106 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000107 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000108 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000109 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000110
111 ~RewriteObjC() {}
112
113 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000114
115 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000116 // If replacement succeeded or warning disabled return with no warning.
117 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000118 return;
119
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000120 SourceRange Range = Old->getSourceRange();
121 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
122 0, 0, &Range, 1);
123 }
124
Steve Naroffba92b2e2008-03-27 22:29:16 +0000125 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
126 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000127 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000128 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000129 SilenceRewriteMacroWarning)
130 return;
131
132 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
133 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000134
Chris Lattneraadaf782008-01-31 19:51:04 +0000135 void RemoveText(SourceLocation Loc, unsigned StrLen) {
136 // If removal succeeded or warning disabled return with no warning.
137 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
138 return;
139
140 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
141 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000142
Chris Lattneraadaf782008-01-31 19:51:04 +0000143 void ReplaceText(SourceLocation Start, unsigned OrigLength,
144 const char *NewStr, unsigned NewLength) {
145 // If removal succeeded or warning disabled return with no warning.
146 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
147 SilenceRewriteMacroWarning)
148 return;
149
150 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
151 }
152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000154 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000155 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
158 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000159 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
161 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
162 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
163 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
164 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000165 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000166 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000167 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000168 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000169 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000171 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000172 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000173 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000174
Chris Lattnerf04da132007-10-24 17:06:59 +0000175 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000176 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000177 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000178 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000179 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000180 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000181 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000182 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000183 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000184 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
186 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
187 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000188 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
189 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000190 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
191 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000192 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000193 Stmt *RewriteBreakStmt(BreakStmt *S);
194 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000195 void SynthCountByEnumWithState(std::string &buf);
196
Steve Naroff09b266e2007-10-30 23:14:51 +0000197 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000198 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000199 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000200 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000201 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000202 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000203 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000204 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000205 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000206 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000210 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000213 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000214
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
216 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000217 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000218 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000219 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000220 const char *ClassName,
221 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000222
Chris Lattner780f3292008-07-21 21:32:27 +0000223 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
224 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000226 const char *ClassName,
227 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000229 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
231 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000232 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000233 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000234 };
235}
236
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000237static bool IsHeaderFile(const std::string &Filename) {
238 std::string::size_type DotPos = Filename.rfind('.');
239
240 if (DotPos == std::string::npos) {
241 // no file extension
242 return false;
243 }
244
245 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
246 // C header: .h
247 // C++ header: .hh or .H;
248 return Ext == "h" || Ext == "hh" || Ext == "H";
249}
250
Steve Naroffb29b4272008-04-14 22:03:09 +0000251RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000252 Diagnostic &D, const LangOptions &LOpts)
253 : Diags(D), LangOpts(LOpts) {
254 IsHeader = IsHeaderFile(inFile);
255 InFileName = inFile;
256 OutFileName = outFile;
257 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
258 "rewriting sub-expression within a macro (may not be correct)");
259}
260
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000261ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000262 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000263 Diagnostic &Diags,
264 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000265 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000266}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000267
Steve Naroffb29b4272008-04-14 22:03:09 +0000268void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000269 Context = &context;
270 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000271 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000272 MsgSendFunctionDecl = 0;
273 MsgSendSuperFunctionDecl = 0;
274 MsgSendStretFunctionDecl = 0;
275 MsgSendSuperStretFunctionDecl = 0;
276 MsgSendFpretFunctionDecl = 0;
277 GetClassFunctionDecl = 0;
278 GetMetaClassFunctionDecl = 0;
279 SelGetUidFunctionDecl = 0;
280 CFStringFunctionDecl = 0;
281 GetProtocolFunctionDecl = 0;
282 ConstantStringClassReference = 0;
283 NSStringRecord = 0;
284 CurMethodDecl = 0;
285 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000286 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000288 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000289 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000290
291 // Get the ID and start/end of the main file.
292 MainFileID = SM->getMainFileID();
293 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
294 MainFileStart = MainBuf->getBufferStart();
295 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000296
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000297 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000298
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000299 // declaring objc_selector outside the parameter list removes a silly
300 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000301 if (IsHeader)
302 Preamble = "#pragma once\n";
303 Preamble += "struct objc_selector; struct objc_class;\n";
304 Preamble += "#ifndef OBJC_SUPER\n";
305 Preamble += "struct objc_super { struct objc_object *object; ";
306 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000307 if (LangOpts.Microsoft) {
308 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000309 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
310 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000311 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000312 Preamble += "};\n";
313 Preamble += "#define OBJC_SUPER\n";
314 Preamble += "#endif\n";
315 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
316 Preamble += "typedef struct objc_object Protocol;\n";
317 Preamble += "#define _REWRITER_typedef_Protocol\n";
318 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000319 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000320 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
321 else
322 Preamble += "#define __OBJC_RW_EXTERN extern\n";
323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000324 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000326 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000328 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000329 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000330 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000331 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000332 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000333 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000335 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000336 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000337 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
338 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
339 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
340 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
341 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000342 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000343 // @synchronized hooks.
344 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
345 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000346 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000347 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
348 Preamble += "struct __objcFastEnumerationState {\n\t";
349 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000350 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000351 Preamble += "unsigned long *mutationsPtr;\n\t";
352 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000353 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __FASTENUMERATIONSTATE\n";
355 Preamble += "#endif\n";
356 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
357 Preamble += "struct __NSConstantStringImpl {\n";
358 Preamble += " int *isa;\n";
359 Preamble += " int flags;\n";
360 Preamble += " char *str;\n";
361 Preamble += " long length;\n";
362 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000363 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
364 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
365 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000366 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000367 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000368 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
369 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000370 if (LangOpts.Microsoft) {
371 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000372 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000373 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374}
375
376
Chris Lattnerf04da132007-10-24 17:06:59 +0000377//===----------------------------------------------------------------------===//
378// Top Level Driver Code
379//===----------------------------------------------------------------------===//
380
Steve Naroffb29b4272008-04-14 22:03:09 +0000381void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000382 // Two cases: either the decl could be in the main file, or it could be in a
383 // #included file. If the former, rewrite it now. If the later, check to see
384 // if we rewrote the #include/#import.
385 SourceLocation Loc = D->getLocation();
386 Loc = SM->getLogicalLoc(Loc);
387
388 // If this is for a builtin, ignore it.
389 if (Loc.isInvalid()) return;
390
Steve Naroffebf2b562007-10-23 23:50:29 +0000391 // Look for built-in declarations that we need to refer during the rewrite.
392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000393 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000394 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000395 // declared in <Foundation/NSString.h>
396 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
397 ConstantStringClassReference = FVD;
398 return;
399 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000400 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000401 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000402 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000403 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000405 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000406 } else if (ObjCForwardProtocolDecl *FP =
407 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000408 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000409 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000410 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000411 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000412 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000413}
414
Chris Lattnerf04da132007-10-24 17:06:59 +0000415/// HandleDeclInMainFile - This is called for each top-level decl defined in the
416/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000417void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
419 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000420 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000421
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000423 if (Stmt *Body = MD->getBody()) {
424 //Body->dump();
425 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000426 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000427 CurMethodDecl = 0;
428 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000429 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000430 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000431 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000432 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000433 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000434 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000435 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000436 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000437 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000438 if (VD->getInit())
439 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
440 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000441 // Nothing yet.
442}
443
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000444void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000445 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000446
447 // Rewrite tabs if we care.
448 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000449
Steve Naroffa7b402d2008-03-28 22:26:09 +0000450 if (Diags.hasErrorOccurred())
451 return;
452
453 // Create the output file.
454
Ted Kremeneka95d3752008-09-13 05:16:45 +0000455 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
456 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000457 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000458 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000459 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000460 std::string Err;
461 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
462 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000463 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000464 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000465 } else {
466 llvm::sys::Path Path(InFileName);
467 Path.eraseSuffix();
468 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000469 std::string Err;
470 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
471 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000472 }
473
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000474 RewriteInclude();
475
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
477 Preamble.c_str(), Preamble.size(), false);
478
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000479 // Rewrite Objective-c meta data*
480 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000481 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000482
Chris Lattnerf04da132007-10-24 17:06:59 +0000483 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
484 // we are done.
485 if (const RewriteBuffer *RewriteBuf =
486 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000487 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000488 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000489 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000490 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000491 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000492 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000493 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000494 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000495}
496
Chris Lattnerf04da132007-10-24 17:06:59 +0000497//===----------------------------------------------------------------------===//
498// Syntactic (non-AST) Rewriting Code
499//===----------------------------------------------------------------------===//
500
Steve Naroffb29b4272008-04-14 22:03:09 +0000501void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000502 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
503 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
504 const char *MainBufStart = MainBuf.first;
505 const char *MainBufEnd = MainBuf.second;
506 size_t ImportLen = strlen("import");
507 size_t IncludeLen = strlen("include");
508
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000509 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000510 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
511 if (*BufPtr == '#') {
512 if (++BufPtr == MainBufEnd)
513 return;
514 while (*BufPtr == ' ' || *BufPtr == '\t')
515 if (++BufPtr == MainBufEnd)
516 return;
517 if (!strncmp(BufPtr, "import", ImportLen)) {
518 // replace import with include
519 SourceLocation ImportLoc =
520 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000521 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000522 BufPtr += ImportLen;
523 }
524 }
525 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526}
527
Steve Naroffb29b4272008-04-14 22:03:09 +0000528void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000529 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
530 const char *MainBufStart = MainBuf.first;
531 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000532
Chris Lattnerf04da132007-10-24 17:06:59 +0000533 // Loop over the whole file, looking for tabs.
534 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
535 if (*BufPtr != '\t')
536 continue;
537
538 // Okay, we found a tab. This tab will turn into at least one character,
539 // but it depends on which 'virtual column' it is in. Compute that now.
540 unsigned VCol = 0;
541 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
542 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
543 ++VCol;
544
545 // Okay, now that we know the virtual column, we know how many spaces to
546 // insert. We assume 8-character tab-stops.
547 unsigned Spaces = 8-(VCol & 7);
548
549 // Get the location of the tab.
550 SourceLocation TabLoc =
551 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
552
553 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000554 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000555 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000556}
557
558
Steve Naroffb29b4272008-04-14 22:03:09 +0000559void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000561 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000562
563 // Get the start location and compute the semi location.
564 SourceLocation startLoc = ClassDecl->getLocation();
565 const char *startBuf = SM->getCharacterData(startLoc);
566 const char *semiPtr = strchr(startBuf, ';');
567
568 // Translate to typedef's that forward reference structs with the same name
569 // as the class. As a convenience, we include the original declaration
570 // as a comment.
571 std::string typedefString;
572 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000573 typedefString.append(startBuf, semiPtr-startBuf+1);
574 typedefString += "\n";
575 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000577 typedefString += "#ifndef _REWRITER_typedef_";
578 typedefString += ForwardDecl->getName();
579 typedefString += "\n";
580 typedefString += "#define _REWRITER_typedef_";
581 typedefString += ForwardDecl->getName();
582 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000583 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000584 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000585 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000586 }
587
588 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000589 ReplaceText(startLoc, semiPtr-startBuf+1,
590 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000591}
592
Steve Naroffb29b4272008-04-14 22:03:09 +0000593void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000594 SourceLocation LocStart = Method->getLocStart();
595 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000596
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000597 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000598 InsertText(LocStart, "#if 0\n", 6);
599 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000600 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000601 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000602 }
603}
604
Steve Naroffb29b4272008-04-14 22:03:09 +0000605void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000606{
Chris Lattner55d13b42008-03-16 21:23:50 +0000607 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000609 SourceLocation Loc = Property->getLocation();
610
Chris Lattneraadaf782008-01-31 19:51:04 +0000611 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000612
613 // FIXME: handle properties that are declared across multiple lines.
614 }
615}
616
Steve Naroffb29b4272008-04-14 22:03:09 +0000617void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000618 SourceLocation LocStart = CatDecl->getLocStart();
619
620 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000621 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000622
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 E = CatDecl->instmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000626 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000627 E = CatDecl->classmeth_end(); I != E; ++I)
628 RewriteMethodDeclaration(*I);
629
Steve Naroff423cb562007-10-30 13:30:57 +0000630 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000631 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000632}
633
Steve Naroffb29b4272008-04-14 22:03:09 +0000634void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000635 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000636
Steve Naroff752d6ef2007-10-30 16:42:30 +0000637 SourceLocation LocStart = PDecl->getLocStart();
638
639 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000640 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000641
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000642 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000643 E = PDecl->instmeth_end(); I != E; ++I)
644 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000646 E = PDecl->classmeth_end(); I != E; ++I)
647 RewriteMethodDeclaration(*I);
648
Steve Naroff752d6ef2007-10-30 16:42:30 +0000649 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000650 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000652
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000653 // Must comment out @optional/@required
654 const char *startBuf = SM->getCharacterData(LocStart);
655 const char *endBuf = SM->getCharacterData(LocEnd);
656 for (const char *p = startBuf; p < endBuf; p++) {
657 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
658 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000659 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000660 ReplaceText(OptionalLoc, strlen("@optional"),
661 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000662
663 }
664 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
665 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000666 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000667 ReplaceText(OptionalLoc, strlen("@required"),
668 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000669
670 }
671 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000672}
673
Steve Naroffb29b4272008-04-14 22:03:09 +0000674void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000675 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000676 if (LocStart.isInvalid())
677 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000678 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000679 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000680}
681
Steve Naroffb29b4272008-04-14 22:03:09 +0000682void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000683 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000684 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000687 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000688 else if (OMD->getResultType()->isFunctionPointerType()) {
689 // needs special handling, since pointer-to-functions have special
690 // syntax (where a decaration models use).
691 QualType retType = OMD->getResultType();
692 if (const PointerType* PT = retType->getAsPointerType()) {
693 QualType PointeeTy = PT->getPointeeType();
694 if ((FPRetType = PointeeTy->getAsFunctionType())) {
695 ResultStr += FPRetType->getResultType().getAsString();
696 ResultStr += "(*";
697 }
698 }
699 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000700 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000701 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702
703 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000704 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000705
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000706 if (OMD->isInstance())
707 NameStr += "_I_";
708 else
709 NameStr += "_C_";
710
711 NameStr += OMD->getClassInterface()->getName();
712 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000713
714 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000715 if (ObjCCategoryImplDecl *CID =
716 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000717 NameStr += CID->getName();
718 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 }
Steve Naroff563b8282008-04-04 22:23:44 +0000720 // Append selector names, replacing ':' with '_'
721 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000722 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000723 else {
724 std::string selString = OMD->getSelector().getName();
725 int len = selString.size();
726 for (int i = 0; i < len; i++)
727 if (selString[i] == ':')
728 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000729 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000730 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000731 // Remember this name for metadata emission
732 MethodInternalNames[OMD] = NameStr;
733 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734
735 // Rewrite arguments
736 ResultStr += "(";
737
738 // invisible arguments
739 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000740 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000742 if (!LangOpts.Microsoft) {
743 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
744 ResultStr += "struct ";
745 }
746 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000747 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000748 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749 }
750 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752
753 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 ResultStr += " _cmd";
756
757 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000758 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 ParmVarDecl *PDecl = OMD->getParamDecl(i);
760 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000761 if (PDecl->getType()->isObjCQualifiedIdType()) {
762 ResultStr += "id ";
763 ResultStr += PDecl->getName();
764 } else {
765 std::string Name = PDecl->getName();
766 PDecl->getType().getAsStringInternal(Name);
767 ResultStr += Name;
768 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000769 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000770 if (OMD->isVariadic())
771 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000772 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000773
Steve Naroff76e429d2008-07-16 14:40:40 +0000774 if (FPRetType) {
775 ResultStr += ")"; // close the precedence "scope" for "*".
776
777 // Now, emit the argument types (if any).
778 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
779 ResultStr += "(";
780 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
781 if (i) ResultStr += ", ";
782 std::string ParamStr = FT->getArgType(i).getAsString();
783 ResultStr += ParamStr;
784 }
785 if (FT->isVariadic()) {
786 if (FT->getNumArgs()) ResultStr += ", ";
787 ResultStr += "...";
788 }
789 ResultStr += ")";
790 } else {
791 ResultStr += "()";
792 }
793 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000794}
Steve Naroffb29b4272008-04-14 22:03:09 +0000795void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000796 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
797 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000798
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000799 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000800 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000801 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000802 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000803
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000805 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
806 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000807 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 ObjCMethodDecl *OMD = *I;
809 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000810 SourceLocation LocStart = OMD->getLocStart();
811 SourceLocation LocEnd = OMD->getBody()->getLocStart();
812
813 const char *startBuf = SM->getCharacterData(LocStart);
814 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, endBuf-startBuf,
816 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000817 }
818
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000819 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000820 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
821 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000822 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000823 ObjCMethodDecl *OMD = *I;
824 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000825 SourceLocation LocStart = OMD->getLocStart();
826 SourceLocation LocEnd = OMD->getBody()->getLocStart();
827
828 const char *startBuf = SM->getCharacterData(LocStart);
829 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000830 ReplaceText(LocStart, endBuf-startBuf,
831 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000832 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000833 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000834 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000835 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000836 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000837}
838
Steve Naroffb29b4272008-04-14 22:03:09 +0000839void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000840 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000841 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000842 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000843 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000844 ResultStr += ClassDecl->getName();
845 ResultStr += "\n";
846 ResultStr += "#define _REWRITER_typedef_";
847 ResultStr += ClassDecl->getName();
848 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000849 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000850 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000851 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000852 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000854 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000855 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000856
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000857 RewriteProperties(ClassDecl->getNumPropertyDecl(),
858 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000860 E = ClassDecl->instmeth_end(); I != E; ++I)
861 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000863 E = ClassDecl->classmeth_end(); I != E; ++I)
864 RewriteMethodDeclaration(*I);
865
Steve Naroff2feac5e2007-10-30 03:43:13 +0000866 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000867 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000868}
869
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000870Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
871 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000872 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000873 if (CurMethodDecl) {
874 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000875 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
876 // lookup which class implements the instance variable.
877 ObjCInterfaceDecl *clsDeclared = 0;
878 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
879 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
880
881 // Synthesize an explicit cast to gain access to the ivar.
882 std::string RecName = clsDeclared->getIdentifier()->getName();
883 RecName += "_IMPL";
884 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000885 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000886 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000887 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
888 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000889 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
890 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000891 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000892 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
893 IV->getBase()->getLocEnd(),
894 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000895 if (IV->isFreeIvar() &&
896 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000897 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
898 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000899 ReplaceStmt(IV, ME);
900 delete IV;
901 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000902 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000903
904 ReplaceStmt(IV->getBase(), PE);
905 // Cannot delete IV->getBase(), since PE points to it.
906 // Replace the old base with the cast. This is important when doing
907 // embedded rewrites. For example, [newInv->_container addObject:0].
908 IV->setBase(PE);
909 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000910 }
Steve Naroff84472a82008-04-18 21:55:08 +0000911 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000912 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
913
914 // Explicit ivar refs need to have a cast inserted.
915 // FIXME: consider sharing some of this code with the code above.
916 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000917 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000918 // lookup which class implements the instance variable.
919 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000920 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000921 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
922
923 // Synthesize an explicit cast to gain access to the ivar.
924 std::string RecName = clsDeclared->getIdentifier()->getName();
925 RecName += "_IMPL";
926 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000927 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000928 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000929 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
930 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000931 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
932 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000933 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000934 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
935 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000936 ReplaceStmt(IV->getBase(), PE);
937 // Cannot delete IV->getBase(), since PE points to it.
938 // Replace the old base with the cast. This is important when doing
939 // embedded rewrites. For example, [newInv->_container addObject:0].
940 IV->setBase(PE);
941 return IV;
942 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000943 }
Steve Naroff84472a82008-04-18 21:55:08 +0000944 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000945}
946
Chris Lattnerf04da132007-10-24 17:06:59 +0000947//===----------------------------------------------------------------------===//
948// Function Body / Expression rewriting
949//===----------------------------------------------------------------------===//
950
Steve Naroffb29b4272008-04-14 22:03:09 +0000951Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000952 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
953 isa<DoStmt>(S) || isa<ForStmt>(S))
954 Stmts.push_back(S);
955 else if (isa<ObjCForCollectionStmt>(S)) {
956 Stmts.push_back(S);
957 ObjCBcLabelNo.push_back(++BcLabelCount);
958 }
959
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000960 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000961
962 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000963 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
964 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000965 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000966 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000967 if (newStmt)
968 *CI = newStmt;
969 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000970
971 // Handle specific things.
972 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
973 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000974
975 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000976 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000977
978 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
979 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000980
Steve Naroffbeaf2992007-11-03 11:27:19 +0000981 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
982 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000983
Steve Naroff934f2762007-10-24 22:48:43 +0000984 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
985 // Before we rewrite it, put the original message expression in a comment.
986 SourceLocation startLoc = MessExpr->getLocStart();
987 SourceLocation endLoc = MessExpr->getLocEnd();
988
989 const char *startBuf = SM->getCharacterData(startLoc);
990 const char *endBuf = SM->getCharacterData(endLoc);
991
992 std::string messString;
993 messString += "// ";
994 messString.append(startBuf, endBuf-startBuf+1);
995 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000996
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000997 // FIXME: Missing definition of
998 // InsertText(clang::SourceLocation, char const*, unsigned int).
999 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001000 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001001 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001002 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001003 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1006 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001007
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001008 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1009 return RewriteObjCSynchronizedStmt(StmtTry);
1010
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001011 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1012 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001013
1014 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1015 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001016
1017 if (ObjCForCollectionStmt *StmtForCollection =
1018 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001019 return RewriteObjCForCollectionStmt(StmtForCollection,
1020 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001021 if (BreakStmt *StmtBreakStmt =
1022 dyn_cast<BreakStmt>(S))
1023 return RewriteBreakStmt(StmtBreakStmt);
1024 if (ContinueStmt *StmtContinueStmt =
1025 dyn_cast<ContinueStmt>(S))
1026 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001027
Ted Kremenekab9bae72008-10-06 22:45:07 +00001028 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1029 // and cast exprs.
1030 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1031 // FIXME: What we're doing here is modifying the type-specifier that
1032 // precedes the first Decl. In the future the DeclGroup should have
1033 // a separate type-specifier that we can rewrite.
1034 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
1035 }
1036
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001037 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001038 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001040 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1041 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1042 assert(!Stmts.empty() && "Statement stack is empty");
1043 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1044 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1045 && "Statement stack mismatch");
1046 Stmts.pop_back();
1047 }
Steve Naroff874e2322007-11-15 10:28:18 +00001048#if 0
1049 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1050 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1051 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001052 std::string SStr;
1053 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001054 Replacement->printPretty(Buf);
1055 const std::string &Str = Buf.str();
1056
1057 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001058 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001059 delete S;
1060 return Replacement;
1061 }
1062#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001063 // Return this stmt unmodified.
1064 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001065}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001066
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067/// SynthCountByEnumWithState - To print:
1068/// ((unsigned int (*)
1069/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1070/// (void *)objc_msgSend)((id)l_collection,
1071/// sel_registerName(
1072/// "countByEnumeratingWithState:objects:count:"),
1073/// &enumState,
1074/// (id *)items, (unsigned int)16)
1075///
Steve Naroffb29b4272008-04-14 22:03:09 +00001076void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001077 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1078 "id *, unsigned int))(void *)objc_msgSend)";
1079 buf += "\n\t\t";
1080 buf += "((id)l_collection,\n\t\t";
1081 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1082 buf += "\n\t\t";
1083 buf += "&enumState, "
1084 "(id *)items, (unsigned int)16)";
1085}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001086
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001087/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1088/// statement to exit to its outer synthesized loop.
1089///
Steve Naroffb29b4272008-04-14 22:03:09 +00001090Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001091 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1092 return S;
1093 // replace break with goto __break_label
1094 std::string buf;
1095
1096 SourceLocation startLoc = S->getLocStart();
1097 buf = "goto __break_label_";
1098 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001099 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001100
1101 return 0;
1102}
1103
1104/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1105/// statement to continue with its inner synthesized loop.
1106///
Steve Naroffb29b4272008-04-14 22:03:09 +00001107Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001108 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1109 return S;
1110 // replace continue with goto __continue_label
1111 std::string buf;
1112
1113 SourceLocation startLoc = S->getLocStart();
1114 buf = "goto __continue_label_";
1115 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001116 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001117
1118 return 0;
1119}
1120
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001121/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001122/// It rewrites:
1123/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001124
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001125/// Into:
1126/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127/// type elem;
1128/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001129/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001130/// id l_collection = (id)collection;
1131/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1132/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001133/// if (limit) {
1134/// unsigned long startMutations = *enumState.mutationsPtr;
1135/// do {
1136/// unsigned long counter = 0;
1137/// do {
1138/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001140/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001141/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001142/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001143/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001144/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1145/// objects:items count:16]);
1146/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001147/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001148/// }
1149/// else
1150/// elem = nil;
1151/// }
1152///
Steve Naroffb29b4272008-04-14 22:03:09 +00001153Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001154 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001155 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1156 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1157 "ObjCForCollectionStmt Statement stack mismatch");
1158 assert(!ObjCBcLabelNo.empty() &&
1159 "ObjCForCollectionStmt - Label No stack empty");
1160
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001161 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001163 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001164 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165 std::string buf;
1166 buf = "\n{\n\t";
1167 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1168 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001169 ScopedDecl* D = DS->getSolitaryDecl();
1170 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001171 elementTypeAsString = ElementType.getAsString();
1172 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001173 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001174 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 buf += elementName;
1176 buf += ";\n\t";
1177 }
Chris Lattner06767512008-04-08 05:52:18 +00001178 else {
1179 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001180 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001181 elementTypeAsString = DR->getDecl()->getType().getAsString();
1182 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001183
1184 // struct __objcFastEnumerationState enumState = { 0 };
1185 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1186 // id items[16];
1187 buf += "id items[16];\n\t";
1188 // id l_collection = (id)
1189 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001190 // Find start location of 'collection' the hard way!
1191 const char *startCollectionBuf = startBuf;
1192 startCollectionBuf += 3; // skip 'for'
1193 startCollectionBuf = strchr(startCollectionBuf, '(');
1194 startCollectionBuf++; // skip '('
1195 // find 'in' and skip it.
1196 while (*startCollectionBuf != ' ' ||
1197 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1198 (*(startCollectionBuf+3) != ' ' &&
1199 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1200 startCollectionBuf++;
1201 startCollectionBuf += 3;
1202
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001203 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001204 ReplaceText(startLoc, startCollectionBuf - startBuf,
1205 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001206 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001207 SourceLocation rightParenLoc = S->getRParenLoc();
1208 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1209 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001210 buf = ";\n\t";
1211
1212 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1213 // objects:items count:16];
1214 // which is synthesized into:
1215 // unsigned int limit =
1216 // ((unsigned int (*)
1217 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1218 // (void *)objc_msgSend)((id)l_collection,
1219 // sel_registerName(
1220 // "countByEnumeratingWithState:objects:count:"),
1221 // (struct __objcFastEnumerationState *)&state,
1222 // (id *)items, (unsigned int)16);
1223 buf += "unsigned long limit =\n\t\t";
1224 SynthCountByEnumWithState(buf);
1225 buf += ";\n\t";
1226 /// if (limit) {
1227 /// unsigned long startMutations = *enumState.mutationsPtr;
1228 /// do {
1229 /// unsigned long counter = 0;
1230 /// do {
1231 /// if (startMutations != *enumState.mutationsPtr)
1232 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001233 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001234 buf += "if (limit) {\n\t";
1235 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1236 buf += "do {\n\t\t";
1237 buf += "unsigned long counter = 0;\n\t\t";
1238 buf += "do {\n\t\t\t";
1239 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1240 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1241 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001242 buf += " = (";
1243 buf += elementTypeAsString;
1244 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001245 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001246 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001247
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001249 /// } while (counter < limit);
1250 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1251 /// objects:items count:16]);
1252 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001254 /// }
1255 /// else
1256 /// elem = nil;
1257 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001258 ///
1259 buf = ";\n\t";
1260 buf += "__continue_label_";
1261 buf += utostr(ObjCBcLabelNo.back());
1262 buf += ": ;";
1263 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264 buf += "} while (counter < limit);\n\t";
1265 buf += "} while (limit = ";
1266 SynthCountByEnumWithState(buf);
1267 buf += ");\n\t";
1268 buf += elementName;
1269 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001270 buf += "__break_label_";
1271 buf += utostr(ObjCBcLabelNo.back());
1272 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273 buf += "}\n\t";
1274 buf += "else\n\t\t";
1275 buf += elementName;
1276 buf += " = nil;\n";
1277 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001278
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001279 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001280 if (isa<CompoundStmt>(S->getBody())) {
1281 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1282 InsertText(endBodyLoc, buf.c_str(), buf.size());
1283 } else {
1284 /* Need to treat single statements specially. For example:
1285 *
1286 * for (A *a in b) if (stuff()) break;
1287 * for (A *a in b) xxxyy;
1288 *
1289 * The following code simply scans ahead to the semi to find the actual end.
1290 */
1291 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1292 const char *semiBuf = strchr(stmtBuf, ';');
1293 assert(semiBuf && "Can't find ';'");
1294 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1295 InsertText(endBodyLoc, buf.c_str(), buf.size());
1296 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001297 Stmts.pop_back();
1298 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001299 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001300}
1301
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001302/// RewriteObjCSynchronizedStmt -
1303/// This routine rewrites @synchronized(expr) stmt;
1304/// into:
1305/// objc_sync_enter(expr);
1306/// @try stmt @finally { objc_sync_exit(expr); }
1307///
Steve Naroffb29b4272008-04-14 22:03:09 +00001308Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001309 // Get the start location and compute the semi location.
1310 SourceLocation startLoc = S->getLocStart();
1311 const char *startBuf = SM->getCharacterData(startLoc);
1312
1313 assert((*startBuf == '@') && "bogus @synchronized location");
1314
1315 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001316 buf = "objc_sync_enter((id)";
1317 const char *lparenBuf = startBuf;
1318 while (*lparenBuf != '(') lparenBuf++;
1319 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001320 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1321 // the sync expression is typically a message expression that's already
1322 // been rewritten! (which implies the SourceLocation's are invalid).
1323 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001324 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001325 while (*endBuf != ')') endBuf--;
1326 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001327 buf = ");\n";
1328 // declare a new scope with two variables, _stack and _rethrow.
1329 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1330 buf += "int buf[18/*32-bit i386*/];\n";
1331 buf += "char *pointers[4];} _stack;\n";
1332 buf += "id volatile _rethrow = 0;\n";
1333 buf += "objc_exception_try_enter(&_stack);\n";
1334 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001335 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001336 startLoc = S->getSynchBody()->getLocEnd();
1337 startBuf = SM->getCharacterData(startLoc);
1338
Steve Naroffc7089f12008-08-19 13:04:19 +00001339 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001340 SourceLocation lastCurlyLoc = startLoc;
1341 buf = "}\nelse {\n";
1342 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1343 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001344 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001345 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1346 S->getSynchExpr(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001347 std::string syncExprBufS;
1348 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001349 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001350 buf += syncExprBuf.str();
1351 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001352 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1353 buf += "}\n";
1354 buf += "}";
1355
Chris Lattneraadaf782008-01-31 19:51:04 +00001356 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001357 return 0;
1358}
1359
Steve Naroffb29b4272008-04-14 22:03:09 +00001360Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001361 // Get the start location and compute the semi location.
1362 SourceLocation startLoc = S->getLocStart();
1363 const char *startBuf = SM->getCharacterData(startLoc);
1364
1365 assert((*startBuf == '@') && "bogus @try location");
1366
1367 std::string buf;
1368 // declare a new scope with two variables, _stack and _rethrow.
1369 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1370 buf += "int buf[18/*32-bit i386*/];\n";
1371 buf += "char *pointers[4];} _stack;\n";
1372 buf += "id volatile _rethrow = 0;\n";
1373 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001374 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001375
Chris Lattneraadaf782008-01-31 19:51:04 +00001376 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001377
1378 startLoc = S->getTryBody()->getLocEnd();
1379 startBuf = SM->getCharacterData(startLoc);
1380
1381 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001382
Steve Naroff75730982007-11-07 04:08:17 +00001383 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001384 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1385 if (catchList) {
1386 startLoc = startLoc.getFileLocWithOffset(1);
1387 buf = " /* @catch begin */ else {\n";
1388 buf += " id _caught = objc_exception_extract(&_stack);\n";
1389 buf += " objc_exception_try_enter (&_stack);\n";
1390 buf += " if (_setjmp(_stack.buf))\n";
1391 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1392 buf += " else { /* @catch continue */";
1393
1394 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001395 } else { /* no catch list */
1396 buf = "}\nelse {\n";
1397 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1398 buf += "}";
1399 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001400 }
Steve Naroff75730982007-11-07 04:08:17 +00001401 bool sawIdTypedCatch = false;
1402 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001403 while (catchList) {
1404 Stmt *catchStmt = catchList->getCatchParamStmt();
1405
1406 if (catchList == S->getCatchStmts())
1407 buf = "if ("; // we are generating code for the first catch clause
1408 else
1409 buf = "else if (";
1410 startLoc = catchList->getLocStart();
1411 startBuf = SM->getCharacterData(startLoc);
1412
1413 assert((*startBuf == '@') && "bogus @catch location");
1414
1415 const char *lParenLoc = strchr(startBuf, '(');
1416
Steve Naroffbe4b3332008-02-01 22:08:12 +00001417 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001418 // Now rewrite the body...
1419 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001420 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1421 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001422 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1423 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001424 assert((*bodyBuf == '{') && "bogus @catch body location");
1425
1426 buf += "1) { id _tmp = _caught;";
1427 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1428 buf.c_str(), buf.size());
1429 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001430 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001432 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001433 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001434 sawIdTypedCatch = true;
1435 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001437
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001438 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001439 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001440 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001441 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001442 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001443 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001444 }
1445 }
1446 // Now rewrite the body...
1447 lastCatchBody = catchList->getCatchBody();
1448 SourceLocation rParenLoc = catchList->getRParenLoc();
1449 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1450 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1451 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1452 assert((*rParenBuf == ')') && "bogus @catch paren location");
1453 assert((*bodyBuf == '{') && "bogus @catch body location");
1454
1455 buf = " = _caught;";
1456 // Here we replace ") {" with "= _caught;" (which initializes and
1457 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001458 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001459 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001460 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001461 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001462 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001463 catchList = catchList->getNextCatchStmt();
1464 }
1465 // Complete the catch list...
1466 if (lastCatchBody) {
1467 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001468 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1469 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001470
Steve Naroff378f47a2008-09-11 15:29:03 +00001471 // Insert the last (implicit) else clause *before* the right curly brace.
1472 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1473 buf = "} /* last catch end */\n";
1474 buf += "else {\n";
1475 buf += " _rethrow = _caught;\n";
1476 buf += " objc_exception_try_exit(&_stack);\n";
1477 buf += "} } /* @catch end */\n";
1478 if (!S->getFinallyStmt())
1479 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001480 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001481
1482 // Set lastCurlyLoc
1483 lastCurlyLoc = lastCatchBody->getLocEnd();
1484 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001485 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001486 startLoc = finalStmt->getLocStart();
1487 startBuf = SM->getCharacterData(startLoc);
1488 assert((*startBuf == '@') && "bogus @finally start");
1489
1490 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001491 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001492
1493 Stmt *body = finalStmt->getFinallyBody();
1494 SourceLocation startLoc = body->getLocStart();
1495 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001496 assert(*SM->getCharacterData(startLoc) == '{' &&
1497 "bogus @finally body location");
1498 assert(*SM->getCharacterData(endLoc) == '}' &&
1499 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001500
1501 startLoc = startLoc.getFileLocWithOffset(1);
1502 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001503 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001504 endLoc = endLoc.getFileLocWithOffset(-1);
1505 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001506 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001507
1508 // Set lastCurlyLoc
1509 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001510 } else { /* no finally clause - make sure we synthesize an implicit one */
1511 buf = "{ /* implicit finally clause */\n";
1512 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1513 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1514 buf += "}";
1515 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001516 }
1517 // Now emit the final closing curly brace...
1518 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1519 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001520 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001521 return 0;
1522}
1523
Steve Naroffb29b4272008-04-14 22:03:09 +00001524Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001525 return 0;
1526}
1527
Steve Naroffb29b4272008-04-14 22:03:09 +00001528Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001529 return 0;
1530}
1531
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001532// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001533// the throw expression is typically a message expression that's already
1534// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001535Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001536 // Get the start location and compute the semi location.
1537 SourceLocation startLoc = S->getLocStart();
1538 const char *startBuf = SM->getCharacterData(startLoc);
1539
1540 assert((*startBuf == '@') && "bogus @throw location");
1541
1542 std::string buf;
1543 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001544 if (S->getThrowExpr())
1545 buf = "objc_exception_throw(";
1546 else // add an implicit argument
1547 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001548
1549 // handle "@ throw" correctly.
1550 const char *wBuf = strchr(startBuf, 'w');
1551 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1552 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1553
Steve Naroff2bd03922007-11-07 15:32:26 +00001554 const char *semiBuf = strchr(startBuf, ';');
1555 assert((*semiBuf == ';') && "@throw: can't find ';'");
1556 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1557 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001558 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001559 return 0;
1560}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001561
Steve Naroffb29b4272008-04-14 22:03:09 +00001562Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001563 // Create a new string expression.
1564 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001565 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001566 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001567 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1568 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001569 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001570 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001571
Chris Lattner07506182007-11-30 22:53:43 +00001572 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001573 delete Exp;
1574 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001575}
1576
Steve Naroffb29b4272008-04-14 22:03:09 +00001577Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001578 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1579 // Create a call to sel_registerName("selName").
1580 llvm::SmallVector<Expr*, 8> SelExprs;
1581 QualType argType = Context->getPointerType(Context->CharTy);
1582 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1583 Exp->getSelector().getName().size(),
1584 false, argType, SourceLocation(),
1585 SourceLocation()));
1586 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1587 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001588 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001589 delete Exp;
1590 return SelExp;
1591}
1592
Steve Naroffb29b4272008-04-14 22:03:09 +00001593CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001594 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001595 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001596 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001597
1598 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001599 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001600
1601 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001602 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001603 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1604
1605 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001606
Steve Naroff934f2762007-10-24 22:48:43 +00001607 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1608}
1609
Steve Naroffd5255f52007-11-01 13:24:47 +00001610static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1611 const char *&startRef, const char *&endRef) {
1612 while (startBuf < endBuf) {
1613 if (*startBuf == '<')
1614 startRef = startBuf; // mark the start.
1615 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001616 if (startRef && *startRef == '<') {
1617 endRef = startBuf; // mark the end.
1618 return true;
1619 }
1620 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001621 }
1622 startBuf++;
1623 }
1624 return false;
1625}
1626
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001627static void scanToNextArgument(const char *&argRef) {
1628 int angle = 0;
1629 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1630 if (*argRef == '<')
1631 angle++;
1632 else if (*argRef == '>')
1633 angle--;
1634 argRef++;
1635 }
1636 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1637}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001638
Steve Naroffb29b4272008-04-14 22:03:09 +00001639bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001640
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001641 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001642 return true;
1643
Steve Naroffd5255f52007-11-01 13:24:47 +00001644 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001645 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001646 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001647 return true; // we have "Class <Protocol> *".
1648 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001649 return false;
1650}
1651
Steve Naroff4f95b752008-07-29 18:15:38 +00001652void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1653 QualType Type = E->getType();
1654 if (needToScanForQualifiers(Type)) {
1655 SourceLocation Loc = E->getLocStart();
1656 const char *startBuf = SM->getCharacterData(Loc);
1657 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1658 const char *startRef = 0, *endRef = 0;
1659 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1660 // Get the locations of the startRef, endRef.
1661 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1662 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1663 // Comment out the protocol references.
1664 InsertText(LessLoc, "/*", 2);
1665 InsertText(GreaterLoc, "*/", 2);
1666 }
1667 }
1668}
1669
Steve Naroffb29b4272008-04-14 22:03:09 +00001670void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001671 SourceLocation Loc;
1672 QualType Type;
1673 const FunctionTypeProto *proto = 0;
1674 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1675 Loc = VD->getLocation();
1676 Type = VD->getType();
1677 }
1678 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1679 Loc = FD->getLocation();
1680 // Check for ObjC 'id' and class types that have been adorned with protocol
1681 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1682 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1683 assert(funcType && "missing function type");
1684 proto = dyn_cast<FunctionTypeProto>(funcType);
1685 if (!proto)
1686 return;
1687 Type = proto->getResultType();
1688 }
1689 else
1690 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001691
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001692 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001693 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001694
1695 const char *endBuf = SM->getCharacterData(Loc);
1696 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001697 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001698 startBuf--; // scan backward (from the decl location) for return type.
1699 const char *startRef = 0, *endRef = 0;
1700 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1701 // Get the locations of the startRef, endRef.
1702 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1703 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1704 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001705 InsertText(LessLoc, "/*", 2);
1706 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001707 }
1708 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001709 if (!proto)
1710 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001711 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001712 const char *startBuf = SM->getCharacterData(Loc);
1713 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001714 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1715 if (needToScanForQualifiers(proto->getArgType(i))) {
1716 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001717
Steve Naroffd5255f52007-11-01 13:24:47 +00001718 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001719 // scan forward (from the decl location) for argument types.
1720 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001721 const char *startRef = 0, *endRef = 0;
1722 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1723 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001724 SourceLocation LessLoc =
1725 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1726 SourceLocation GreaterLoc =
1727 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001728 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001729 InsertText(LessLoc, "/*", 2);
1730 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001731 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001732 startBuf = ++endBuf;
1733 }
1734 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001735 // If the function name is derived from a macro expansion, then the
1736 // argument buffer will not follow the name. Need to speak with Chris.
1737 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001738 startBuf++; // scan forward (from the decl location) for argument types.
1739 startBuf++;
1740 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001741 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001742}
1743
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001744// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001745void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001746 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1747 llvm::SmallVector<QualType, 16> ArgTys;
1748 ArgTys.push_back(Context->getPointerType(
1749 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001750 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001751 &ArgTys[0], ArgTys.size(),
1752 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001753 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001754 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001755 SelGetUidIdent, getFuncType,
1756 FunctionDecl::Extern, false, 0);
1757}
1758
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001759// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001760void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001761 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1762 llvm::SmallVector<QualType, 16> ArgTys;
1763 ArgTys.push_back(Context->getPointerType(
1764 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001765 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001766 &ArgTys[0], ArgTys.size(),
1767 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001768 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001769 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001770 SelGetProtoIdent, getFuncType,
1771 FunctionDecl::Extern, false, 0);
1772}
1773
Steve Naroffb29b4272008-04-14 22:03:09 +00001774void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001775 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001776 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001777 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001778 return;
1779 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001780 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001781}
1782
Steve Naroffc0a123c2008-03-11 17:37:02 +00001783// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001784void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001785 if (SuperContructorFunctionDecl)
1786 return;
1787 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1788 llvm::SmallVector<QualType, 16> ArgTys;
1789 QualType argT = Context->getObjCIdType();
1790 assert(!argT.isNull() && "Can't find 'id' type");
1791 ArgTys.push_back(argT);
1792 ArgTys.push_back(argT);
1793 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1794 &ArgTys[0], ArgTys.size(),
1795 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001796 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001797 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001798 msgSendIdent, msgSendType,
1799 FunctionDecl::Extern, false, 0);
1800}
1801
Steve Naroff09b266e2007-10-30 23:14:51 +00001802// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001803void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001804 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1805 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001806 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001807 assert(!argT.isNull() && "Can't find 'id' type");
1808 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001809 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001810 assert(!argT.isNull() && "Can't find 'SEL' type");
1811 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001812 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001813 &ArgTys[0], ArgTys.size(),
1814 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001815 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001816 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001817 msgSendIdent, msgSendType,
1818 FunctionDecl::Extern, false, 0);
1819}
1820
Steve Naroff874e2322007-11-15 10:28:18 +00001821// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001822void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001823 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1824 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001825 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001826 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001827 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001828 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1829 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1830 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001831 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001832 assert(!argT.isNull() && "Can't find 'SEL' type");
1833 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001834 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001835 &ArgTys[0], ArgTys.size(),
1836 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001837 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001838 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001839 msgSendIdent, msgSendType,
1840 FunctionDecl::Extern, false, 0);
1841}
1842
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001843// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001844void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001845 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1846 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001847 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001848 assert(!argT.isNull() && "Can't find 'id' type");
1849 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001850 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001851 assert(!argT.isNull() && "Can't find 'SEL' type");
1852 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001854 &ArgTys[0], ArgTys.size(),
1855 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001856 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001857 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001858 msgSendIdent, msgSendType,
1859 FunctionDecl::Extern, false, 0);
1860}
1861
1862// SynthMsgSendSuperStretFunctionDecl -
1863// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001864void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001865 IdentifierInfo *msgSendIdent =
1866 &Context->Idents.get("objc_msgSendSuper_stret");
1867 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001868 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001869 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001870 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001871 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1872 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1873 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001874 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001875 assert(!argT.isNull() && "Can't find 'SEL' type");
1876 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001877 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001878 &ArgTys[0], ArgTys.size(),
1879 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001880 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001881 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001882 msgSendIdent, msgSendType,
1883 FunctionDecl::Extern, false, 0);
1884}
1885
Steve Naroff1284db82008-05-08 22:02:18 +00001886// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001887void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001888 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1889 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001890 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001891 assert(!argT.isNull() && "Can't find 'id' type");
1892 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001893 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001894 assert(!argT.isNull() && "Can't find 'SEL' type");
1895 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001896 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001897 &ArgTys[0], ArgTys.size(),
1898 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001899 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001900 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001901 msgSendIdent, msgSendType,
1902 FunctionDecl::Extern, false, 0);
1903}
1904
Steve Naroff09b266e2007-10-30 23:14:51 +00001905// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001906void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001907 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1908 llvm::SmallVector<QualType, 16> ArgTys;
1909 ArgTys.push_back(Context->getPointerType(
1910 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001911 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001912 &ArgTys[0], ArgTys.size(),
1913 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001914 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001915 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001916 getClassIdent, getClassType,
1917 FunctionDecl::Extern, false, 0);
1918}
1919
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001920// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001921void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001922 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1923 llvm::SmallVector<QualType, 16> ArgTys;
1924 ArgTys.push_back(Context->getPointerType(
1925 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001926 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001927 &ArgTys[0], ArgTys.size(),
1928 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001929 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001930 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001931 getClassIdent, getClassType,
1932 FunctionDecl::Extern, false, 0);
1933}
1934
Steve Naroffb29b4272008-04-14 22:03:09 +00001935Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001936 QualType strType = getConstantStringStructType();
1937
1938 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001939
1940 std::string tmpName = InFileName;
1941 unsigned i;
1942 for (i=0; i < tmpName.length(); i++) {
1943 char c = tmpName.at(i);
1944 // replace any non alphanumeric characters with '_'.
1945 if (!isalpha(c) && (c < '0' || c > '9'))
1946 tmpName[i] = '_';
1947 }
1948 S += tmpName;
1949 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001950 S += utostr(NumObjCStringLiterals++);
1951
Steve Naroffba92b2e2008-03-27 22:29:16 +00001952 Preamble += "static __NSConstantStringImpl " + S;
1953 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1954 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001955 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001956 std::string prettyBufS;
1957 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001958 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001959 Preamble += prettyBuf.str();
1960 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001961 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001962 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001963
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001964 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001965 &Context->Idents.get(S.c_str()), strType,
1966 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001967 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1968 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1969 Context->getPointerType(DRE->getType()),
1970 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001971 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001972 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001973 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001974 delete Exp;
1975 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001976}
1977
Steve Naroffb29b4272008-04-14 22:03:09 +00001978ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001979 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001980 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1981
Chris Lattnerd9f69102008-08-10 01:53:14 +00001982 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1983 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001984 const PointerType *PT = PDE->getType()->getAsPointerType();
1985 assert(PT);
1986 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1987 return IT->getDecl();
1988 }
1989 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001990}
1991
1992// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001993QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001994 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001995 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001996 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001997 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001998 QualType FieldTypes[2];
1999
2000 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002002 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002003 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002004 // Create fields
2005 FieldDecl *FieldDecls[2];
2006
2007 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002008 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002009 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002010
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002011 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002012 }
2013 return Context->getTagDeclType(SuperStructDecl);
2014}
2015
Steve Naroffb29b4272008-04-14 22:03:09 +00002016QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002017 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002018 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002019 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002020 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002021 QualType FieldTypes[4];
2022
2023 // struct objc_object *receiver;
2024 FieldTypes[0] = Context->getObjCIdType();
2025 // int flags;
2026 FieldTypes[1] = Context->IntTy;
2027 // char *str;
2028 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2029 // long length;
2030 FieldTypes[3] = Context->LongTy;
2031 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002032 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002033
2034 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002035 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002036 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002037
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002038 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002039 }
2040 return Context->getTagDeclType(ConstantStringDecl);
2041}
2042
Steve Naroffb29b4272008-04-14 22:03:09 +00002043Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002044 if (!SelGetUidFunctionDecl)
2045 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002046 if (!MsgSendFunctionDecl)
2047 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002048 if (!MsgSendSuperFunctionDecl)
2049 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 if (!MsgSendStretFunctionDecl)
2051 SynthMsgSendStretFunctionDecl();
2052 if (!MsgSendSuperStretFunctionDecl)
2053 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002054 if (!MsgSendFpretFunctionDecl)
2055 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002056 if (!GetClassFunctionDecl)
2057 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002058 if (!GetMetaClassFunctionDecl)
2059 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002060
Steve Naroff874e2322007-11-15 10:28:18 +00002061 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2063 // May need to use objc_msgSend_stret() as well.
2064 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002065 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002066 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002067 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002068 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002069 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002070 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002071 }
Steve Naroff874e2322007-11-15 10:28:18 +00002072
Steve Naroff934f2762007-10-24 22:48:43 +00002073 // Synthesize a call to objc_msgSend().
2074 llvm::SmallVector<Expr*, 8> MsgExprs;
2075 IdentifierInfo *clsName = Exp->getClassName();
2076
2077 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2078 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002079 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2080 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002081 if (!strcmp(clsName->getName(), "super")) {
2082 MsgSendFlavor = MsgSendSuperFunctionDecl;
2083 if (MsgSendStretFlavor)
2084 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2085 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2086
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002087 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002088 CurMethodDecl->getClassInterface()->getSuperClass();
2089
2090 llvm::SmallVector<Expr*, 4> InitExprs;
2091
2092 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002093 InitExprs.push_back(new DeclRefExpr(
2094 CurMethodDecl->getSelfDecl(),
2095 Context->getObjCIdType(),
2096 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002097 llvm::SmallVector<Expr*, 8> ClsExprs;
2098 QualType argType = Context->getPointerType(Context->CharTy);
2099 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2100 SuperDecl->getIdentifier()->getLength(),
2101 false, argType, SourceLocation(),
2102 SourceLocation()));
2103 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2104 &ClsExprs[0],
2105 ClsExprs.size());
2106 // To turn off a warning, type-cast to 'id'
2107 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002108 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002109 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2110 // struct objc_super
2111 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002112 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002113
Steve Naroff23f41272008-03-11 18:14:26 +00002114 if (LangOpts.Microsoft) {
2115 SynthSuperContructorFunctionDecl();
2116 // Simulate a contructor call...
2117 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2118 superType, SourceLocation());
2119 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2120 superType, SourceLocation());
2121 } else {
2122 // (struct objc_super) { <exprs from above> }
2123 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2124 &InitExprs[0], InitExprs.size(),
2125 SourceLocation());
2126 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2127 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002128 // struct objc_super *
2129 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2130 Context->getPointerType(SuperRep->getType()),
2131 SourceLocation());
2132 MsgExprs.push_back(Unop);
2133 } else {
2134 llvm::SmallVector<Expr*, 8> ClsExprs;
2135 QualType argType = Context->getPointerType(Context->CharTy);
2136 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2137 clsName->getLength(),
2138 false, argType, SourceLocation(),
2139 SourceLocation()));
2140 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2141 &ClsExprs[0],
2142 ClsExprs.size());
2143 MsgExprs.push_back(Cls);
2144 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002145 } else { // instance message.
2146 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002148 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002149 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002150 if (MsgSendStretFlavor)
2151 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002152 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2153
2154 llvm::SmallVector<Expr*, 4> InitExprs;
2155
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002156 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002157 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002158 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2159 Context->getObjCIdType(),
2160 SourceLocation()),
2161 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002162
2163 llvm::SmallVector<Expr*, 8> ClsExprs;
2164 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002165 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2166 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002167 false, argType, SourceLocation(),
2168 SourceLocation()));
2169 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002170 &ClsExprs[0],
2171 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002172 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002173 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002174 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002175 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002176 // struct objc_super
2177 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002178 Expr *SuperRep;
2179
2180 if (LangOpts.Microsoft) {
2181 SynthSuperContructorFunctionDecl();
2182 // Simulate a contructor call...
2183 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2184 superType, SourceLocation());
2185 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2186 superType, SourceLocation());
2187 } else {
2188 // (struct objc_super) { <exprs from above> }
2189 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2190 &InitExprs[0], InitExprs.size(),
2191 SourceLocation());
2192 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2193 }
Steve Naroff874e2322007-11-15 10:28:18 +00002194 // struct objc_super *
2195 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2196 Context->getPointerType(SuperRep->getType()),
2197 SourceLocation());
2198 MsgExprs.push_back(Unop);
2199 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002200 // Remove all type-casts because it may contain objc-style types; e.g.
2201 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002202 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002203 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002204 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2205 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002206 MsgExprs.push_back(recExpr);
2207 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002208 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002209 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002210 llvm::SmallVector<Expr*, 8> SelExprs;
2211 QualType argType = Context->getPointerType(Context->CharTy);
2212 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2213 Exp->getSelector().getName().size(),
2214 false, argType, SourceLocation(),
2215 SourceLocation()));
2216 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2217 &SelExprs[0], SelExprs.size());
2218 MsgExprs.push_back(SelExp);
2219
2220 // Now push any user supplied arguments.
2221 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002222 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002223 // Make all implicit casts explicit...ICE comes in handy:-)
2224 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2225 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002226 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002227 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002228 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002229 }
2230 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002231 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002232 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002233 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002234 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002235 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002236 userExpr, SourceLocation());
2237 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002238 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002239 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002240 // We've transferred the ownership to MsgExprs. Null out the argument in
2241 // the original expression, since we will delete it below.
2242 Exp->setArg(i, 0);
2243 }
Steve Naroffab972d32007-11-04 22:37:50 +00002244 // Generate the funky cast.
2245 CastExpr *cast;
2246 llvm::SmallVector<QualType, 8> ArgTypes;
2247 QualType returnType;
2248
2249 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002250 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2251 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2252 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002253 ArgTypes.push_back(Context->getObjCIdType());
2254 ArgTypes.push_back(Context->getObjCSelType());
2255 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002256 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002257 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002258 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2259 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002260 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002261 ArgTypes.push_back(t);
2262 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002263 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2264 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002265 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002266 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002267 }
2268 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002269 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002270
2271 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002272 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2273 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002274
2275 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2276 // If we don't do this cast, we get the following bizarre warning/note:
2277 // xx.m:13: warning: function called through a non-compatible type
2278 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002279 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002280 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002281
Steve Naroffab972d32007-11-04 22:37:50 +00002282 // Now do the "normal" pointer to function cast.
2283 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002284 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002285 // If we don't have a method decl, force a variadic cast.
2286 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002287 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002288 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002289
2290 // Don't forget the parens to enforce the proper binding.
2291 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2292
2293 const FunctionType *FT = msgSendType->getAsFunctionType();
2294 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2295 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002296 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002297 if (MsgSendStretFlavor) {
2298 // We have the method which returns a struct/union. Must also generate
2299 // call to objc_msgSend_stret and hang both varieties on a conditional
2300 // expression which dictate which one to envoke depending on size of
2301 // method's return type.
2302
2303 // Create a reference to the objc_msgSend_stret() declaration.
2304 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2305 SourceLocation());
2306 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002307 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002308 SourceLocation());
2309 // Now do the "normal" pointer to function cast.
2310 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002311 &ArgTypes[0], ArgTypes.size(),
2312 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002313 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002314 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002315
2316 // Don't forget the parens to enforce the proper binding.
2317 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2318
2319 FT = msgSendType->getAsFunctionType();
2320 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2321 FT->getResultType(), SourceLocation());
2322
2323 // Build sizeof(returnType)
2324 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2325 returnType, Context->getSizeType(),
2326 SourceLocation(), SourceLocation());
2327 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2328 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2329 // For X86 it is more complicated and some kind of target specific routine
2330 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002331 unsigned IntSize =
2332 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002333 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2334 Context->IntTy,
2335 SourceLocation());
2336 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2337 BinaryOperator::LE,
2338 Context->IntTy,
2339 SourceLocation());
2340 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2341 ConditionalOperator *CondExpr =
2342 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002343 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002344 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002345 return ReplacingStmt;
2346}
2347
Steve Naroffb29b4272008-04-14 22:03:09 +00002348Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002349 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002350 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002351 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002352
Chris Lattnere64b7772007-10-24 16:57:36 +00002353 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002354 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002355}
2356
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002357/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2358/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002359Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002360 if (!GetProtocolFunctionDecl)
2361 SynthGetProtocolFunctionDecl();
2362 // Create a call to objc_getProtocol("ProtocolName").
2363 llvm::SmallVector<Expr*, 8> ProtoExprs;
2364 QualType argType = Context->getPointerType(Context->CharTy);
2365 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2366 strlen(Exp->getProtocol()->getName()),
2367 false, argType, SourceLocation(),
2368 SourceLocation()));
2369 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2370 &ProtoExprs[0],
2371 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002372 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002373 delete Exp;
2374 return ProtoExp;
2375
2376}
2377
Steve Naroffbaf58c32008-05-31 14:15:04 +00002378bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2379 const char *endBuf) {
2380 while (startBuf < endBuf) {
2381 if (*startBuf == '#') {
2382 // Skip whitespace.
2383 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2384 ;
2385 if (!strncmp(startBuf, "if", strlen("if")) ||
2386 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2387 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2388 !strncmp(startBuf, "define", strlen("define")) ||
2389 !strncmp(startBuf, "undef", strlen("undef")) ||
2390 !strncmp(startBuf, "else", strlen("else")) ||
2391 !strncmp(startBuf, "elif", strlen("elif")) ||
2392 !strncmp(startBuf, "endif", strlen("endif")) ||
2393 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2394 !strncmp(startBuf, "include", strlen("include")) ||
2395 !strncmp(startBuf, "import", strlen("import")) ||
2396 !strncmp(startBuf, "include_next", strlen("include_next")))
2397 return true;
2398 }
2399 startBuf++;
2400 }
2401 return false;
2402}
2403
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002405/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002406void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002407 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002408 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2409 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002410 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002412 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002414 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002415 SourceLocation LocStart = CDecl->getLocStart();
2416 SourceLocation LocEnd = CDecl->getLocEnd();
2417
2418 const char *startBuf = SM->getCharacterData(LocStart);
2419 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002420
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002421 // If no ivars and no root or if its root, directly or indirectly,
2422 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002423 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2424 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002425 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002426 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002427 return;
2428 }
2429
2430 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002432 Result += "\nstruct ";
2433 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002434 if (LangOpts.Microsoft)
2435 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002436
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002437 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002438 const char *cursor = strchr(startBuf, '{');
2439 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002440 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002441 // If the buffer contains preprocessor directives, we do more fine-grained
2442 // rewrites. This is intended to fix code that looks like (which occurs in
2443 // NSURL.h, for example):
2444 //
2445 // #ifdef XYZ
2446 // @interface Foo : NSObject
2447 // #else
2448 // @interface FooBar : NSObject
2449 // #endif
2450 // {
2451 // int i;
2452 // }
2453 // @end
2454 //
2455 // This clause is segregated to avoid breaking the common case.
2456 if (BufferContainsPPDirectives(startBuf, cursor)) {
2457 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2458 CDecl->getClassLoc();
2459 const char *endHeader = SM->getCharacterData(L);
2460 endHeader += Lexer::MeasureTokenLength(L, *SM);
2461
Chris Lattner3db6cae2008-07-21 18:19:38 +00002462 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002463 // advance to the end of the referenced protocols.
2464 while (endHeader < cursor && *endHeader != '>') endHeader++;
2465 endHeader++;
2466 }
2467 // rewrite the original header
2468 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2469 } else {
2470 // rewrite the original header *without* disturbing the '{'
2471 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2472 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002473 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002474 Result = "\n struct ";
2475 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002476 Result += "_IMPL ";
2477 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002478 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002479
2480 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002481 SourceLocation OnePastCurly =
2482 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2483 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002484 }
2485 cursor++; // past '{'
2486
2487 // Now comment out any visibility specifiers.
2488 while (cursor < endBuf) {
2489 if (*cursor == '@') {
2490 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002491 // Skip whitespace.
2492 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2493 /*scan*/;
2494
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002495 // FIXME: presence of @public, etc. inside comment results in
2496 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002497 if (!strncmp(cursor, "public", strlen("public")) ||
2498 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002499 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002500 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002501 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002502 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002503 // FIXME: If there are cases where '<' is used in ivar declaration part
2504 // of user code, then scan the ivar list and use needToScanForQualifiers
2505 // for type checking.
2506 else if (*cursor == '<') {
2507 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002508 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002509 cursor = strchr(cursor, '>');
2510 cursor++;
2511 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002512 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002513 }
Steve Narofffea763e82007-11-14 19:25:57 +00002514 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002515 }
Steve Narofffea763e82007-11-14 19:25:57 +00002516 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002517 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002518 } else { // we don't have any instance variables - insert super struct.
2519 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2520 Result += " {\n struct ";
2521 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002522 Result += "_IMPL ";
2523 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002524 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002525 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002526 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002527 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002529 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002530}
2531
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002532// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002533/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002534void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002535 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002536 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002537 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002538 const char *ClassName,
2539 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002540 if (MethodBegin == MethodEnd) return;
2541
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002542 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002543 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002544 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002545 SEL _cmd;
2546 char *method_types;
2547 void *_imp;
2548 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002549 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002550 Result += "\nstruct _objc_method {\n";
2551 Result += "\tSEL _cmd;\n";
2552 Result += "\tchar *method_types;\n";
2553 Result += "\tvoid *_imp;\n";
2554 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002555
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002556 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002557 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002558
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002559 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002560
2561 /* struct {
2562 struct _objc_method_list *next_method;
2563 int method_count;
2564 struct _objc_method method_list[];
2565 }
2566 */
2567 Result += "\nstatic struct {\n";
2568 Result += "\tstruct _objc_method_list *next_method;\n";
2569 Result += "\tint method_count;\n";
2570 Result += "\tstruct _objc_method method_list[";
2571 Result += utostr(MethodEnd-MethodBegin);
2572 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002573 Result += prefix;
2574 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2575 Result += "_METHODS_";
2576 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002577 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002578 Result += IsInstanceMethod ? "inst" : "cls";
2579 Result += "_meth\")))= ";
2580 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002581
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002582 Result += "\t,{{(SEL)\"";
2583 Result += (*MethodBegin)->getSelector().getName().c_str();
2584 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002585 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002586 Result += "\", \"";
2587 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002588 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002589 Result += MethodInternalNames[*MethodBegin];
2590 Result += "}\n";
2591 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2592 Result += "\t ,{(SEL)\"";
2593 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002594 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002596 Result += "\", \"";
2597 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002598 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002599 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002600 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002601 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002602 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002603}
2604
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002605/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002606void RewriteObjC::
2607RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2608 const char *prefix,
2609 const char *ClassName,
2610 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002611 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002612 if (Protocols.empty()) return;
2613
2614 for (unsigned i = 0; i != Protocols.size(); i++) {
2615 ObjCProtocolDecl *PDecl = Protocols[i];
2616 // Output struct protocol_methods holder of method selector and type.
2617 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2618 /* struct protocol_methods {
2619 SEL _cmd;
2620 char *method_types;
2621 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002622 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002623 Result += "\nstruct protocol_methods {\n";
2624 Result += "\tSEL _cmd;\n";
2625 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002626 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002627
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002628 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002629 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002630 // Do not synthesize the protocol more than once.
2631 if (ObjCSynthesizedProtocols.count(PDecl))
2632 continue;
2633
2634 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2635 unsigned NumMethods = PDecl->getNumInstanceMethods();
2636 /* struct _objc_protocol_method_list {
2637 int protocol_method_count;
2638 struct protocol_methods protocols[];
2639 }
2640 */
2641 Result += "\nstatic struct {\n";
2642 Result += "\tint protocol_method_count;\n";
2643 Result += "\tstruct protocol_methods protocols[";
2644 Result += utostr(NumMethods);
2645 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2646 Result += PDecl->getName();
2647 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2648 "{\n\t" + utostr(NumMethods) + "\n";
2649
2650 // Output instance methods declared in this protocol.
2651 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2652 E = PDecl->instmeth_end(); I != E; ++I) {
2653 if (I == PDecl->instmeth_begin())
2654 Result += "\t ,{{(SEL)\"";
2655 else
2656 Result += "\t ,{(SEL)\"";
2657 Result += (*I)->getSelector().getName().c_str();
2658 std::string MethodTypeString;
2659 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2660 Result += "\", \"";
2661 Result += MethodTypeString;
2662 Result += "\"}\n";
2663 }
2664 Result += "\t }\n};\n";
2665 }
2666
2667 // Output class methods declared in this protocol.
2668 int NumMethods = PDecl->getNumClassMethods();
2669 if (NumMethods > 0) {
2670 /* struct _objc_protocol_method_list {
2671 int protocol_method_count;
2672 struct protocol_methods protocols[];
2673 }
2674 */
2675 Result += "\nstatic struct {\n";
2676 Result += "\tint protocol_method_count;\n";
2677 Result += "\tstruct protocol_methods protocols[";
2678 Result += utostr(NumMethods);
2679 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2680 Result += PDecl->getName();
2681 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2682 "{\n\t";
2683 Result += utostr(NumMethods);
2684 Result += "\n";
2685
2686 // Output instance methods declared in this protocol.
2687 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2688 E = PDecl->classmeth_end(); I != E; ++I) {
2689 if (I == PDecl->classmeth_begin())
2690 Result += "\t ,{{(SEL)\"";
2691 else
2692 Result += "\t ,{(SEL)\"";
2693 Result += (*I)->getSelector().getName().c_str();
2694 std::string MethodTypeString;
2695 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2696 Result += "\", \"";
2697 Result += MethodTypeString;
2698 Result += "\"}\n";
2699 }
2700 Result += "\t }\n};\n";
2701 }
2702
2703 // Output:
2704 /* struct _objc_protocol {
2705 // Objective-C 1.0 extensions
2706 struct _objc_protocol_extension *isa;
2707 char *protocol_name;
2708 struct _objc_protocol **protocol_list;
2709 struct _objc_protocol_method_list *instance_methods;
2710 struct _objc_protocol_method_list *class_methods;
2711 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002712 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002713 static bool objc_protocol = false;
2714 if (!objc_protocol) {
2715 Result += "\nstruct _objc_protocol {\n";
2716 Result += "\tstruct _objc_protocol_extension *isa;\n";
2717 Result += "\tchar *protocol_name;\n";
2718 Result += "\tstruct _objc_protocol **protocol_list;\n";
2719 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2720 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2721 Result += "};\n";
2722
2723 objc_protocol = true;
2724 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002725
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002726 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2727 Result += PDecl->getName();
2728 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2729 "{\n\t0, \"";
2730 Result += PDecl->getName();
2731 Result += "\", 0, ";
2732 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2733 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2734 Result += PDecl->getName();
2735 Result += ", ";
2736 }
2737 else
2738 Result += "0, ";
2739 if (PDecl->getNumClassMethods() > 0) {
2740 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2741 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002743 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002744 else
2745 Result += "0\n";
2746 Result += "};\n";
2747
2748 // Mark this protocol as having been generated.
2749 if (!ObjCSynthesizedProtocols.insert(PDecl))
2750 assert(false && "protocol already synthesized");
2751 }
2752 // Output the top lovel protocol meta-data for the class.
2753 /* struct _objc_protocol_list {
2754 struct _objc_protocol_list *next;
2755 int protocol_count;
2756 struct _objc_protocol *class_protocols[];
2757 }
2758 */
2759 Result += "\nstatic struct {\n";
2760 Result += "\tstruct _objc_protocol_list *next;\n";
2761 Result += "\tint protocol_count;\n";
2762 Result += "\tstruct _objc_protocol *class_protocols[";
2763 Result += utostr(Protocols.size());
2764 Result += "];\n} _OBJC_";
2765 Result += prefix;
2766 Result += "_PROTOCOLS_";
2767 Result += ClassName;
2768 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2769 "{\n\t0, ";
2770 Result += utostr(Protocols.size());
2771 Result += "\n";
2772
2773 Result += "\t,{&_OBJC_PROTOCOL_";
2774 Result += Protocols[0]->getName();
2775 Result += " \n";
2776
2777 for (unsigned i = 1; i != Protocols.size(); i++) {
2778 Result += "\t ,&_OBJC_PROTOCOL_";
2779 Result += Protocols[i]->getName();
2780 Result += "\n";
2781 }
2782 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002783}
2784
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002785/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002787void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002788 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002789 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002790 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002791 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2793 CDecl = CDecl->getNextClassCategory())
2794 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2795 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002796
Chris Lattnereb44eee2007-12-23 01:40:15 +00002797 std::string FullCategoryName = ClassDecl->getName();
2798 FullCategoryName += '_';
2799 FullCategoryName += IDecl->getName();
2800
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002801 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002802 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002803 true, "CATEGORY_", FullCategoryName.c_str(),
2804 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002805
2806 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002807 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002808 false, "CATEGORY_", FullCategoryName.c_str(),
2809 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002810
2811 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002812 // Null CDecl is case of a category implementation with no category interface
2813 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002814 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002815 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002816
2817 /* struct _objc_category {
2818 char *category_name;
2819 char *class_name;
2820 struct _objc_method_list *instance_methods;
2821 struct _objc_method_list *class_methods;
2822 struct _objc_protocol_list *protocols;
2823 // Objective-C 1.0 extensions
2824 uint32_t size; // sizeof (struct _objc_category)
2825 struct _objc_property_list *instance_properties; // category's own
2826 // @property decl.
2827 };
2828 */
2829
2830 static bool objc_category = false;
2831 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 Result += "\nstruct _objc_category {\n";
2833 Result += "\tchar *category_name;\n";
2834 Result += "\tchar *class_name;\n";
2835 Result += "\tstruct _objc_method_list *instance_methods;\n";
2836 Result += "\tstruct _objc_method_list *class_methods;\n";
2837 Result += "\tstruct _objc_protocol_list *protocols;\n";
2838 Result += "\tunsigned int size;\n";
2839 Result += "\tstruct _objc_property_list *instance_properties;\n";
2840 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002841 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002842 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2844 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002845 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002846 Result += IDecl->getName();
2847 Result += "\"\n\t, \"";
2848 Result += ClassDecl->getName();
2849 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002850
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002851 if (IDecl->getNumInstanceMethods() > 0) {
2852 Result += "\t, (struct _objc_method_list *)"
2853 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2854 Result += FullCategoryName;
2855 Result += "\n";
2856 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002857 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002858 Result += "\t, 0\n";
2859 if (IDecl->getNumClassMethods() > 0) {
2860 Result += "\t, (struct _objc_method_list *)"
2861 "&_OBJC_CATEGORY_CLASS_METHODS_";
2862 Result += FullCategoryName;
2863 Result += "\n";
2864 }
2865 else
2866 Result += "\t, 0\n";
2867
Chris Lattner780f3292008-07-21 21:32:27 +00002868 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002869 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2870 Result += FullCategoryName;
2871 Result += "\n";
2872 }
2873 else
2874 Result += "\t, 0\n";
2875 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002876}
2877
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002878/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2879/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002880void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002881 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002882 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002883 if (ivar->isBitField()) {
2884 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2885 // place all bitfields at offset 0.
2886 Result += "0";
2887 } else {
2888 Result += "__OFFSETOFIVAR__(struct ";
2889 Result += IDecl->getName();
2890 if (LangOpts.Microsoft)
2891 Result += "_IMPL";
2892 Result += ", ";
2893 Result += ivar->getName();
2894 Result += ")";
2895 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002896}
2897
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002898//===----------------------------------------------------------------------===//
2899// Meta Data Emission
2900//===----------------------------------------------------------------------===//
2901
Steve Naroffb29b4272008-04-14 22:03:09 +00002902void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002903 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002904 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002905
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002906 // Explictly declared @interface's are already synthesized.
2907 if (CDecl->ImplicitInterfaceDecl()) {
2908 // FIXME: Implementation of a class with no @interface (legacy) doese not
2909 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002910 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002911 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002912
Chris Lattnerbe6df082007-12-12 07:56:42 +00002913 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002914 unsigned NumIvars = !IDecl->ivar_empty()
2915 ? IDecl->ivar_size()
2916 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002917 if (NumIvars > 0) {
2918 static bool objc_ivar = false;
2919 if (!objc_ivar) {
2920 /* struct _objc_ivar {
2921 char *ivar_name;
2922 char *ivar_type;
2923 int ivar_offset;
2924 };
2925 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002926 Result += "\nstruct _objc_ivar {\n";
2927 Result += "\tchar *ivar_name;\n";
2928 Result += "\tchar *ivar_type;\n";
2929 Result += "\tint ivar_offset;\n";
2930 Result += "};\n";
2931
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002932 objc_ivar = true;
2933 }
2934
Steve Naroff946a6932008-03-11 00:12:29 +00002935 /* struct {
2936 int ivar_count;
2937 struct _objc_ivar ivar_list[nIvars];
2938 };
2939 */
2940 Result += "\nstatic struct {\n";
2941 Result += "\tint ivar_count;\n";
2942 Result += "\tstruct _objc_ivar ivar_list[";
2943 Result += utostr(NumIvars);
2944 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002945 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002946 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002947 "{\n\t";
2948 Result += utostr(NumIvars);
2949 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002950
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002951 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002952 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002953 IVI = IDecl->ivar_begin();
2954 IVE = IDecl->ivar_end();
2955 } else {
2956 IVI = CDecl->ivar_begin();
2957 IVE = CDecl->ivar_end();
2958 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002959 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002960 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002961 Result += "\", \"";
2962 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002963 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002964 Result += StrEncoding;
2965 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002966 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002967 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002968 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002969 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002970 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002971 Result += "\", \"";
2972 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002973 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002974 Result += StrEncoding;
2975 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002976 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002977 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002978 }
2979
2980 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002981 }
2982
2983 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002984 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002985 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002986
2987 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002989 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002991 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002992 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002993 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002995
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002996 // Declaration of class/meta-class metadata
2997 /* struct _objc_class {
2998 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002999 const char *super_class_name;
3000 char *name;
3001 long version;
3002 long info;
3003 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003004 struct _objc_ivar_list *ivars;
3005 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003006 struct objc_cache *cache;
3007 struct objc_protocol_list *protocols;
3008 const char *ivar_layout;
3009 struct _objc_class_ext *ext;
3010 };
3011 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003012 static bool objc_class = false;
3013 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003014 Result += "\nstruct _objc_class {\n";
3015 Result += "\tstruct _objc_class *isa;\n";
3016 Result += "\tconst char *super_class_name;\n";
3017 Result += "\tchar *name;\n";
3018 Result += "\tlong version;\n";
3019 Result += "\tlong info;\n";
3020 Result += "\tlong instance_size;\n";
3021 Result += "\tstruct _objc_ivar_list *ivars;\n";
3022 Result += "\tstruct _objc_method_list *methods;\n";
3023 Result += "\tstruct objc_cache *cache;\n";
3024 Result += "\tstruct _objc_protocol_list *protocols;\n";
3025 Result += "\tconst char *ivar_layout;\n";
3026 Result += "\tstruct _objc_class_ext *ext;\n";
3027 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003028 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003029 }
3030
3031 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003032 ObjCInterfaceDecl *RootClass = 0;
3033 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003034 while (SuperClass) {
3035 RootClass = SuperClass;
3036 SuperClass = SuperClass->getSuperClass();
3037 }
3038 SuperClass = CDecl->getSuperClass();
3039
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003040 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3041 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003042 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003043 "{\n\t(struct _objc_class *)\"";
3044 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3045 Result += "\"";
3046
3047 if (SuperClass) {
3048 Result += ", \"";
3049 Result += SuperClass->getName();
3050 Result += "\", \"";
3051 Result += CDecl->getName();
3052 Result += "\"";
3053 }
3054 else {
3055 Result += ", 0, \"";
3056 Result += CDecl->getName();
3057 Result += "\"";
3058 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003059 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003060 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003062 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003063 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003064 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003065 Result += "\n";
3066 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003067 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003068 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003069 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003070 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003071 Result += CDecl->getName();
3072 Result += ",0,0\n";
3073 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003074 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003075 Result += "\t,0,0,0,0\n";
3076 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003077
3078 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003079 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3080 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003081 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003082 "{\n\t&_OBJC_METACLASS_";
3083 Result += CDecl->getName();
3084 if (SuperClass) {
3085 Result += ", \"";
3086 Result += SuperClass->getName();
3087 Result += "\", \"";
3088 Result += CDecl->getName();
3089 Result += "\"";
3090 }
3091 else {
3092 Result += ", 0, \"";
3093 Result += CDecl->getName();
3094 Result += "\"";
3095 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003096 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003097 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003098 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003099 Result += ",0";
3100 else {
3101 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003102 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003103 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003104 if (LangOpts.Microsoft)
3105 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003106 Result += ")";
3107 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003108 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003109 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003110 Result += CDecl->getName();
3111 Result += "\n\t";
3112 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003113 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003114 Result += ",0";
3115 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003116 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 Result += CDecl->getName();
3118 Result += ", 0\n\t";
3119 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003120 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003121 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003122 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003123 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003124 Result += CDecl->getName();
3125 Result += ", 0,0\n";
3126 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003127 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003128 Result += ",0,0,0\n";
3129 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003130}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003131
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003132/// RewriteImplementations - This routine rewrites all method implementations
3133/// and emits meta-data.
3134
Steve Naroffb29b4272008-04-14 22:03:09 +00003135void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003136 int ClsDefCount = ClassImplementation.size();
3137 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003138
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003139 if (ClsDefCount == 0 && CatDefCount == 0)
3140 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003141 // Rewrite implemented methods
3142 for (int i = 0; i < ClsDefCount; i++)
3143 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003144
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003145 for (int i = 0; i < CatDefCount; i++)
3146 RewriteImplementationDecl(CategoryImplementation[i]);
3147
Steve Naroff5df5b762008-05-07 21:23:49 +00003148 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003149 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003150 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003151 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003152 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003153
3154 // For each implemented category, write out all its meta data.
3155 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003156 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003158 // Write objc_symtab metadata
3159 /*
3160 struct _objc_symtab
3161 {
3162 long sel_ref_cnt;
3163 SEL *refs;
3164 short cls_def_cnt;
3165 short cat_def_cnt;
3166 void *defs[cls_def_cnt + cat_def_cnt];
3167 };
3168 */
3169
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003170 Result += "\nstruct _objc_symtab {\n";
3171 Result += "\tlong sel_ref_cnt;\n";
3172 Result += "\tSEL *refs;\n";
3173 Result += "\tshort cls_def_cnt;\n";
3174 Result += "\tshort cat_def_cnt;\n";
3175 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3176 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003177
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003178 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003179 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003180 Result += "\t0, 0, " + utostr(ClsDefCount)
3181 + ", " + utostr(CatDefCount) + "\n";
3182 for (int i = 0; i < ClsDefCount; i++) {
3183 Result += "\t,&_OBJC_CLASS_";
3184 Result += ClassImplementation[i]->getName();
3185 Result += "\n";
3186 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003187
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188 for (int i = 0; i < CatDefCount; i++) {
3189 Result += "\t,&_OBJC_CATEGORY_";
3190 Result += CategoryImplementation[i]->getClassInterface()->getName();
3191 Result += "_";
3192 Result += CategoryImplementation[i]->getName();
3193 Result += "\n";
3194 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003195
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003196 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003197
3198 // Write objc_module metadata
3199
3200 /*
3201 struct _objc_module {
3202 long version;
3203 long size;
3204 const char *name;
3205 struct _objc_symtab *symtab;
3206 }
3207 */
3208
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003209 Result += "\nstruct _objc_module {\n";
3210 Result += "\tlong version;\n";
3211 Result += "\tlong size;\n";
3212 Result += "\tconst char *name;\n";
3213 Result += "\tstruct _objc_symtab *symtab;\n";
3214 Result += "};\n\n";
3215 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003216 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003217 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3218 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003220
3221 if (LangOpts.Microsoft) {
3222 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003223 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003224 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3225 Result += "&_OBJC_MODULES;\n";
3226 Result += "#pragma data_seg(pop)\n\n";
3227 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003228}
Chris Lattner311ff022007-10-16 22:36:42 +00003229
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003230
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003231
3232