blob: d23bf2d22535ecb85aa6ac708f0be852375d1d0e [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;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000060 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000061
Steve Naroffd82a9ab2008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000075
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000079
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff874e2322007-11-15 10:28:18 +000083 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000084 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000087
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffa7b402d2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
95
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000096 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000097 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +000098 virtual void Initialize(ASTContext &context);
99
100 virtual void InitializeTU(TranslationUnit &TU) {
101 TU.SetOwnsDecls(false);
102 Initialize(TU.getContext());
103 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000104
Chris Lattner8a12c272007-10-11 18:38:32 +0000105
Chris Lattnerf04da132007-10-24 17:06:59 +0000106 // Top Level Driver code.
107 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000108 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000109 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000110 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000111
112 ~RewriteObjC() {}
113
114 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000115
116 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000117 // If replacement succeeded or warning disabled return with no warning.
118 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000119 return;
120
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000121 SourceRange Range = Old->getSourceRange();
122 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
123 0, 0, &Range, 1);
124 }
125
Steve Naroffba92b2e2008-03-27 22:29:16 +0000126 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
127 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000128 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000129 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000130 SilenceRewriteMacroWarning)
131 return;
132
133 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
134 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000135
Chris Lattneraadaf782008-01-31 19:51:04 +0000136 void RemoveText(SourceLocation Loc, unsigned StrLen) {
137 // If removal succeeded or warning disabled return with no warning.
138 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
139 return;
140
141 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
142 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000143
Chris Lattneraadaf782008-01-31 19:51:04 +0000144 void ReplaceText(SourceLocation Start, unsigned OrigLength,
145 const char *NewStr, unsigned NewLength) {
146 // If removal succeeded or warning disabled return with no warning.
147 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
148 SilenceRewriteMacroWarning)
149 return;
150
151 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
152 }
153
Chris Lattnerf04da132007-10-24 17:06:59 +0000154 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000155 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000156 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000157 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
159 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000160 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000161 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
162 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
163 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
164 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
165 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000166 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000167 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000168 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000169 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000170 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000172 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000173 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000174 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000175
Chris Lattnerf04da132007-10-24 17:06:59 +0000176 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000177 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000178 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000179 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000180 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000181 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000182 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000183 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000185 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000186 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
187 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
188 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000189 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
190 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000191 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
192 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000193 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000194 Stmt *RewriteBreakStmt(BreakStmt *S);
195 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000196 void SynthCountByEnumWithState(std::string &buf);
197
Steve Naroff09b266e2007-10-30 23:14:51 +0000198 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000199 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000200 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000201 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000202 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000203 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000204 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000205 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000206 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000207 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000208
Chris Lattnerf04da132007-10-24 17:06:59 +0000209 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000211 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000212
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000213 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000214 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000215
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
217 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000218 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000219 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000220 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000221 const char *ClassName,
222 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000223
Chris Lattner780f3292008-07-21 21:32:27 +0000224 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
225 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000227 const char *ClassName,
228 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000230 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
232 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000233 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000234 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000235 };
236}
237
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000238static bool IsHeaderFile(const std::string &Filename) {
239 std::string::size_type DotPos = Filename.rfind('.');
240
241 if (DotPos == std::string::npos) {
242 // no file extension
243 return false;
244 }
245
246 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
247 // C header: .h
248 // C++ header: .hh or .H;
249 return Ext == "h" || Ext == "hh" || Ext == "H";
250}
251
Steve Naroffb29b4272008-04-14 22:03:09 +0000252RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000253 Diagnostic &D, const LangOptions &LOpts)
254 : Diags(D), LangOpts(LOpts) {
255 IsHeader = IsHeaderFile(inFile);
256 InFileName = inFile;
257 OutFileName = outFile;
258 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
259 "rewriting sub-expression within a macro (may not be correct)");
260}
261
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000262ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000263 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000264 Diagnostic &Diags,
265 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000266 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000267}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000268
Steve Naroffb29b4272008-04-14 22:03:09 +0000269void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000270 Context = &context;
271 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000272 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000273 MsgSendFunctionDecl = 0;
274 MsgSendSuperFunctionDecl = 0;
275 MsgSendStretFunctionDecl = 0;
276 MsgSendSuperStretFunctionDecl = 0;
277 MsgSendFpretFunctionDecl = 0;
278 GetClassFunctionDecl = 0;
279 GetMetaClassFunctionDecl = 0;
280 SelGetUidFunctionDecl = 0;
281 CFStringFunctionDecl = 0;
282 GetProtocolFunctionDecl = 0;
283 ConstantStringClassReference = 0;
284 NSStringRecord = 0;
285 CurMethodDecl = 0;
286 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000287 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000288 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000289 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000290 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000291
292 // Get the ID and start/end of the main file.
293 MainFileID = SM->getMainFileID();
294 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
295 MainFileStart = MainBuf->getBufferStart();
296 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000297
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000298 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000299
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000300 // declaring objc_selector outside the parameter list removes a silly
301 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000302 if (IsHeader)
303 Preamble = "#pragma once\n";
304 Preamble += "struct objc_selector; struct objc_class;\n";
305 Preamble += "#ifndef OBJC_SUPER\n";
306 Preamble += "struct objc_super { struct objc_object *object; ";
307 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000308 if (LangOpts.Microsoft) {
309 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000310 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
311 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000312 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000313 Preamble += "};\n";
314 Preamble += "#define OBJC_SUPER\n";
315 Preamble += "#endif\n";
316 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
317 Preamble += "typedef struct objc_object Protocol;\n";
318 Preamble += "#define _REWRITER_typedef_Protocol\n";
319 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000320 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000321 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
322 else
323 Preamble += "#define __OBJC_RW_EXTERN extern\n";
324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000325 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000327 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000328 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000329 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000331 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000332 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000333 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000334 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000335 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000336 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000337 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000338 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
339 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
340 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
341 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
342 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000343 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000344 // @synchronized hooks.
345 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
346 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000347 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000348 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
349 Preamble += "struct __objcFastEnumerationState {\n\t";
350 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000351 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000352 Preamble += "unsigned long *mutationsPtr;\n\t";
353 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000354 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000355 Preamble += "#define __FASTENUMERATIONSTATE\n";
356 Preamble += "#endif\n";
357 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
358 Preamble += "struct __NSConstantStringImpl {\n";
359 Preamble += " int *isa;\n";
360 Preamble += " int flags;\n";
361 Preamble += " char *str;\n";
362 Preamble += " long length;\n";
363 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000364 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
365 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
366 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000367 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000368 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000369 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
370 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000371 if (LangOpts.Microsoft) {
372 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000373 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000374 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000375}
376
377
Chris Lattnerf04da132007-10-24 17:06:59 +0000378//===----------------------------------------------------------------------===//
379// Top Level Driver Code
380//===----------------------------------------------------------------------===//
381
Steve Naroffb29b4272008-04-14 22:03:09 +0000382void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000383 // Two cases: either the decl could be in the main file, or it could be in a
384 // #included file. If the former, rewrite it now. If the later, check to see
385 // if we rewrote the #include/#import.
386 SourceLocation Loc = D->getLocation();
387 Loc = SM->getLogicalLoc(Loc);
388
389 // If this is for a builtin, ignore it.
390 if (Loc.isInvalid()) return;
391
Steve Naroffebf2b562007-10-23 23:50:29 +0000392 // Look for built-in declarations that we need to refer during the rewrite.
393 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000394 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000395 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000396 // declared in <Foundation/NSString.h>
397 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
398 ConstantStringClassReference = FVD;
399 return;
400 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000401 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000402 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000403 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000404 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000405 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000406 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000407 } else if (ObjCForwardProtocolDecl *FP =
408 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000409 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000410 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000411 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000412 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000413 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000414}
415
Chris Lattnerf04da132007-10-24 17:06:59 +0000416/// HandleDeclInMainFile - This is called for each top-level decl defined in the
417/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000418void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
420 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000421 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000422
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000423 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000424 if (Stmt *Body = MD->getBody()) {
425 //Body->dump();
426 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000427 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000428 CurMethodDecl = 0;
429 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000430 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000431 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000432 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000433 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000434 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000435 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000436 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000437 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000438 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000439 if (VD->getInit())
440 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
441 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000442 // Nothing yet.
443}
444
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000445void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000446 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000447
448 // Rewrite tabs if we care.
449 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000450
Steve Naroffa7b402d2008-03-28 22:26:09 +0000451 if (Diags.hasErrorOccurred())
452 return;
453
454 // Create the output file.
455
Ted Kremeneka95d3752008-09-13 05:16:45 +0000456 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
457 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000458 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000459 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000460 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000461 std::string Err;
462 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
463 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000464 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000465 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000466 } else {
467 llvm::sys::Path Path(InFileName);
468 Path.eraseSuffix();
469 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000470 std::string Err;
471 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
472 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000473 }
474
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000475 RewriteInclude();
476
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
478 Preamble.c_str(), Preamble.size(), false);
479
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000480 // Rewrite Objective-c meta data*
481 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000482 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000483
Chris Lattnerf04da132007-10-24 17:06:59 +0000484 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
485 // we are done.
486 if (const RewriteBuffer *RewriteBuf =
487 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000488 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000489 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000490 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000491 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000492 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000493 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000494 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000495 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000496}
497
Chris Lattnerf04da132007-10-24 17:06:59 +0000498//===----------------------------------------------------------------------===//
499// Syntactic (non-AST) Rewriting Code
500//===----------------------------------------------------------------------===//
501
Steve Naroffb29b4272008-04-14 22:03:09 +0000502void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000503 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
504 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
505 const char *MainBufStart = MainBuf.first;
506 const char *MainBufEnd = MainBuf.second;
507 size_t ImportLen = strlen("import");
508 size_t IncludeLen = strlen("include");
509
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000510 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000511 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
512 if (*BufPtr == '#') {
513 if (++BufPtr == MainBufEnd)
514 return;
515 while (*BufPtr == ' ' || *BufPtr == '\t')
516 if (++BufPtr == MainBufEnd)
517 return;
518 if (!strncmp(BufPtr, "import", ImportLen)) {
519 // replace import with include
520 SourceLocation ImportLoc =
521 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000522 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000523 BufPtr += ImportLen;
524 }
525 }
526 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000527}
528
Steve Naroffb29b4272008-04-14 22:03:09 +0000529void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000530 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
531 const char *MainBufStart = MainBuf.first;
532 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000533
Chris Lattnerf04da132007-10-24 17:06:59 +0000534 // Loop over the whole file, looking for tabs.
535 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
536 if (*BufPtr != '\t')
537 continue;
538
539 // Okay, we found a tab. This tab will turn into at least one character,
540 // but it depends on which 'virtual column' it is in. Compute that now.
541 unsigned VCol = 0;
542 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
543 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
544 ++VCol;
545
546 // Okay, now that we know the virtual column, we know how many spaces to
547 // insert. We assume 8-character tab-stops.
548 unsigned Spaces = 8-(VCol & 7);
549
550 // Get the location of the tab.
551 SourceLocation TabLoc =
552 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
553
554 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000555 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000556 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000557}
558
559
Steve Naroffb29b4272008-04-14 22:03:09 +0000560void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000561 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000562 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000563
564 // Get the start location and compute the semi location.
565 SourceLocation startLoc = ClassDecl->getLocation();
566 const char *startBuf = SM->getCharacterData(startLoc);
567 const char *semiPtr = strchr(startBuf, ';');
568
569 // Translate to typedef's that forward reference structs with the same name
570 // as the class. As a convenience, we include the original declaration
571 // as a comment.
572 std::string typedefString;
573 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000574 typedefString.append(startBuf, semiPtr-startBuf+1);
575 typedefString += "\n";
576 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000577 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000578 typedefString += "#ifndef _REWRITER_typedef_";
579 typedefString += ForwardDecl->getName();
580 typedefString += "\n";
581 typedefString += "#define _REWRITER_typedef_";
582 typedefString += ForwardDecl->getName();
583 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000584 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000585 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000586 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000587 }
588
589 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000590 ReplaceText(startLoc, semiPtr-startBuf+1,
591 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000592}
593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000595 SourceLocation LocStart = Method->getLocStart();
596 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000597
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000598 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000599 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000600 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000601 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000602 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000603 }
604}
605
Steve Naroffb29b4272008-04-14 22:03:09 +0000606void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000607{
Chris Lattner55d13b42008-03-16 21:23:50 +0000608 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000609 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000610 SourceLocation Loc = Property->getLocation();
611
Chris Lattneraadaf782008-01-31 19:51:04 +0000612 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000613
614 // FIXME: handle properties that are declared across multiple lines.
615 }
616}
617
Steve Naroffb29b4272008-04-14 22:03:09 +0000618void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000619 SourceLocation LocStart = CatDecl->getLocStart();
620
621 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000622 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000623
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000624 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000625 E = CatDecl->instmeth_end(); I != E; ++I)
626 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000627 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000628 E = CatDecl->classmeth_end(); I != E; ++I)
629 RewriteMethodDeclaration(*I);
630
Steve Naroff423cb562007-10-30 13:30:57 +0000631 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000632 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000633}
634
Steve Naroffb29b4272008-04-14 22:03:09 +0000635void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000636 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000637
Steve Naroff752d6ef2007-10-30 16:42:30 +0000638 SourceLocation LocStart = PDecl->getLocStart();
639
640 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000641 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000642
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000644 E = PDecl->instmeth_end(); I != E; ++I)
645 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000646 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000647 E = PDecl->classmeth_end(); I != E; ++I)
648 RewriteMethodDeclaration(*I);
649
Steve Naroff752d6ef2007-10-30 16:42:30 +0000650 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000651 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000652 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000653
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000654 // Must comment out @optional/@required
655 const char *startBuf = SM->getCharacterData(LocStart);
656 const char *endBuf = SM->getCharacterData(LocEnd);
657 for (const char *p = startBuf; p < endBuf; p++) {
658 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
659 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000660 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000661 ReplaceText(OptionalLoc, strlen("@optional"),
662 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000663
664 }
665 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
666 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000667 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000668 ReplaceText(OptionalLoc, strlen("@required"),
669 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000670
671 }
672 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000673}
674
Steve Naroffb29b4272008-04-14 22:03:09 +0000675void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000676 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000677 if (LocStart.isInvalid())
678 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000679 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000680 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000681}
682
Steve Naroffb29b4272008-04-14 22:03:09 +0000683void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000684 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000685 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000686 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000688 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000689 else if (OMD->getResultType()->isFunctionPointerType()) {
690 // needs special handling, since pointer-to-functions have special
691 // syntax (where a decaration models use).
692 QualType retType = OMD->getResultType();
693 if (const PointerType* PT = retType->getAsPointerType()) {
694 QualType PointeeTy = PT->getPointeeType();
695 if ((FPRetType = PointeeTy->getAsFunctionType())) {
696 ResultStr += FPRetType->getResultType().getAsString();
697 ResultStr += "(*";
698 }
699 }
700 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000701 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000702 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000703
704 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000705 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000706
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000707 if (OMD->isInstance())
708 NameStr += "_I_";
709 else
710 NameStr += "_C_";
711
712 NameStr += OMD->getClassInterface()->getName();
713 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714
715 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 if (ObjCCategoryImplDecl *CID =
717 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000718 NameStr += CID->getName();
719 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000720 }
Steve Naroff563b8282008-04-04 22:23:44 +0000721 // Append selector names, replacing ':' with '_'
722 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000723 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000724 else {
725 std::string selString = OMD->getSelector().getName();
726 int len = selString.size();
727 for (int i = 0; i < len; i++)
728 if (selString[i] == ':')
729 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000730 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000732 // Remember this name for metadata emission
733 MethodInternalNames[OMD] = NameStr;
734 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000735
736 // Rewrite arguments
737 ResultStr += "(";
738
739 // invisible arguments
740 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000741 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000742 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000743 if (!LangOpts.Microsoft) {
744 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
745 ResultStr += "struct ";
746 }
747 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000748 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000749 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000750 }
751 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000752 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000753
754 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000755 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000756 ResultStr += " _cmd";
757
758 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000759 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000760 ParmVarDecl *PDecl = OMD->getParamDecl(i);
761 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000762 if (PDecl->getType()->isObjCQualifiedIdType()) {
763 ResultStr += "id ";
764 ResultStr += PDecl->getName();
765 } else {
766 std::string Name = PDecl->getName();
767 PDecl->getType().getAsStringInternal(Name);
768 ResultStr += Name;
769 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000771 if (OMD->isVariadic())
772 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000773 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000774
Steve Naroff76e429d2008-07-16 14:40:40 +0000775 if (FPRetType) {
776 ResultStr += ")"; // close the precedence "scope" for "*".
777
778 // Now, emit the argument types (if any).
779 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
780 ResultStr += "(";
781 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
782 if (i) ResultStr += ", ";
783 std::string ParamStr = FT->getArgType(i).getAsString();
784 ResultStr += ParamStr;
785 }
786 if (FT->isVariadic()) {
787 if (FT->getNumArgs()) ResultStr += ", ";
788 ResultStr += "...";
789 }
790 ResultStr += ")";
791 } else {
792 ResultStr += "()";
793 }
794 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000795}
Steve Naroffb29b4272008-04-14 22:03:09 +0000796void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
798 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000799
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000800 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000801 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000802 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000803 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000804
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000806 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
807 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000808 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000809 ObjCMethodDecl *OMD = *I;
810 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000811 SourceLocation LocStart = OMD->getLocStart();
812 SourceLocation LocEnd = OMD->getBody()->getLocStart();
813
814 const char *startBuf = SM->getCharacterData(LocStart);
815 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000816 ReplaceText(LocStart, endBuf-startBuf,
817 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000818 }
819
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000821 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
822 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000823 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000824 ObjCMethodDecl *OMD = *I;
825 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000826 SourceLocation LocStart = OMD->getLocStart();
827 SourceLocation LocEnd = OMD->getBody()->getLocStart();
828
829 const char *startBuf = SM->getCharacterData(LocStart);
830 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000831 ReplaceText(LocStart, endBuf-startBuf,
832 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000833 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000834 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000835 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000836 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000837 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000838}
839
Steve Naroffb29b4272008-04-14 22:03:09 +0000840void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000841 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000842 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000843 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000844 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000845 ResultStr += ClassDecl->getName();
846 ResultStr += "\n";
847 ResultStr += "#define _REWRITER_typedef_";
848 ResultStr += ClassDecl->getName();
849 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000850 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000851 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000852 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000853 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000854 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000855 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000857
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000858 RewriteProperties(ClassDecl->getNumPropertyDecl(),
859 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000860 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000861 E = ClassDecl->instmeth_end(); I != E; ++I)
862 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000863 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000864 E = ClassDecl->classmeth_end(); I != E; ++I)
865 RewriteMethodDeclaration(*I);
866
Steve Naroff2feac5e2007-10-30 03:43:13 +0000867 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000868 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000869}
870
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000871Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
872 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000873 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000874 if (CurMethodDecl) {
875 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000876 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
877 // lookup which class implements the instance variable.
878 ObjCInterfaceDecl *clsDeclared = 0;
879 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
880 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
881
882 // Synthesize an explicit cast to gain access to the ivar.
883 std::string RecName = clsDeclared->getIdentifier()->getName();
884 RecName += "_IMPL";
885 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000886 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000887 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000888 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
889 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000890 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
891 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000892 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000893 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
894 IV->getBase()->getLocEnd(),
895 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000896 if (IV->isFreeIvar() &&
897 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000898 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
899 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000900 ReplaceStmt(IV, ME);
901 delete IV;
902 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000903 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000904
905 ReplaceStmt(IV->getBase(), PE);
906 // Cannot delete IV->getBase(), since PE points to it.
907 // Replace the old base with the cast. This is important when doing
908 // embedded rewrites. For example, [newInv->_container addObject:0].
909 IV->setBase(PE);
910 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000911 }
Steve Naroff84472a82008-04-18 21:55:08 +0000912 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000913 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
914
915 // Explicit ivar refs need to have a cast inserted.
916 // FIXME: consider sharing some of this code with the code above.
917 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000918 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000919 // lookup which class implements the instance variable.
920 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000921 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000922 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
923
924 // Synthesize an explicit cast to gain access to the ivar.
925 std::string RecName = clsDeclared->getIdentifier()->getName();
926 RecName += "_IMPL";
927 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000928 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000929 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000930 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
931 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000932 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
933 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000934 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000935 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
936 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000937 ReplaceStmt(IV->getBase(), PE);
938 // Cannot delete IV->getBase(), since PE points to it.
939 // Replace the old base with the cast. This is important when doing
940 // embedded rewrites. For example, [newInv->_container addObject:0].
941 IV->setBase(PE);
942 return IV;
943 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000944 }
Steve Naroff84472a82008-04-18 21:55:08 +0000945 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000946}
947
Chris Lattnerf04da132007-10-24 17:06:59 +0000948//===----------------------------------------------------------------------===//
949// Function Body / Expression rewriting
950//===----------------------------------------------------------------------===//
951
Steve Naroffb29b4272008-04-14 22:03:09 +0000952Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000953 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
954 isa<DoStmt>(S) || isa<ForStmt>(S))
955 Stmts.push_back(S);
956 else if (isa<ObjCForCollectionStmt>(S)) {
957 Stmts.push_back(S);
958 ObjCBcLabelNo.push_back(++BcLabelCount);
959 }
960
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000961 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000962
963 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000964 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
965 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000966 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000967 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000968 if (newStmt)
969 *CI = newStmt;
970 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000971
972 // Handle specific things.
973 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
974 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000975
976 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000977 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000978
979 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
980 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000981
Steve Naroffbeaf2992007-11-03 11:27:19 +0000982 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
983 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000984
Steve Naroff934f2762007-10-24 22:48:43 +0000985 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
986 // Before we rewrite it, put the original message expression in a comment.
987 SourceLocation startLoc = MessExpr->getLocStart();
988 SourceLocation endLoc = MessExpr->getLocEnd();
989
990 const char *startBuf = SM->getCharacterData(startLoc);
991 const char *endBuf = SM->getCharacterData(endLoc);
992
993 std::string messString;
994 messString += "// ";
995 messString.append(startBuf, endBuf-startBuf+1);
996 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000997
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000998 // FIXME: Missing definition of
999 // InsertText(clang::SourceLocation, char const*, unsigned int).
1000 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001001 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001002 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001003 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001004 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001005
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001006 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1007 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001008
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001009 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1010 return RewriteObjCSynchronizedStmt(StmtTry);
1011
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1013 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001014
1015 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1016 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001017
1018 if (ObjCForCollectionStmt *StmtForCollection =
1019 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001020 return RewriteObjCForCollectionStmt(StmtForCollection,
1021 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001022 if (BreakStmt *StmtBreakStmt =
1023 dyn_cast<BreakStmt>(S))
1024 return RewriteBreakStmt(StmtBreakStmt);
1025 if (ContinueStmt *StmtContinueStmt =
1026 dyn_cast<ContinueStmt>(S))
1027 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001028
1029 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls and cast exprs.
1030 if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
1031 RewriteObjCQualifiedInterfaceTypes(DS->getDecl());
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001032 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001033 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001034
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001035 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1036 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1037 assert(!Stmts.empty() && "Statement stack is empty");
1038 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1039 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1040 && "Statement stack mismatch");
1041 Stmts.pop_back();
1042 }
Steve Naroff874e2322007-11-15 10:28:18 +00001043#if 0
1044 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1045 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1046 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001047 std::string SStr;
1048 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001049 Replacement->printPretty(Buf);
1050 const std::string &Str = Buf.str();
1051
1052 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001053 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001054 delete S;
1055 return Replacement;
1056 }
1057#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001058 // Return this stmt unmodified.
1059 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001060}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001061
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001062/// SynthCountByEnumWithState - To print:
1063/// ((unsigned int (*)
1064/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1065/// (void *)objc_msgSend)((id)l_collection,
1066/// sel_registerName(
1067/// "countByEnumeratingWithState:objects:count:"),
1068/// &enumState,
1069/// (id *)items, (unsigned int)16)
1070///
Steve Naroffb29b4272008-04-14 22:03:09 +00001071void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001072 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1073 "id *, unsigned int))(void *)objc_msgSend)";
1074 buf += "\n\t\t";
1075 buf += "((id)l_collection,\n\t\t";
1076 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1077 buf += "\n\t\t";
1078 buf += "&enumState, "
1079 "(id *)items, (unsigned int)16)";
1080}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001081
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001082/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1083/// statement to exit to its outer synthesized loop.
1084///
Steve Naroffb29b4272008-04-14 22:03:09 +00001085Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001086 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1087 return S;
1088 // replace break with goto __break_label
1089 std::string buf;
1090
1091 SourceLocation startLoc = S->getLocStart();
1092 buf = "goto __break_label_";
1093 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001094 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001095
1096 return 0;
1097}
1098
1099/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1100/// statement to continue with its inner synthesized loop.
1101///
Steve Naroffb29b4272008-04-14 22:03:09 +00001102Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001103 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1104 return S;
1105 // replace continue with goto __continue_label
1106 std::string buf;
1107
1108 SourceLocation startLoc = S->getLocStart();
1109 buf = "goto __continue_label_";
1110 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001111 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001112
1113 return 0;
1114}
1115
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001116/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001117/// It rewrites:
1118/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001119
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001120/// Into:
1121/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001122/// type elem;
1123/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001124/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001125/// id l_collection = (id)collection;
1126/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1127/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001128/// if (limit) {
1129/// unsigned long startMutations = *enumState.mutationsPtr;
1130/// do {
1131/// unsigned long counter = 0;
1132/// do {
1133/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001135/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001136/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001137/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001138/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1140/// objects:items count:16]);
1141/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001142/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001143/// }
1144/// else
1145/// elem = nil;
1146/// }
1147///
Steve Naroffb29b4272008-04-14 22:03:09 +00001148Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001149 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001150 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1151 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1152 "ObjCForCollectionStmt Statement stack mismatch");
1153 assert(!ObjCBcLabelNo.empty() &&
1154 "ObjCForCollectionStmt - Label No stack empty");
1155
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001156 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001157 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001159 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001160 std::string buf;
1161 buf = "\n{\n\t";
1162 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1163 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001164 ScopedDecl* D = DS->getSolitaryDecl();
1165 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001166 elementTypeAsString = ElementType.getAsString();
1167 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001168 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001169 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001170 buf += elementName;
1171 buf += ";\n\t";
1172 }
Chris Lattner06767512008-04-08 05:52:18 +00001173 else {
1174 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001176 elementTypeAsString = DR->getDecl()->getType().getAsString();
1177 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001178
1179 // struct __objcFastEnumerationState enumState = { 0 };
1180 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1181 // id items[16];
1182 buf += "id items[16];\n\t";
1183 // id l_collection = (id)
1184 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001185 // Find start location of 'collection' the hard way!
1186 const char *startCollectionBuf = startBuf;
1187 startCollectionBuf += 3; // skip 'for'
1188 startCollectionBuf = strchr(startCollectionBuf, '(');
1189 startCollectionBuf++; // skip '('
1190 // find 'in' and skip it.
1191 while (*startCollectionBuf != ' ' ||
1192 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1193 (*(startCollectionBuf+3) != ' ' &&
1194 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1195 startCollectionBuf++;
1196 startCollectionBuf += 3;
1197
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001198 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001199 ReplaceText(startLoc, startCollectionBuf - startBuf,
1200 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001201 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001202 SourceLocation rightParenLoc = S->getRParenLoc();
1203 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1204 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001205 buf = ";\n\t";
1206
1207 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1208 // objects:items count:16];
1209 // which is synthesized into:
1210 // unsigned int limit =
1211 // ((unsigned int (*)
1212 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1213 // (void *)objc_msgSend)((id)l_collection,
1214 // sel_registerName(
1215 // "countByEnumeratingWithState:objects:count:"),
1216 // (struct __objcFastEnumerationState *)&state,
1217 // (id *)items, (unsigned int)16);
1218 buf += "unsigned long limit =\n\t\t";
1219 SynthCountByEnumWithState(buf);
1220 buf += ";\n\t";
1221 /// if (limit) {
1222 /// unsigned long startMutations = *enumState.mutationsPtr;
1223 /// do {
1224 /// unsigned long counter = 0;
1225 /// do {
1226 /// if (startMutations != *enumState.mutationsPtr)
1227 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001228 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001229 buf += "if (limit) {\n\t";
1230 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1231 buf += "do {\n\t\t";
1232 buf += "unsigned long counter = 0;\n\t\t";
1233 buf += "do {\n\t\t\t";
1234 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1235 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1236 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001237 buf += " = (";
1238 buf += elementTypeAsString;
1239 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001240 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001241 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001242
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001243 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001244 /// } while (counter < limit);
1245 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1246 /// objects:items count:16]);
1247 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001249 /// }
1250 /// else
1251 /// elem = nil;
1252 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253 ///
1254 buf = ";\n\t";
1255 buf += "__continue_label_";
1256 buf += utostr(ObjCBcLabelNo.back());
1257 buf += ": ;";
1258 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001259 buf += "} while (counter < limit);\n\t";
1260 buf += "} while (limit = ";
1261 SynthCountByEnumWithState(buf);
1262 buf += ");\n\t";
1263 buf += elementName;
1264 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001265 buf += "__break_label_";
1266 buf += utostr(ObjCBcLabelNo.back());
1267 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268 buf += "}\n\t";
1269 buf += "else\n\t\t";
1270 buf += elementName;
1271 buf += " = nil;\n";
1272 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001273
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001274 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001275 if (isa<CompoundStmt>(S->getBody())) {
1276 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1277 InsertText(endBodyLoc, buf.c_str(), buf.size());
1278 } else {
1279 /* Need to treat single statements specially. For example:
1280 *
1281 * for (A *a in b) if (stuff()) break;
1282 * for (A *a in b) xxxyy;
1283 *
1284 * The following code simply scans ahead to the semi to find the actual end.
1285 */
1286 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1287 const char *semiBuf = strchr(stmtBuf, ';');
1288 assert(semiBuf && "Can't find ';'");
1289 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1290 InsertText(endBodyLoc, buf.c_str(), buf.size());
1291 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001292 Stmts.pop_back();
1293 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001295}
1296
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001297/// RewriteObjCSynchronizedStmt -
1298/// This routine rewrites @synchronized(expr) stmt;
1299/// into:
1300/// objc_sync_enter(expr);
1301/// @try stmt @finally { objc_sync_exit(expr); }
1302///
Steve Naroffb29b4272008-04-14 22:03:09 +00001303Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001304 // Get the start location and compute the semi location.
1305 SourceLocation startLoc = S->getLocStart();
1306 const char *startBuf = SM->getCharacterData(startLoc);
1307
1308 assert((*startBuf == '@') && "bogus @synchronized location");
1309
1310 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001311 buf = "objc_sync_enter((id)";
1312 const char *lparenBuf = startBuf;
1313 while (*lparenBuf != '(') lparenBuf++;
1314 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001315 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1316 // the sync expression is typically a message expression that's already
1317 // been rewritten! (which implies the SourceLocation's are invalid).
1318 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001319 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001320 while (*endBuf != ')') endBuf--;
1321 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001322 buf = ");\n";
1323 // declare a new scope with two variables, _stack and _rethrow.
1324 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1325 buf += "int buf[18/*32-bit i386*/];\n";
1326 buf += "char *pointers[4];} _stack;\n";
1327 buf += "id volatile _rethrow = 0;\n";
1328 buf += "objc_exception_try_enter(&_stack);\n";
1329 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001330 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001331 startLoc = S->getSynchBody()->getLocEnd();
1332 startBuf = SM->getCharacterData(startLoc);
1333
Steve Naroffc7089f12008-08-19 13:04:19 +00001334 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001335 SourceLocation lastCurlyLoc = startLoc;
1336 buf = "}\nelse {\n";
1337 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1338 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001339 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001340 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1341 S->getSynchExpr(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001342 std::string syncExprBufS;
1343 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001344 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001345 buf += syncExprBuf.str();
1346 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001347 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1348 buf += "}\n";
1349 buf += "}";
1350
Chris Lattneraadaf782008-01-31 19:51:04 +00001351 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001352 return 0;
1353}
1354
Steve Naroffb29b4272008-04-14 22:03:09 +00001355Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001356 // Get the start location and compute the semi location.
1357 SourceLocation startLoc = S->getLocStart();
1358 const char *startBuf = SM->getCharacterData(startLoc);
1359
1360 assert((*startBuf == '@') && "bogus @try location");
1361
1362 std::string buf;
1363 // declare a new scope with two variables, _stack and _rethrow.
1364 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1365 buf += "int buf[18/*32-bit i386*/];\n";
1366 buf += "char *pointers[4];} _stack;\n";
1367 buf += "id volatile _rethrow = 0;\n";
1368 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001369 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001370
Chris Lattneraadaf782008-01-31 19:51:04 +00001371 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001372
1373 startLoc = S->getTryBody()->getLocEnd();
1374 startBuf = SM->getCharacterData(startLoc);
1375
1376 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001377
Steve Naroff75730982007-11-07 04:08:17 +00001378 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001379 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1380 if (catchList) {
1381 startLoc = startLoc.getFileLocWithOffset(1);
1382 buf = " /* @catch begin */ else {\n";
1383 buf += " id _caught = objc_exception_extract(&_stack);\n";
1384 buf += " objc_exception_try_enter (&_stack);\n";
1385 buf += " if (_setjmp(_stack.buf))\n";
1386 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1387 buf += " else { /* @catch continue */";
1388
1389 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001390 } else { /* no catch list */
1391 buf = "}\nelse {\n";
1392 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1393 buf += "}";
1394 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001395 }
Steve Naroff75730982007-11-07 04:08:17 +00001396 bool sawIdTypedCatch = false;
1397 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001398 while (catchList) {
1399 Stmt *catchStmt = catchList->getCatchParamStmt();
1400
1401 if (catchList == S->getCatchStmts())
1402 buf = "if ("; // we are generating code for the first catch clause
1403 else
1404 buf = "else if (";
1405 startLoc = catchList->getLocStart();
1406 startBuf = SM->getCharacterData(startLoc);
1407
1408 assert((*startBuf == '@') && "bogus @catch location");
1409
1410 const char *lParenLoc = strchr(startBuf, '(');
1411
Steve Naroffbe4b3332008-02-01 22:08:12 +00001412 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001413 // Now rewrite the body...
1414 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001415 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1416 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001417 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1418 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001419 assert((*bodyBuf == '{') && "bogus @catch body location");
1420
1421 buf += "1) { id _tmp = _caught;";
1422 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1423 buf.c_str(), buf.size());
1424 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001425 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001426 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001427 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001428 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001429 sawIdTypedCatch = true;
1430 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001432
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001433 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001434 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001435 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001436 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001437 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001438 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001439 }
1440 }
1441 // Now rewrite the body...
1442 lastCatchBody = catchList->getCatchBody();
1443 SourceLocation rParenLoc = catchList->getRParenLoc();
1444 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1445 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1446 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1447 assert((*rParenBuf == ')') && "bogus @catch paren location");
1448 assert((*bodyBuf == '{') && "bogus @catch body location");
1449
1450 buf = " = _caught;";
1451 // Here we replace ") {" with "= _caught;" (which initializes and
1452 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001453 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001454 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001455 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001456 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001457 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001458 catchList = catchList->getNextCatchStmt();
1459 }
1460 // Complete the catch list...
1461 if (lastCatchBody) {
1462 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001463 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1464 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001465
Steve Naroff378f47a2008-09-11 15:29:03 +00001466 // Insert the last (implicit) else clause *before* the right curly brace.
1467 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1468 buf = "} /* last catch end */\n";
1469 buf += "else {\n";
1470 buf += " _rethrow = _caught;\n";
1471 buf += " objc_exception_try_exit(&_stack);\n";
1472 buf += "} } /* @catch end */\n";
1473 if (!S->getFinallyStmt())
1474 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001475 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001476
1477 // Set lastCurlyLoc
1478 lastCurlyLoc = lastCatchBody->getLocEnd();
1479 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001480 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001481 startLoc = finalStmt->getLocStart();
1482 startBuf = SM->getCharacterData(startLoc);
1483 assert((*startBuf == '@') && "bogus @finally start");
1484
1485 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001486 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001487
1488 Stmt *body = finalStmt->getFinallyBody();
1489 SourceLocation startLoc = body->getLocStart();
1490 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001491 assert(*SM->getCharacterData(startLoc) == '{' &&
1492 "bogus @finally body location");
1493 assert(*SM->getCharacterData(endLoc) == '}' &&
1494 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001495
1496 startLoc = startLoc.getFileLocWithOffset(1);
1497 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001498 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001499 endLoc = endLoc.getFileLocWithOffset(-1);
1500 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001501 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001502
1503 // Set lastCurlyLoc
1504 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001505 } else { /* no finally clause - make sure we synthesize an implicit one */
1506 buf = "{ /* implicit finally clause */\n";
1507 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1508 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1509 buf += "}";
1510 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001511 }
1512 // Now emit the final closing curly brace...
1513 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1514 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001515 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001516 return 0;
1517}
1518
Steve Naroffb29b4272008-04-14 22:03:09 +00001519Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001520 return 0;
1521}
1522
Steve Naroffb29b4272008-04-14 22:03:09 +00001523Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001524 return 0;
1525}
1526
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001527// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001528// the throw expression is typically a message expression that's already
1529// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001530Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001531 // Get the start location and compute the semi location.
1532 SourceLocation startLoc = S->getLocStart();
1533 const char *startBuf = SM->getCharacterData(startLoc);
1534
1535 assert((*startBuf == '@') && "bogus @throw location");
1536
1537 std::string buf;
1538 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001539 if (S->getThrowExpr())
1540 buf = "objc_exception_throw(";
1541 else // add an implicit argument
1542 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001543
1544 // handle "@ throw" correctly.
1545 const char *wBuf = strchr(startBuf, 'w');
1546 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1547 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1548
Steve Naroff2bd03922007-11-07 15:32:26 +00001549 const char *semiBuf = strchr(startBuf, ';');
1550 assert((*semiBuf == ';') && "@throw: can't find ';'");
1551 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1552 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001553 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001554 return 0;
1555}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001556
Steve Naroffb29b4272008-04-14 22:03:09 +00001557Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001558 // Create a new string expression.
1559 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001560 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001561 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1562 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001563 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1564 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001565 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001566 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001567
Chris Lattner07506182007-11-30 22:53:43 +00001568 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001569 delete Exp;
1570 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001571}
1572
Steve Naroffb29b4272008-04-14 22:03:09 +00001573Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001574 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1575 // Create a call to sel_registerName("selName").
1576 llvm::SmallVector<Expr*, 8> SelExprs;
1577 QualType argType = Context->getPointerType(Context->CharTy);
1578 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1579 Exp->getSelector().getName().size(),
1580 false, argType, SourceLocation(),
1581 SourceLocation()));
1582 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1583 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001584 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001585 delete Exp;
1586 return SelExp;
1587}
1588
Steve Naroffb29b4272008-04-14 22:03:09 +00001589CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001590 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001591 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001592 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001593
1594 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001595 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001596
1597 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001598 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001599 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1600
1601 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001602
Steve Naroff934f2762007-10-24 22:48:43 +00001603 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1604}
1605
Steve Naroffd5255f52007-11-01 13:24:47 +00001606static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1607 const char *&startRef, const char *&endRef) {
1608 while (startBuf < endBuf) {
1609 if (*startBuf == '<')
1610 startRef = startBuf; // mark the start.
1611 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001612 if (startRef && *startRef == '<') {
1613 endRef = startBuf; // mark the end.
1614 return true;
1615 }
1616 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001617 }
1618 startBuf++;
1619 }
1620 return false;
1621}
1622
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001623static void scanToNextArgument(const char *&argRef) {
1624 int angle = 0;
1625 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1626 if (*argRef == '<')
1627 angle++;
1628 else if (*argRef == '>')
1629 angle--;
1630 argRef++;
1631 }
1632 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1633}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001634
Steve Naroffb29b4272008-04-14 22:03:09 +00001635bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001636
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001637 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001638 return true;
1639
Steve Naroffd5255f52007-11-01 13:24:47 +00001640 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001641 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001643 return true; // we have "Class <Protocol> *".
1644 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001645 return false;
1646}
1647
Steve Naroff4f95b752008-07-29 18:15:38 +00001648void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1649 QualType Type = E->getType();
1650 if (needToScanForQualifiers(Type)) {
1651 SourceLocation Loc = E->getLocStart();
1652 const char *startBuf = SM->getCharacterData(Loc);
1653 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1654 const char *startRef = 0, *endRef = 0;
1655 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1656 // Get the locations of the startRef, endRef.
1657 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1658 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1659 // Comment out the protocol references.
1660 InsertText(LessLoc, "/*", 2);
1661 InsertText(GreaterLoc, "*/", 2);
1662 }
1663 }
1664}
1665
Steve Naroffb29b4272008-04-14 22:03:09 +00001666void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001667 SourceLocation Loc;
1668 QualType Type;
1669 const FunctionTypeProto *proto = 0;
1670 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1671 Loc = VD->getLocation();
1672 Type = VD->getType();
1673 }
1674 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1675 Loc = FD->getLocation();
1676 // Check for ObjC 'id' and class types that have been adorned with protocol
1677 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1678 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1679 assert(funcType && "missing function type");
1680 proto = dyn_cast<FunctionTypeProto>(funcType);
1681 if (!proto)
1682 return;
1683 Type = proto->getResultType();
1684 }
1685 else
1686 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001687
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001688 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001689 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001690
1691 const char *endBuf = SM->getCharacterData(Loc);
1692 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001693 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001694 startBuf--; // scan backward (from the decl location) for return type.
1695 const char *startRef = 0, *endRef = 0;
1696 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1697 // Get the locations of the startRef, endRef.
1698 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1699 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1700 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001701 InsertText(LessLoc, "/*", 2);
1702 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001703 }
1704 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001705 if (!proto)
1706 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001707 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001708 const char *startBuf = SM->getCharacterData(Loc);
1709 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001710 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1711 if (needToScanForQualifiers(proto->getArgType(i))) {
1712 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001713
Steve Naroffd5255f52007-11-01 13:24:47 +00001714 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001715 // scan forward (from the decl location) for argument types.
1716 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001717 const char *startRef = 0, *endRef = 0;
1718 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1719 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001720 SourceLocation LessLoc =
1721 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1722 SourceLocation GreaterLoc =
1723 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001724 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001725 InsertText(LessLoc, "/*", 2);
1726 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001727 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001728 startBuf = ++endBuf;
1729 }
1730 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001731 // If the function name is derived from a macro expansion, then the
1732 // argument buffer will not follow the name. Need to speak with Chris.
1733 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001734 startBuf++; // scan forward (from the decl location) for argument types.
1735 startBuf++;
1736 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001737 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001738}
1739
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001740// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001741void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001742 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1743 llvm::SmallVector<QualType, 16> ArgTys;
1744 ArgTys.push_back(Context->getPointerType(
1745 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001746 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001747 &ArgTys[0], ArgTys.size(),
1748 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001749 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001750 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001751 SelGetUidIdent, getFuncType,
1752 FunctionDecl::Extern, false, 0);
1753}
1754
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001755// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001756void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001757 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1758 llvm::SmallVector<QualType, 16> ArgTys;
1759 ArgTys.push_back(Context->getPointerType(
1760 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001761 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001762 &ArgTys[0], ArgTys.size(),
1763 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001764 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001765 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001766 SelGetProtoIdent, getFuncType,
1767 FunctionDecl::Extern, false, 0);
1768}
1769
Steve Naroffb29b4272008-04-14 22:03:09 +00001770void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001771 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001772 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001773 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001774 return;
1775 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001776 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001777}
1778
Steve Naroffc0a123c2008-03-11 17:37:02 +00001779// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001780void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001781 if (SuperContructorFunctionDecl)
1782 return;
1783 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1784 llvm::SmallVector<QualType, 16> ArgTys;
1785 QualType argT = Context->getObjCIdType();
1786 assert(!argT.isNull() && "Can't find 'id' type");
1787 ArgTys.push_back(argT);
1788 ArgTys.push_back(argT);
1789 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1790 &ArgTys[0], ArgTys.size(),
1791 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001792 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001793 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001794 msgSendIdent, msgSendType,
1795 FunctionDecl::Extern, false, 0);
1796}
1797
Steve Naroff09b266e2007-10-30 23:14:51 +00001798// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001799void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001800 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1801 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001802 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001803 assert(!argT.isNull() && "Can't find 'id' type");
1804 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001805 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001806 assert(!argT.isNull() && "Can't find 'SEL' type");
1807 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001808 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001809 &ArgTys[0], ArgTys.size(),
1810 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001811 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001812 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001813 msgSendIdent, msgSendType,
1814 FunctionDecl::Extern, false, 0);
1815}
1816
Steve Naroff874e2322007-11-15 10:28:18 +00001817// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001818void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001819 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1820 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001821 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001822 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001823 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001824 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1825 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1826 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001827 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001828 assert(!argT.isNull() && "Can't find 'SEL' type");
1829 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001830 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001831 &ArgTys[0], ArgTys.size(),
1832 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001833 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001834 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001835 msgSendIdent, msgSendType,
1836 FunctionDecl::Extern, false, 0);
1837}
1838
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001839// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001840void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001841 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1842 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001843 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001844 assert(!argT.isNull() && "Can't find 'id' type");
1845 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001846 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001847 assert(!argT.isNull() && "Can't find 'SEL' type");
1848 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001849 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001850 &ArgTys[0], ArgTys.size(),
1851 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001852 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001853 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001854 msgSendIdent, msgSendType,
1855 FunctionDecl::Extern, false, 0);
1856}
1857
1858// SynthMsgSendSuperStretFunctionDecl -
1859// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001860void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001861 IdentifierInfo *msgSendIdent =
1862 &Context->Idents.get("objc_msgSendSuper_stret");
1863 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001864 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001865 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001866 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001867 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1868 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1869 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001870 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001871 assert(!argT.isNull() && "Can't find 'SEL' type");
1872 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001873 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001874 &ArgTys[0], ArgTys.size(),
1875 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001876 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001877 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001878 msgSendIdent, msgSendType,
1879 FunctionDecl::Extern, false, 0);
1880}
1881
Steve Naroff1284db82008-05-08 22:02:18 +00001882// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001883void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001884 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1885 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001886 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001887 assert(!argT.isNull() && "Can't find 'id' type");
1888 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001889 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001890 assert(!argT.isNull() && "Can't find 'SEL' type");
1891 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001892 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001893 &ArgTys[0], ArgTys.size(),
1894 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001895 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001896 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001897 msgSendIdent, msgSendType,
1898 FunctionDecl::Extern, false, 0);
1899}
1900
Steve Naroff09b266e2007-10-30 23:14:51 +00001901// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001902void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001903 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1904 llvm::SmallVector<QualType, 16> ArgTys;
1905 ArgTys.push_back(Context->getPointerType(
1906 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001907 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001908 &ArgTys[0], ArgTys.size(),
1909 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001910 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001911 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001912 getClassIdent, getClassType,
1913 FunctionDecl::Extern, false, 0);
1914}
1915
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001916// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001917void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001918 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1919 llvm::SmallVector<QualType, 16> ArgTys;
1920 ArgTys.push_back(Context->getPointerType(
1921 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001922 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001923 &ArgTys[0], ArgTys.size(),
1924 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001925 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001926 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001927 getClassIdent, getClassType,
1928 FunctionDecl::Extern, false, 0);
1929}
1930
Steve Naroffb29b4272008-04-14 22:03:09 +00001931Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001932 QualType strType = getConstantStringStructType();
1933
1934 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001935
1936 std::string tmpName = InFileName;
1937 unsigned i;
1938 for (i=0; i < tmpName.length(); i++) {
1939 char c = tmpName.at(i);
1940 // replace any non alphanumeric characters with '_'.
1941 if (!isalpha(c) && (c < '0' || c > '9'))
1942 tmpName[i] = '_';
1943 }
1944 S += tmpName;
1945 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001946 S += utostr(NumObjCStringLiterals++);
1947
Steve Naroffba92b2e2008-03-27 22:29:16 +00001948 Preamble += "static __NSConstantStringImpl " + S;
1949 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1950 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001951 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001952 std::string prettyBufS;
1953 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001954 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001955 Preamble += prettyBuf.str();
1956 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001957 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001958 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001959
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001960 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001961 &Context->Idents.get(S.c_str()), strType,
1962 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001963 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1964 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1965 Context->getPointerType(DRE->getType()),
1966 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001967 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001968 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001969 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001970 delete Exp;
1971 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001972}
1973
Steve Naroffb29b4272008-04-14 22:03:09 +00001974ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001975 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001976 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1977
Chris Lattnerd9f69102008-08-10 01:53:14 +00001978 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1979 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001980 const PointerType *PT = PDE->getType()->getAsPointerType();
1981 assert(PT);
1982 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1983 return IT->getDecl();
1984 }
1985 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001986}
1987
1988// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001989QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001990 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001991 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001992 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001993 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001994 QualType FieldTypes[2];
1995
1996 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001998 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002000 // Create fields
2001 FieldDecl *FieldDecls[2];
2002
2003 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002004 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002005 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002006
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002007 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002008 }
2009 return Context->getTagDeclType(SuperStructDecl);
2010}
2011
Steve Naroffb29b4272008-04-14 22:03:09 +00002012QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002013 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002014 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002015 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002016 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002017 QualType FieldTypes[4];
2018
2019 // struct objc_object *receiver;
2020 FieldTypes[0] = Context->getObjCIdType();
2021 // int flags;
2022 FieldTypes[1] = Context->IntTy;
2023 // char *str;
2024 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2025 // long length;
2026 FieldTypes[3] = Context->LongTy;
2027 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002028 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002029
2030 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002031 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002032 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002033
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002034 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002035 }
2036 return Context->getTagDeclType(ConstantStringDecl);
2037}
2038
Steve Naroffb29b4272008-04-14 22:03:09 +00002039Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002040 if (!SelGetUidFunctionDecl)
2041 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002042 if (!MsgSendFunctionDecl)
2043 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002044 if (!MsgSendSuperFunctionDecl)
2045 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 if (!MsgSendStretFunctionDecl)
2047 SynthMsgSendStretFunctionDecl();
2048 if (!MsgSendSuperStretFunctionDecl)
2049 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002050 if (!MsgSendFpretFunctionDecl)
2051 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002052 if (!GetClassFunctionDecl)
2053 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002054 if (!GetMetaClassFunctionDecl)
2055 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002056
Steve Naroff874e2322007-11-15 10:28:18 +00002057 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002058 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2059 // May need to use objc_msgSend_stret() as well.
2060 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002063 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002065 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002066 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067 }
Steve Naroff874e2322007-11-15 10:28:18 +00002068
Steve Naroff934f2762007-10-24 22:48:43 +00002069 // Synthesize a call to objc_msgSend().
2070 llvm::SmallVector<Expr*, 8> MsgExprs;
2071 IdentifierInfo *clsName = Exp->getClassName();
2072
2073 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2074 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002075 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2076 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002077 if (!strcmp(clsName->getName(), "super")) {
2078 MsgSendFlavor = MsgSendSuperFunctionDecl;
2079 if (MsgSendStretFlavor)
2080 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2081 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2082
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002084 CurMethodDecl->getClassInterface()->getSuperClass();
2085
2086 llvm::SmallVector<Expr*, 4> InitExprs;
2087
2088 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002089 InitExprs.push_back(new DeclRefExpr(
2090 CurMethodDecl->getSelfDecl(),
2091 Context->getObjCIdType(),
2092 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002093 llvm::SmallVector<Expr*, 8> ClsExprs;
2094 QualType argType = Context->getPointerType(Context->CharTy);
2095 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2096 SuperDecl->getIdentifier()->getLength(),
2097 false, argType, SourceLocation(),
2098 SourceLocation()));
2099 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2100 &ClsExprs[0],
2101 ClsExprs.size());
2102 // To turn off a warning, type-cast to 'id'
2103 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002104 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002105 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2106 // struct objc_super
2107 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002108 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002109
Steve Naroff23f41272008-03-11 18:14:26 +00002110 if (LangOpts.Microsoft) {
2111 SynthSuperContructorFunctionDecl();
2112 // Simulate a contructor call...
2113 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2114 superType, SourceLocation());
2115 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2116 superType, SourceLocation());
2117 } else {
2118 // (struct objc_super) { <exprs from above> }
2119 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2120 &InitExprs[0], InitExprs.size(),
2121 SourceLocation());
2122 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2123 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002124 // struct objc_super *
2125 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2126 Context->getPointerType(SuperRep->getType()),
2127 SourceLocation());
2128 MsgExprs.push_back(Unop);
2129 } else {
2130 llvm::SmallVector<Expr*, 8> ClsExprs;
2131 QualType argType = Context->getPointerType(Context->CharTy);
2132 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2133 clsName->getLength(),
2134 false, argType, SourceLocation(),
2135 SourceLocation()));
2136 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2137 &ClsExprs[0],
2138 ClsExprs.size());
2139 MsgExprs.push_back(Cls);
2140 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002141 } else { // instance message.
2142 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002143
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002144 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002145 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002146 if (MsgSendStretFlavor)
2147 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002148 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2149
2150 llvm::SmallVector<Expr*, 4> InitExprs;
2151
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002152 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002153 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002154 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2155 Context->getObjCIdType(),
2156 SourceLocation()),
2157 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002158
2159 llvm::SmallVector<Expr*, 8> ClsExprs;
2160 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002161 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2162 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002163 false, argType, SourceLocation(),
2164 SourceLocation()));
2165 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002166 &ClsExprs[0],
2167 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002168 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002169 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002170 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002171 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002172 // struct objc_super
2173 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002174 Expr *SuperRep;
2175
2176 if (LangOpts.Microsoft) {
2177 SynthSuperContructorFunctionDecl();
2178 // Simulate a contructor call...
2179 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2180 superType, SourceLocation());
2181 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2182 superType, SourceLocation());
2183 } else {
2184 // (struct objc_super) { <exprs from above> }
2185 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2186 &InitExprs[0], InitExprs.size(),
2187 SourceLocation());
2188 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2189 }
Steve Naroff874e2322007-11-15 10:28:18 +00002190 // struct objc_super *
2191 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2192 Context->getPointerType(SuperRep->getType()),
2193 SourceLocation());
2194 MsgExprs.push_back(Unop);
2195 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002196 // Remove all type-casts because it may contain objc-style types; e.g.
2197 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002198 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002199 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002200 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2201 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002202 MsgExprs.push_back(recExpr);
2203 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002204 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002205 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002206 llvm::SmallVector<Expr*, 8> SelExprs;
2207 QualType argType = Context->getPointerType(Context->CharTy);
2208 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2209 Exp->getSelector().getName().size(),
2210 false, argType, SourceLocation(),
2211 SourceLocation()));
2212 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2213 &SelExprs[0], SelExprs.size());
2214 MsgExprs.push_back(SelExp);
2215
2216 // Now push any user supplied arguments.
2217 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002218 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002219 // Make all implicit casts explicit...ICE comes in handy:-)
2220 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2221 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002222 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002224 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002225 }
2226 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002227 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002228 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002229 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002230 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002231 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002232 userExpr, SourceLocation());
2233 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002234 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002235 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002236 // We've transferred the ownership to MsgExprs. Null out the argument in
2237 // the original expression, since we will delete it below.
2238 Exp->setArg(i, 0);
2239 }
Steve Naroffab972d32007-11-04 22:37:50 +00002240 // Generate the funky cast.
2241 CastExpr *cast;
2242 llvm::SmallVector<QualType, 8> ArgTypes;
2243 QualType returnType;
2244
2245 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002246 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2247 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2248 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 ArgTypes.push_back(Context->getObjCIdType());
2250 ArgTypes.push_back(Context->getObjCSelType());
2251 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002252 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002253 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2255 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002256 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002257 ArgTypes.push_back(t);
2258 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002259 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2260 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002261 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002262 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002263 }
2264 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002265 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002266
2267 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002268 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2269 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002270
2271 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2272 // If we don't do this cast, we get the following bizarre warning/note:
2273 // xx.m:13: warning: function called through a non-compatible type
2274 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002275 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002276 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002277
Steve Naroffab972d32007-11-04 22:37:50 +00002278 // Now do the "normal" pointer to function cast.
2279 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002280 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002281 // If we don't have a method decl, force a variadic cast.
2282 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002283 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002284 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002285
2286 // Don't forget the parens to enforce the proper binding.
2287 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2288
2289 const FunctionType *FT = msgSendType->getAsFunctionType();
2290 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2291 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002292 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002293 if (MsgSendStretFlavor) {
2294 // We have the method which returns a struct/union. Must also generate
2295 // call to objc_msgSend_stret and hang both varieties on a conditional
2296 // expression which dictate which one to envoke depending on size of
2297 // method's return type.
2298
2299 // Create a reference to the objc_msgSend_stret() declaration.
2300 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2301 SourceLocation());
2302 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002303 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002304 SourceLocation());
2305 // Now do the "normal" pointer to function cast.
2306 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002307 &ArgTypes[0], ArgTypes.size(),
2308 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002309 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002310 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002311
2312 // Don't forget the parens to enforce the proper binding.
2313 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2314
2315 FT = msgSendType->getAsFunctionType();
2316 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2317 FT->getResultType(), SourceLocation());
2318
2319 // Build sizeof(returnType)
2320 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2321 returnType, Context->getSizeType(),
2322 SourceLocation(), SourceLocation());
2323 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2324 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2325 // For X86 it is more complicated and some kind of target specific routine
2326 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002327 unsigned IntSize =
2328 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002329 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2330 Context->IntTy,
2331 SourceLocation());
2332 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2333 BinaryOperator::LE,
2334 Context->IntTy,
2335 SourceLocation());
2336 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2337 ConditionalOperator *CondExpr =
2338 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002339 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002340 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002341 return ReplacingStmt;
2342}
2343
Steve Naroffb29b4272008-04-14 22:03:09 +00002344Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002345 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002346 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002347 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002348
Chris Lattnere64b7772007-10-24 16:57:36 +00002349 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002350 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002351}
2352
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002353/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2354/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002355Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002356 if (!GetProtocolFunctionDecl)
2357 SynthGetProtocolFunctionDecl();
2358 // Create a call to objc_getProtocol("ProtocolName").
2359 llvm::SmallVector<Expr*, 8> ProtoExprs;
2360 QualType argType = Context->getPointerType(Context->CharTy);
2361 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2362 strlen(Exp->getProtocol()->getName()),
2363 false, argType, SourceLocation(),
2364 SourceLocation()));
2365 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2366 &ProtoExprs[0],
2367 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002368 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002369 delete Exp;
2370 return ProtoExp;
2371
2372}
2373
Steve Naroffbaf58c32008-05-31 14:15:04 +00002374bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2375 const char *endBuf) {
2376 while (startBuf < endBuf) {
2377 if (*startBuf == '#') {
2378 // Skip whitespace.
2379 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2380 ;
2381 if (!strncmp(startBuf, "if", strlen("if")) ||
2382 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2383 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2384 !strncmp(startBuf, "define", strlen("define")) ||
2385 !strncmp(startBuf, "undef", strlen("undef")) ||
2386 !strncmp(startBuf, "else", strlen("else")) ||
2387 !strncmp(startBuf, "elif", strlen("elif")) ||
2388 !strncmp(startBuf, "endif", strlen("endif")) ||
2389 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2390 !strncmp(startBuf, "include", strlen("include")) ||
2391 !strncmp(startBuf, "import", strlen("import")) ||
2392 !strncmp(startBuf, "include_next", strlen("include_next")))
2393 return true;
2394 }
2395 startBuf++;
2396 }
2397 return false;
2398}
2399
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002401/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002402void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002403 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2405 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002406 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002408 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002410 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002411 SourceLocation LocStart = CDecl->getLocStart();
2412 SourceLocation LocEnd = CDecl->getLocEnd();
2413
2414 const char *startBuf = SM->getCharacterData(LocStart);
2415 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002416
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002417 // If no ivars and no root or if its root, directly or indirectly,
2418 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002419 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2420 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002421 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002422 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002423 return;
2424 }
2425
2426 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002427 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002428 Result += "\nstruct ";
2429 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002430 if (LangOpts.Microsoft)
2431 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002432
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002433 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002434 const char *cursor = strchr(startBuf, '{');
2435 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002436 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002437 // If the buffer contains preprocessor directives, we do more fine-grained
2438 // rewrites. This is intended to fix code that looks like (which occurs in
2439 // NSURL.h, for example):
2440 //
2441 // #ifdef XYZ
2442 // @interface Foo : NSObject
2443 // #else
2444 // @interface FooBar : NSObject
2445 // #endif
2446 // {
2447 // int i;
2448 // }
2449 // @end
2450 //
2451 // This clause is segregated to avoid breaking the common case.
2452 if (BufferContainsPPDirectives(startBuf, cursor)) {
2453 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2454 CDecl->getClassLoc();
2455 const char *endHeader = SM->getCharacterData(L);
2456 endHeader += Lexer::MeasureTokenLength(L, *SM);
2457
Chris Lattner3db6cae2008-07-21 18:19:38 +00002458 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002459 // advance to the end of the referenced protocols.
2460 while (endHeader < cursor && *endHeader != '>') endHeader++;
2461 endHeader++;
2462 }
2463 // rewrite the original header
2464 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2465 } else {
2466 // rewrite the original header *without* disturbing the '{'
2467 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2468 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002470 Result = "\n struct ";
2471 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002472 Result += "_IMPL ";
2473 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002474 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002475
2476 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002477 SourceLocation OnePastCurly =
2478 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2479 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002480 }
2481 cursor++; // past '{'
2482
2483 // Now comment out any visibility specifiers.
2484 while (cursor < endBuf) {
2485 if (*cursor == '@') {
2486 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002487 // Skip whitespace.
2488 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2489 /*scan*/;
2490
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002491 // FIXME: presence of @public, etc. inside comment results in
2492 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002493 if (!strncmp(cursor, "public", strlen("public")) ||
2494 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002495 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002496 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002497 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002498 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002499 // FIXME: If there are cases where '<' is used in ivar declaration part
2500 // of user code, then scan the ivar list and use needToScanForQualifiers
2501 // for type checking.
2502 else if (*cursor == '<') {
2503 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002504 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002505 cursor = strchr(cursor, '>');
2506 cursor++;
2507 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002508 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002509 }
Steve Narofffea763e82007-11-14 19:25:57 +00002510 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002511 }
Steve Narofffea763e82007-11-14 19:25:57 +00002512 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002513 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002514 } else { // we don't have any instance variables - insert super struct.
2515 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2516 Result += " {\n struct ";
2517 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002518 Result += "_IMPL ";
2519 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002520 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002521 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002522 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002523 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002525 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002526}
2527
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002529/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002530void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002531 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002532 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002533 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002534 const char *ClassName,
2535 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002536 if (MethodBegin == MethodEnd) return;
2537
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002538 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002539 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002541 SEL _cmd;
2542 char *method_types;
2543 void *_imp;
2544 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002545 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002546 Result += "\nstruct _objc_method {\n";
2547 Result += "\tSEL _cmd;\n";
2548 Result += "\tchar *method_types;\n";
2549 Result += "\tvoid *_imp;\n";
2550 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002551
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002552 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002553 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002554
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002556
2557 /* struct {
2558 struct _objc_method_list *next_method;
2559 int method_count;
2560 struct _objc_method method_list[];
2561 }
2562 */
2563 Result += "\nstatic struct {\n";
2564 Result += "\tstruct _objc_method_list *next_method;\n";
2565 Result += "\tint method_count;\n";
2566 Result += "\tstruct _objc_method method_list[";
2567 Result += utostr(MethodEnd-MethodBegin);
2568 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002569 Result += prefix;
2570 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2571 Result += "_METHODS_";
2572 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002573 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002574 Result += IsInstanceMethod ? "inst" : "cls";
2575 Result += "_meth\")))= ";
2576 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002577
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002578 Result += "\t,{{(SEL)\"";
2579 Result += (*MethodBegin)->getSelector().getName().c_str();
2580 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002581 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002582 Result += "\", \"";
2583 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002584 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002585 Result += MethodInternalNames[*MethodBegin];
2586 Result += "}\n";
2587 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2588 Result += "\t ,{(SEL)\"";
2589 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002590 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002591 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002592 Result += "\", \"";
2593 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002594 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002595 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002596 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002597 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002598 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002599}
2600
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002601/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002602void RewriteObjC::
2603RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2604 const char *prefix,
2605 const char *ClassName,
2606 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002607 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002608 if (Protocols.empty()) return;
2609
2610 for (unsigned i = 0; i != Protocols.size(); i++) {
2611 ObjCProtocolDecl *PDecl = Protocols[i];
2612 // Output struct protocol_methods holder of method selector and type.
2613 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2614 /* struct protocol_methods {
2615 SEL _cmd;
2616 char *method_types;
2617 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002618 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002619 Result += "\nstruct protocol_methods {\n";
2620 Result += "\tSEL _cmd;\n";
2621 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002622 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002623
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002624 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002625 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002626 // Do not synthesize the protocol more than once.
2627 if (ObjCSynthesizedProtocols.count(PDecl))
2628 continue;
2629
2630 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2631 unsigned NumMethods = PDecl->getNumInstanceMethods();
2632 /* struct _objc_protocol_method_list {
2633 int protocol_method_count;
2634 struct protocol_methods protocols[];
2635 }
2636 */
2637 Result += "\nstatic struct {\n";
2638 Result += "\tint protocol_method_count;\n";
2639 Result += "\tstruct protocol_methods protocols[";
2640 Result += utostr(NumMethods);
2641 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2642 Result += PDecl->getName();
2643 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2644 "{\n\t" + utostr(NumMethods) + "\n";
2645
2646 // Output instance methods declared in this protocol.
2647 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2648 E = PDecl->instmeth_end(); I != E; ++I) {
2649 if (I == PDecl->instmeth_begin())
2650 Result += "\t ,{{(SEL)\"";
2651 else
2652 Result += "\t ,{(SEL)\"";
2653 Result += (*I)->getSelector().getName().c_str();
2654 std::string MethodTypeString;
2655 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2656 Result += "\", \"";
2657 Result += MethodTypeString;
2658 Result += "\"}\n";
2659 }
2660 Result += "\t }\n};\n";
2661 }
2662
2663 // Output class methods declared in this protocol.
2664 int NumMethods = PDecl->getNumClassMethods();
2665 if (NumMethods > 0) {
2666 /* struct _objc_protocol_method_list {
2667 int protocol_method_count;
2668 struct protocol_methods protocols[];
2669 }
2670 */
2671 Result += "\nstatic struct {\n";
2672 Result += "\tint protocol_method_count;\n";
2673 Result += "\tstruct protocol_methods protocols[";
2674 Result += utostr(NumMethods);
2675 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2676 Result += PDecl->getName();
2677 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2678 "{\n\t";
2679 Result += utostr(NumMethods);
2680 Result += "\n";
2681
2682 // Output instance methods declared in this protocol.
2683 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2684 E = PDecl->classmeth_end(); I != E; ++I) {
2685 if (I == PDecl->classmeth_begin())
2686 Result += "\t ,{{(SEL)\"";
2687 else
2688 Result += "\t ,{(SEL)\"";
2689 Result += (*I)->getSelector().getName().c_str();
2690 std::string MethodTypeString;
2691 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2692 Result += "\", \"";
2693 Result += MethodTypeString;
2694 Result += "\"}\n";
2695 }
2696 Result += "\t }\n};\n";
2697 }
2698
2699 // Output:
2700 /* struct _objc_protocol {
2701 // Objective-C 1.0 extensions
2702 struct _objc_protocol_extension *isa;
2703 char *protocol_name;
2704 struct _objc_protocol **protocol_list;
2705 struct _objc_protocol_method_list *instance_methods;
2706 struct _objc_protocol_method_list *class_methods;
2707 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002708 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002709 static bool objc_protocol = false;
2710 if (!objc_protocol) {
2711 Result += "\nstruct _objc_protocol {\n";
2712 Result += "\tstruct _objc_protocol_extension *isa;\n";
2713 Result += "\tchar *protocol_name;\n";
2714 Result += "\tstruct _objc_protocol **protocol_list;\n";
2715 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2716 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2717 Result += "};\n";
2718
2719 objc_protocol = true;
2720 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002721
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002722 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2723 Result += PDecl->getName();
2724 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2725 "{\n\t0, \"";
2726 Result += PDecl->getName();
2727 Result += "\", 0, ";
2728 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2729 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2730 Result += PDecl->getName();
2731 Result += ", ";
2732 }
2733 else
2734 Result += "0, ";
2735 if (PDecl->getNumClassMethods() > 0) {
2736 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2737 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002738 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002739 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002740 else
2741 Result += "0\n";
2742 Result += "};\n";
2743
2744 // Mark this protocol as having been generated.
2745 if (!ObjCSynthesizedProtocols.insert(PDecl))
2746 assert(false && "protocol already synthesized");
2747 }
2748 // Output the top lovel protocol meta-data for the class.
2749 /* struct _objc_protocol_list {
2750 struct _objc_protocol_list *next;
2751 int protocol_count;
2752 struct _objc_protocol *class_protocols[];
2753 }
2754 */
2755 Result += "\nstatic struct {\n";
2756 Result += "\tstruct _objc_protocol_list *next;\n";
2757 Result += "\tint protocol_count;\n";
2758 Result += "\tstruct _objc_protocol *class_protocols[";
2759 Result += utostr(Protocols.size());
2760 Result += "];\n} _OBJC_";
2761 Result += prefix;
2762 Result += "_PROTOCOLS_";
2763 Result += ClassName;
2764 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2765 "{\n\t0, ";
2766 Result += utostr(Protocols.size());
2767 Result += "\n";
2768
2769 Result += "\t,{&_OBJC_PROTOCOL_";
2770 Result += Protocols[0]->getName();
2771 Result += " \n";
2772
2773 for (unsigned i = 1; i != Protocols.size(); i++) {
2774 Result += "\t ,&_OBJC_PROTOCOL_";
2775 Result += Protocols[i]->getName();
2776 Result += "\n";
2777 }
2778 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002779}
2780
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002781/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002782/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002783void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002784 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002785 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002787 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002788 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2789 CDecl = CDecl->getNextClassCategory())
2790 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2791 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792
Chris Lattnereb44eee2007-12-23 01:40:15 +00002793 std::string FullCategoryName = ClassDecl->getName();
2794 FullCategoryName += '_';
2795 FullCategoryName += IDecl->getName();
2796
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002797 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002798 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002799 true, "CATEGORY_", FullCategoryName.c_str(),
2800 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002801
2802 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002803 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002804 false, "CATEGORY_", FullCategoryName.c_str(),
2805 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002806
2807 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002808 // Null CDecl is case of a category implementation with no category interface
2809 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002810 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002811 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002812
2813 /* struct _objc_category {
2814 char *category_name;
2815 char *class_name;
2816 struct _objc_method_list *instance_methods;
2817 struct _objc_method_list *class_methods;
2818 struct _objc_protocol_list *protocols;
2819 // Objective-C 1.0 extensions
2820 uint32_t size; // sizeof (struct _objc_category)
2821 struct _objc_property_list *instance_properties; // category's own
2822 // @property decl.
2823 };
2824 */
2825
2826 static bool objc_category = false;
2827 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 Result += "\nstruct _objc_category {\n";
2829 Result += "\tchar *category_name;\n";
2830 Result += "\tchar *class_name;\n";
2831 Result += "\tstruct _objc_method_list *instance_methods;\n";
2832 Result += "\tstruct _objc_method_list *class_methods;\n";
2833 Result += "\tstruct _objc_protocol_list *protocols;\n";
2834 Result += "\tunsigned int size;\n";
2835 Result += "\tstruct _objc_property_list *instance_properties;\n";
2836 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002837 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002838 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2840 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002841 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002842 Result += IDecl->getName();
2843 Result += "\"\n\t, \"";
2844 Result += ClassDecl->getName();
2845 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002846
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 if (IDecl->getNumInstanceMethods() > 0) {
2848 Result += "\t, (struct _objc_method_list *)"
2849 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2850 Result += FullCategoryName;
2851 Result += "\n";
2852 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002853 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002854 Result += "\t, 0\n";
2855 if (IDecl->getNumClassMethods() > 0) {
2856 Result += "\t, (struct _objc_method_list *)"
2857 "&_OBJC_CATEGORY_CLASS_METHODS_";
2858 Result += FullCategoryName;
2859 Result += "\n";
2860 }
2861 else
2862 Result += "\t, 0\n";
2863
Chris Lattner780f3292008-07-21 21:32:27 +00002864 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002865 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2866 Result += FullCategoryName;
2867 Result += "\n";
2868 }
2869 else
2870 Result += "\t, 0\n";
2871 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002872}
2873
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002874/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2875/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002876void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002877 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002878 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002879 if (ivar->isBitField()) {
2880 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2881 // place all bitfields at offset 0.
2882 Result += "0";
2883 } else {
2884 Result += "__OFFSETOFIVAR__(struct ";
2885 Result += IDecl->getName();
2886 if (LangOpts.Microsoft)
2887 Result += "_IMPL";
2888 Result += ", ";
2889 Result += ivar->getName();
2890 Result += ")";
2891 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002892}
2893
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002894//===----------------------------------------------------------------------===//
2895// Meta Data Emission
2896//===----------------------------------------------------------------------===//
2897
Steve Naroffb29b4272008-04-14 22:03:09 +00002898void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002901
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002902 // Explictly declared @interface's are already synthesized.
2903 if (CDecl->ImplicitInterfaceDecl()) {
2904 // FIXME: Implementation of a class with no @interface (legacy) doese not
2905 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002906 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002907 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002908
Chris Lattnerbe6df082007-12-12 07:56:42 +00002909 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002910 unsigned NumIvars = !IDecl->ivar_empty()
2911 ? IDecl->ivar_size()
2912 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002913 if (NumIvars > 0) {
2914 static bool objc_ivar = false;
2915 if (!objc_ivar) {
2916 /* struct _objc_ivar {
2917 char *ivar_name;
2918 char *ivar_type;
2919 int ivar_offset;
2920 };
2921 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002922 Result += "\nstruct _objc_ivar {\n";
2923 Result += "\tchar *ivar_name;\n";
2924 Result += "\tchar *ivar_type;\n";
2925 Result += "\tint ivar_offset;\n";
2926 Result += "};\n";
2927
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002928 objc_ivar = true;
2929 }
2930
Steve Naroff946a6932008-03-11 00:12:29 +00002931 /* struct {
2932 int ivar_count;
2933 struct _objc_ivar ivar_list[nIvars];
2934 };
2935 */
2936 Result += "\nstatic struct {\n";
2937 Result += "\tint ivar_count;\n";
2938 Result += "\tstruct _objc_ivar ivar_list[";
2939 Result += utostr(NumIvars);
2940 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002941 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002942 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 "{\n\t";
2944 Result += utostr(NumIvars);
2945 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002946
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002947 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002948 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002949 IVI = IDecl->ivar_begin();
2950 IVE = IDecl->ivar_end();
2951 } else {
2952 IVI = CDecl->ivar_begin();
2953 IVE = CDecl->ivar_end();
2954 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002955 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002956 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002957 Result += "\", \"";
2958 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002959 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2960 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002961 Result += StrEncoding;
2962 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002963 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002964 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002965 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002966 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002967 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002968 Result += "\", \"";
2969 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002970 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2971 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002972 Result += StrEncoding;
2973 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002974 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002975 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002976 }
2977
2978 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002979 }
2980
2981 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002982 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002983 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002984
2985 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002986 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002987 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002988
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002989 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002990 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002991 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002993
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002994 // Declaration of class/meta-class metadata
2995 /* struct _objc_class {
2996 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002997 const char *super_class_name;
2998 char *name;
2999 long version;
3000 long info;
3001 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003002 struct _objc_ivar_list *ivars;
3003 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003004 struct objc_cache *cache;
3005 struct objc_protocol_list *protocols;
3006 const char *ivar_layout;
3007 struct _objc_class_ext *ext;
3008 };
3009 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003010 static bool objc_class = false;
3011 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003012 Result += "\nstruct _objc_class {\n";
3013 Result += "\tstruct _objc_class *isa;\n";
3014 Result += "\tconst char *super_class_name;\n";
3015 Result += "\tchar *name;\n";
3016 Result += "\tlong version;\n";
3017 Result += "\tlong info;\n";
3018 Result += "\tlong instance_size;\n";
3019 Result += "\tstruct _objc_ivar_list *ivars;\n";
3020 Result += "\tstruct _objc_method_list *methods;\n";
3021 Result += "\tstruct objc_cache *cache;\n";
3022 Result += "\tstruct _objc_protocol_list *protocols;\n";
3023 Result += "\tconst char *ivar_layout;\n";
3024 Result += "\tstruct _objc_class_ext *ext;\n";
3025 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003026 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003027 }
3028
3029 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003030 ObjCInterfaceDecl *RootClass = 0;
3031 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003032 while (SuperClass) {
3033 RootClass = SuperClass;
3034 SuperClass = SuperClass->getSuperClass();
3035 }
3036 SuperClass = CDecl->getSuperClass();
3037
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003038 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3039 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003040 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003041 "{\n\t(struct _objc_class *)\"";
3042 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3043 Result += "\"";
3044
3045 if (SuperClass) {
3046 Result += ", \"";
3047 Result += SuperClass->getName();
3048 Result += "\", \"";
3049 Result += CDecl->getName();
3050 Result += "\"";
3051 }
3052 else {
3053 Result += ", 0, \"";
3054 Result += CDecl->getName();
3055 Result += "\"";
3056 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003057 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003058 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003059 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003060 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003061 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003062 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063 Result += "\n";
3064 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003065 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003067 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003068 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 Result += CDecl->getName();
3070 Result += ",0,0\n";
3071 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003072 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 Result += "\t,0,0,0,0\n";
3074 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003075
3076 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003077 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3078 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003079 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 "{\n\t&_OBJC_METACLASS_";
3081 Result += CDecl->getName();
3082 if (SuperClass) {
3083 Result += ", \"";
3084 Result += SuperClass->getName();
3085 Result += "\", \"";
3086 Result += CDecl->getName();
3087 Result += "\"";
3088 }
3089 else {
3090 Result += ", 0, \"";
3091 Result += CDecl->getName();
3092 Result += "\"";
3093 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003094 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003095 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003096 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003097 Result += ",0";
3098 else {
3099 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003100 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003101 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003102 if (LangOpts.Microsoft)
3103 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003104 Result += ")";
3105 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003106 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003107 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003108 Result += CDecl->getName();
3109 Result += "\n\t";
3110 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003111 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003112 Result += ",0";
3113 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003114 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003115 Result += CDecl->getName();
3116 Result += ", 0\n\t";
3117 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003118 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003119 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003120 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003121 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += CDecl->getName();
3123 Result += ", 0,0\n";
3124 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003125 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003126 Result += ",0,0,0\n";
3127 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003128}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003129
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003130/// RewriteImplementations - This routine rewrites all method implementations
3131/// and emits meta-data.
3132
Steve Naroffb29b4272008-04-14 22:03:09 +00003133void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003134 int ClsDefCount = ClassImplementation.size();
3135 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003136
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003137 if (ClsDefCount == 0 && CatDefCount == 0)
3138 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003139 // Rewrite implemented methods
3140 for (int i = 0; i < ClsDefCount; i++)
3141 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003142
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003143 for (int i = 0; i < CatDefCount; i++)
3144 RewriteImplementationDecl(CategoryImplementation[i]);
3145
Steve Naroff5df5b762008-05-07 21:23:49 +00003146 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003147 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003148 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003149 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003150 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003151
3152 // For each implemented category, write out all its meta data.
3153 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003154 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003155
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003156 // Write objc_symtab metadata
3157 /*
3158 struct _objc_symtab
3159 {
3160 long sel_ref_cnt;
3161 SEL *refs;
3162 short cls_def_cnt;
3163 short cat_def_cnt;
3164 void *defs[cls_def_cnt + cat_def_cnt];
3165 };
3166 */
3167
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003168 Result += "\nstruct _objc_symtab {\n";
3169 Result += "\tlong sel_ref_cnt;\n";
3170 Result += "\tSEL *refs;\n";
3171 Result += "\tshort cls_def_cnt;\n";
3172 Result += "\tshort cat_def_cnt;\n";
3173 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3174 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003175
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003177 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003178 Result += "\t0, 0, " + utostr(ClsDefCount)
3179 + ", " + utostr(CatDefCount) + "\n";
3180 for (int i = 0; i < ClsDefCount; i++) {
3181 Result += "\t,&_OBJC_CLASS_";
3182 Result += ClassImplementation[i]->getName();
3183 Result += "\n";
3184 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003185
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003186 for (int i = 0; i < CatDefCount; i++) {
3187 Result += "\t,&_OBJC_CATEGORY_";
3188 Result += CategoryImplementation[i]->getClassInterface()->getName();
3189 Result += "_";
3190 Result += CategoryImplementation[i]->getName();
3191 Result += "\n";
3192 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003193
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003194 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003195
3196 // Write objc_module metadata
3197
3198 /*
3199 struct _objc_module {
3200 long version;
3201 long size;
3202 const char *name;
3203 struct _objc_symtab *symtab;
3204 }
3205 */
3206
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 Result += "\nstruct _objc_module {\n";
3208 Result += "\tlong version;\n";
3209 Result += "\tlong size;\n";
3210 Result += "\tconst char *name;\n";
3211 Result += "\tstruct _objc_symtab *symtab;\n";
3212 Result += "};\n\n";
3213 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003214 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003215 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3216 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003217 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003218
3219 if (LangOpts.Microsoft) {
3220 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003221 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003222 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3223 Result += "&_OBJC_MODULES;\n";
3224 Result += "#pragma data_seg(pop)\n\n";
3225 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003226}
Chris Lattner311ff022007-10-16 22:36:42 +00003227
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003228
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003229
3230