blob: 2f91ea9741bc0cfd4fe6e1f5c29c6df418c06841 [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"
Chris Lattner26de4652007-12-02 01:13:47 +000025#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000026#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000028#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000029#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include <fstream>
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
456 std::ostream *OutFile;
457 if (OutFileName == "-") {
458 OutFile = llvm::cout.stream();
459 } else if (!OutFileName.empty()) {
460 OutFile = new std::ofstream(OutFileName.c_str(),
461 std::ios_base::binary|std::ios_base::out);
462 } else if (InFileName == "-") {
463 OutFile = llvm::cout.stream();
464 } else {
465 llvm::sys::Path Path(InFileName);
466 Path.eraseSuffix();
467 Path.appendSuffix("cpp");
468 OutFile = new std::ofstream(Path.toString().c_str(),
469 std::ios_base::binary|std::ios_base::out);
470 }
471
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000472 RewriteInclude();
473
Steve Naroffba92b2e2008-03-27 22:29:16 +0000474 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
475 Preamble.c_str(), Preamble.size(), false);
476
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000477 // Rewrite Objective-c meta data*
478 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000479 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000480
Chris Lattnerf04da132007-10-24 17:06:59 +0000481 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
482 // we are done.
483 if (const RewriteBuffer *RewriteBuf =
484 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000485 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000486 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000487 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000488 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000489 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000490 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000492}
493
Chris Lattnerf04da132007-10-24 17:06:59 +0000494//===----------------------------------------------------------------------===//
495// Syntactic (non-AST) Rewriting Code
496//===----------------------------------------------------------------------===//
497
Steve Naroffb29b4272008-04-14 22:03:09 +0000498void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000499 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
500 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
501 const char *MainBufStart = MainBuf.first;
502 const char *MainBufEnd = MainBuf.second;
503 size_t ImportLen = strlen("import");
504 size_t IncludeLen = strlen("include");
505
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000506 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000507 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
508 if (*BufPtr == '#') {
509 if (++BufPtr == MainBufEnd)
510 return;
511 while (*BufPtr == ' ' || *BufPtr == '\t')
512 if (++BufPtr == MainBufEnd)
513 return;
514 if (!strncmp(BufPtr, "import", ImportLen)) {
515 // replace import with include
516 SourceLocation ImportLoc =
517 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000518 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000519 BufPtr += ImportLen;
520 }
521 }
522 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000523}
524
Steve Naroffb29b4272008-04-14 22:03:09 +0000525void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000526 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
527 const char *MainBufStart = MainBuf.first;
528 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000529
Chris Lattnerf04da132007-10-24 17:06:59 +0000530 // Loop over the whole file, looking for tabs.
531 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
532 if (*BufPtr != '\t')
533 continue;
534
535 // Okay, we found a tab. This tab will turn into at least one character,
536 // but it depends on which 'virtual column' it is in. Compute that now.
537 unsigned VCol = 0;
538 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
539 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
540 ++VCol;
541
542 // Okay, now that we know the virtual column, we know how many spaces to
543 // insert. We assume 8-character tab-stops.
544 unsigned Spaces = 8-(VCol & 7);
545
546 // Get the location of the tab.
547 SourceLocation TabLoc =
548 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
549
550 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000551 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000552 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000553}
554
555
Steve Naroffb29b4272008-04-14 22:03:09 +0000556void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000557 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000558 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000559
560 // Get the start location and compute the semi location.
561 SourceLocation startLoc = ClassDecl->getLocation();
562 const char *startBuf = SM->getCharacterData(startLoc);
563 const char *semiPtr = strchr(startBuf, ';');
564
565 // Translate to typedef's that forward reference structs with the same name
566 // as the class. As a convenience, we include the original declaration
567 // as a comment.
568 std::string typedefString;
569 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000570 typedefString.append(startBuf, semiPtr-startBuf+1);
571 typedefString += "\n";
572 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000573 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000574 typedefString += "#ifndef _REWRITER_typedef_";
575 typedefString += ForwardDecl->getName();
576 typedefString += "\n";
577 typedefString += "#define _REWRITER_typedef_";
578 typedefString += ForwardDecl->getName();
579 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000580 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000581 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000582 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000583 }
584
585 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000586 ReplaceText(startLoc, semiPtr-startBuf+1,
587 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000588}
589
Steve Naroffb29b4272008-04-14 22:03:09 +0000590void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000591 SourceLocation LocStart = Method->getLocStart();
592 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000593
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000594 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000595 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000596 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000597 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000598 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000599 }
600}
601
Steve Naroffb29b4272008-04-14 22:03:09 +0000602void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000603{
Chris Lattner55d13b42008-03-16 21:23:50 +0000604 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000605 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000606 SourceLocation Loc = Property->getLocation();
607
Chris Lattneraadaf782008-01-31 19:51:04 +0000608 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000609
610 // FIXME: handle properties that are declared across multiple lines.
611 }
612}
613
Steve Naroffb29b4272008-04-14 22:03:09 +0000614void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000615 SourceLocation LocStart = CatDecl->getLocStart();
616
617 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000619
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000620 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000621 E = CatDecl->instmeth_end(); I != E; ++I)
622 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 E = CatDecl->classmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
626
Steve Naroff423cb562007-10-30 13:30:57 +0000627 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000628 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000629}
630
Steve Naroffb29b4272008-04-14 22:03:09 +0000631void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000632 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000633
Steve Naroff752d6ef2007-10-30 16:42:30 +0000634 SourceLocation LocStart = PDecl->getLocStart();
635
636 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000637 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000638
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000639 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000640 E = PDecl->instmeth_end(); I != E; ++I)
641 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000642 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000643 E = PDecl->classmeth_end(); I != E; ++I)
644 RewriteMethodDeclaration(*I);
645
Steve Naroff752d6ef2007-10-30 16:42:30 +0000646 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000647 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000648 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000649
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000650 // Must comment out @optional/@required
651 const char *startBuf = SM->getCharacterData(LocStart);
652 const char *endBuf = SM->getCharacterData(LocEnd);
653 for (const char *p = startBuf; p < endBuf; p++) {
654 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
655 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000656 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000657 ReplaceText(OptionalLoc, strlen("@optional"),
658 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000659
660 }
661 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
662 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000663 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000664 ReplaceText(OptionalLoc, strlen("@required"),
665 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000666
667 }
668 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000669}
670
Steve Naroffb29b4272008-04-14 22:03:09 +0000671void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000672 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000673 if (LocStart.isInvalid())
674 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000675 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000676 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000677}
678
Steve Naroffb29b4272008-04-14 22:03:09 +0000679void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000680 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000681 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000682 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000683 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000684 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000685 else if (OMD->getResultType()->isFunctionPointerType()) {
686 // needs special handling, since pointer-to-functions have special
687 // syntax (where a decaration models use).
688 QualType retType = OMD->getResultType();
689 if (const PointerType* PT = retType->getAsPointerType()) {
690 QualType PointeeTy = PT->getPointeeType();
691 if ((FPRetType = PointeeTy->getAsFunctionType())) {
692 ResultStr += FPRetType->getResultType().getAsString();
693 ResultStr += "(*";
694 }
695 }
696 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000697 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000698 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000699
700 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000701 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000703 if (OMD->isInstance())
704 NameStr += "_I_";
705 else
706 NameStr += "_C_";
707
708 NameStr += OMD->getClassInterface()->getName();
709 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000710
711 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000712 if (ObjCCategoryImplDecl *CID =
713 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000714 NameStr += CID->getName();
715 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000716 }
Steve Naroff563b8282008-04-04 22:23:44 +0000717 // Append selector names, replacing ':' with '_'
718 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000719 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000720 else {
721 std::string selString = OMD->getSelector().getName();
722 int len = selString.size();
723 for (int i = 0; i < len; i++)
724 if (selString[i] == ':')
725 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000726 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000727 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000728 // Remember this name for metadata emission
729 MethodInternalNames[OMD] = NameStr;
730 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731
732 // Rewrite arguments
733 ResultStr += "(";
734
735 // invisible arguments
736 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000737 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000739 if (!LangOpts.Microsoft) {
740 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
741 ResultStr += "struct ";
742 }
743 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000744 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000745 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000746 }
747 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749
750 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752 ResultStr += " _cmd";
753
754 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000755 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000756 ParmVarDecl *PDecl = OMD->getParamDecl(i);
757 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000758 if (PDecl->getType()->isObjCQualifiedIdType()) {
759 ResultStr += "id ";
760 ResultStr += PDecl->getName();
761 } else {
762 std::string Name = PDecl->getName();
763 PDecl->getType().getAsStringInternal(Name);
764 ResultStr += Name;
765 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000766 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000767 if (OMD->isVariadic())
768 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000769 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770
Steve Naroff76e429d2008-07-16 14:40:40 +0000771 if (FPRetType) {
772 ResultStr += ")"; // close the precedence "scope" for "*".
773
774 // Now, emit the argument types (if any).
775 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
776 ResultStr += "(";
777 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
778 if (i) ResultStr += ", ";
779 std::string ParamStr = FT->getArgType(i).getAsString();
780 ResultStr += ParamStr;
781 }
782 if (FT->isVariadic()) {
783 if (FT->getNumArgs()) ResultStr += ", ";
784 ResultStr += "...";
785 }
786 ResultStr += ")";
787 } else {
788 ResultStr += "()";
789 }
790 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000791}
Steve Naroffb29b4272008-04-14 22:03:09 +0000792void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
794 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000795
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000796 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000797 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000798 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000799 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000800
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000802 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
803 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000804 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 ObjCMethodDecl *OMD = *I;
806 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000807 SourceLocation LocStart = OMD->getLocStart();
808 SourceLocation LocEnd = OMD->getBody()->getLocStart();
809
810 const char *startBuf = SM->getCharacterData(LocStart);
811 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000812 ReplaceText(LocStart, endBuf-startBuf,
813 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000814 }
815
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000817 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
818 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000819 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 ObjCMethodDecl *OMD = *I;
821 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000822 SourceLocation LocStart = OMD->getLocStart();
823 SourceLocation LocEnd = OMD->getBody()->getLocStart();
824
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000827 ReplaceText(LocStart, endBuf-startBuf,
828 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000829 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000830 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000831 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000832 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000833 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000834}
835
Steve Naroffb29b4272008-04-14 22:03:09 +0000836void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000837 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000838 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000839 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000840 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000841 ResultStr += ClassDecl->getName();
842 ResultStr += "\n";
843 ResultStr += "#define _REWRITER_typedef_";
844 ResultStr += ClassDecl->getName();
845 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000846 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000847 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000848 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000849 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000850 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000851 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000852 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000853
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000854 RewriteProperties(ClassDecl->getNumPropertyDecl(),
855 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000857 E = ClassDecl->instmeth_end(); I != E; ++I)
858 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000860 E = ClassDecl->classmeth_end(); I != E; ++I)
861 RewriteMethodDeclaration(*I);
862
Steve Naroff2feac5e2007-10-30 03:43:13 +0000863 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000864 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000865}
866
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000867Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
868 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000869 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000870 if (CurMethodDecl) {
871 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000872 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
873 // lookup which class implements the instance variable.
874 ObjCInterfaceDecl *clsDeclared = 0;
875 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
876 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
877
878 // Synthesize an explicit cast to gain access to the ivar.
879 std::string RecName = clsDeclared->getIdentifier()->getName();
880 RecName += "_IMPL";
881 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000882 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Narofff0757612008-05-08 17:52:16 +0000883 SourceLocation(), II, 0);
884 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
885 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000886 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
887 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000888 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000889 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
890 IV->getBase()->getLocEnd(),
891 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000892 if (IV->isFreeIvar() &&
893 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000894 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
895 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000896 ReplaceStmt(IV, ME);
897 delete IV;
898 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000899 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000900
901 ReplaceStmt(IV->getBase(), PE);
902 // Cannot delete IV->getBase(), since PE points to it.
903 // Replace the old base with the cast. This is important when doing
904 // embedded rewrites. For example, [newInv->_container addObject:0].
905 IV->setBase(PE);
906 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000907 }
Steve Naroff84472a82008-04-18 21:55:08 +0000908 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000909 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
910
911 // Explicit ivar refs need to have a cast inserted.
912 // FIXME: consider sharing some of this code with the code above.
913 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000914 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000915 // lookup which class implements the instance variable.
916 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000917 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000918 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
919
920 // Synthesize an explicit cast to gain access to the ivar.
921 std::string RecName = clsDeclared->getIdentifier()->getName();
922 RecName += "_IMPL";
923 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000924 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Steve Naroff9f525972008-05-06 23:20:07 +0000925 SourceLocation(), II, 0);
926 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
927 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000928 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
929 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000930 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000931 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
932 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000933 ReplaceStmt(IV->getBase(), PE);
934 // Cannot delete IV->getBase(), since PE points to it.
935 // Replace the old base with the cast. This is important when doing
936 // embedded rewrites. For example, [newInv->_container addObject:0].
937 IV->setBase(PE);
938 return IV;
939 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000940 }
Steve Naroff84472a82008-04-18 21:55:08 +0000941 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000942}
943
Chris Lattnerf04da132007-10-24 17:06:59 +0000944//===----------------------------------------------------------------------===//
945// Function Body / Expression rewriting
946//===----------------------------------------------------------------------===//
947
Steve Naroffb29b4272008-04-14 22:03:09 +0000948Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000949 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
950 isa<DoStmt>(S) || isa<ForStmt>(S))
951 Stmts.push_back(S);
952 else if (isa<ObjCForCollectionStmt>(S)) {
953 Stmts.push_back(S);
954 ObjCBcLabelNo.push_back(++BcLabelCount);
955 }
956
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000957 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000958
959 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000960 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
961 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000962 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000963 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000964 if (newStmt)
965 *CI = newStmt;
966 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000967
968 // Handle specific things.
969 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
970 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000971
972 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000973 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000974
975 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
976 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000977
Steve Naroffbeaf2992007-11-03 11:27:19 +0000978 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
979 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000980
Steve Naroff934f2762007-10-24 22:48:43 +0000981 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
982 // Before we rewrite it, put the original message expression in a comment.
983 SourceLocation startLoc = MessExpr->getLocStart();
984 SourceLocation endLoc = MessExpr->getLocEnd();
985
986 const char *startBuf = SM->getCharacterData(startLoc);
987 const char *endBuf = SM->getCharacterData(endLoc);
988
989 std::string messString;
990 messString += "// ";
991 messString.append(startBuf, endBuf-startBuf+1);
992 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000993
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000994 // FIXME: Missing definition of
995 // InsertText(clang::SourceLocation, char const*, unsigned int).
996 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000997 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000998 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000999 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001000 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001001
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001002 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1003 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001004
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001005 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1006 return RewriteObjCSynchronizedStmt(StmtTry);
1007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001008 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1009 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001010
1011 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1012 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001013
1014 if (ObjCForCollectionStmt *StmtForCollection =
1015 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001016 return RewriteObjCForCollectionStmt(StmtForCollection,
1017 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001018 if (BreakStmt *StmtBreakStmt =
1019 dyn_cast<BreakStmt>(S))
1020 return RewriteBreakStmt(StmtBreakStmt);
1021 if (ContinueStmt *StmtContinueStmt =
1022 dyn_cast<ContinueStmt>(S))
1023 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001024
1025 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls and cast exprs.
1026 if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
1027 RewriteObjCQualifiedInterfaceTypes(DS->getDecl());
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001028 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001029 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001030
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001031 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1032 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1033 assert(!Stmts.empty() && "Statement stack is empty");
1034 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1035 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1036 && "Statement stack mismatch");
1037 Stmts.pop_back();
1038 }
Steve Naroff874e2322007-11-15 10:28:18 +00001039#if 0
1040 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1041 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1042 // Get the new text.
1043 std::ostringstream Buf;
1044 Replacement->printPretty(Buf);
1045 const std::string &Str = Buf.str();
1046
1047 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001048 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001049 delete S;
1050 return Replacement;
1051 }
1052#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001053 // Return this stmt unmodified.
1054 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001055}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001056
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057/// SynthCountByEnumWithState - To print:
1058/// ((unsigned int (*)
1059/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1060/// (void *)objc_msgSend)((id)l_collection,
1061/// sel_registerName(
1062/// "countByEnumeratingWithState:objects:count:"),
1063/// &enumState,
1064/// (id *)items, (unsigned int)16)
1065///
Steve Naroffb29b4272008-04-14 22:03:09 +00001066void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1068 "id *, unsigned int))(void *)objc_msgSend)";
1069 buf += "\n\t\t";
1070 buf += "((id)l_collection,\n\t\t";
1071 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1072 buf += "\n\t\t";
1073 buf += "&enumState, "
1074 "(id *)items, (unsigned int)16)";
1075}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001076
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001077/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1078/// statement to exit to its outer synthesized loop.
1079///
Steve Naroffb29b4272008-04-14 22:03:09 +00001080Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001081 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1082 return S;
1083 // replace break with goto __break_label
1084 std::string buf;
1085
1086 SourceLocation startLoc = S->getLocStart();
1087 buf = "goto __break_label_";
1088 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001089 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001090
1091 return 0;
1092}
1093
1094/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1095/// statement to continue with its inner synthesized loop.
1096///
Steve Naroffb29b4272008-04-14 22:03:09 +00001097Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001098 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1099 return S;
1100 // replace continue with goto __continue_label
1101 std::string buf;
1102
1103 SourceLocation startLoc = S->getLocStart();
1104 buf = "goto __continue_label_";
1105 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001106 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001107
1108 return 0;
1109}
1110
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001111/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001112/// It rewrites:
1113/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001114
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001115/// Into:
1116/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001117/// type elem;
1118/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001119/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001120/// id l_collection = (id)collection;
1121/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1122/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001123/// if (limit) {
1124/// unsigned long startMutations = *enumState.mutationsPtr;
1125/// do {
1126/// unsigned long counter = 0;
1127/// do {
1128/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001129/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001130/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001131/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001132/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001133/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1135/// objects:items count:16]);
1136/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001137/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001138/// }
1139/// else
1140/// elem = nil;
1141/// }
1142///
Steve Naroffb29b4272008-04-14 22:03:09 +00001143Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001144 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001145 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1146 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1147 "ObjCForCollectionStmt Statement stack mismatch");
1148 assert(!ObjCBcLabelNo.empty() &&
1149 "ObjCForCollectionStmt - Label No stack empty");
1150
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001151 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001152 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001153 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001154 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001155 std::string buf;
1156 buf = "\n{\n\t";
1157 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1158 // type elem;
1159 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001160 elementTypeAsString = ElementType.getAsString();
1161 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 buf += " ";
1163 elementName = DS->getDecl()->getName();
1164 buf += elementName;
1165 buf += ";\n\t";
1166 }
Chris Lattner06767512008-04-08 05:52:18 +00001167 else {
1168 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001169 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001170 elementTypeAsString = DR->getDecl()->getType().getAsString();
1171 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001172
1173 // struct __objcFastEnumerationState enumState = { 0 };
1174 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1175 // id items[16];
1176 buf += "id items[16];\n\t";
1177 // id l_collection = (id)
1178 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001179 // Find start location of 'collection' the hard way!
1180 const char *startCollectionBuf = startBuf;
1181 startCollectionBuf += 3; // skip 'for'
1182 startCollectionBuf = strchr(startCollectionBuf, '(');
1183 startCollectionBuf++; // skip '('
1184 // find 'in' and skip it.
1185 while (*startCollectionBuf != ' ' ||
1186 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1187 (*(startCollectionBuf+3) != ' ' &&
1188 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1189 startCollectionBuf++;
1190 startCollectionBuf += 3;
1191
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001192 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001193 ReplaceText(startLoc, startCollectionBuf - startBuf,
1194 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001195 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001196 SourceLocation rightParenLoc = S->getRParenLoc();
1197 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1198 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001199 buf = ";\n\t";
1200
1201 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1202 // objects:items count:16];
1203 // which is synthesized into:
1204 // unsigned int limit =
1205 // ((unsigned int (*)
1206 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1207 // (void *)objc_msgSend)((id)l_collection,
1208 // sel_registerName(
1209 // "countByEnumeratingWithState:objects:count:"),
1210 // (struct __objcFastEnumerationState *)&state,
1211 // (id *)items, (unsigned int)16);
1212 buf += "unsigned long limit =\n\t\t";
1213 SynthCountByEnumWithState(buf);
1214 buf += ";\n\t";
1215 /// if (limit) {
1216 /// unsigned long startMutations = *enumState.mutationsPtr;
1217 /// do {
1218 /// unsigned long counter = 0;
1219 /// do {
1220 /// if (startMutations != *enumState.mutationsPtr)
1221 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001222 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001223 buf += "if (limit) {\n\t";
1224 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1225 buf += "do {\n\t\t";
1226 buf += "unsigned long counter = 0;\n\t\t";
1227 buf += "do {\n\t\t\t";
1228 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1229 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1230 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001231 buf += " = (";
1232 buf += elementTypeAsString;
1233 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001234 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001235 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001236
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001237 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001238 /// } while (counter < limit);
1239 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1240 /// objects:items count:16]);
1241 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001242 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001243 /// }
1244 /// else
1245 /// elem = nil;
1246 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001247 ///
1248 buf = ";\n\t";
1249 buf += "__continue_label_";
1250 buf += utostr(ObjCBcLabelNo.back());
1251 buf += ": ;";
1252 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001253 buf += "} while (counter < limit);\n\t";
1254 buf += "} while (limit = ";
1255 SynthCountByEnumWithState(buf);
1256 buf += ");\n\t";
1257 buf += elementName;
1258 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001259 buf += "__break_label_";
1260 buf += utostr(ObjCBcLabelNo.back());
1261 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001262 buf += "}\n\t";
1263 buf += "else\n\t\t";
1264 buf += elementName;
1265 buf += " = nil;\n";
1266 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001267
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001269 if (isa<CompoundStmt>(S->getBody())) {
1270 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1271 InsertText(endBodyLoc, buf.c_str(), buf.size());
1272 } else {
1273 /* Need to treat single statements specially. For example:
1274 *
1275 * for (A *a in b) if (stuff()) break;
1276 * for (A *a in b) xxxyy;
1277 *
1278 * The following code simply scans ahead to the semi to find the actual end.
1279 */
1280 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1281 const char *semiBuf = strchr(stmtBuf, ';');
1282 assert(semiBuf && "Can't find ';'");
1283 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1284 InsertText(endBodyLoc, buf.c_str(), buf.size());
1285 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001286 Stmts.pop_back();
1287 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001288 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001289}
1290
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001291/// RewriteObjCSynchronizedStmt -
1292/// This routine rewrites @synchronized(expr) stmt;
1293/// into:
1294/// objc_sync_enter(expr);
1295/// @try stmt @finally { objc_sync_exit(expr); }
1296///
Steve Naroffb29b4272008-04-14 22:03:09 +00001297Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001298 // Get the start location and compute the semi location.
1299 SourceLocation startLoc = S->getLocStart();
1300 const char *startBuf = SM->getCharacterData(startLoc);
1301
1302 assert((*startBuf == '@') && "bogus @synchronized location");
1303
1304 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001305 buf = "objc_sync_enter((id)";
1306 const char *lparenBuf = startBuf;
1307 while (*lparenBuf != '(') lparenBuf++;
1308 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001309 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1310 // the sync expression is typically a message expression that's already
1311 // been rewritten! (which implies the SourceLocation's are invalid).
1312 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001313 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001314 while (*endBuf != ')') endBuf--;
1315 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001316 buf = ");\n";
1317 // declare a new scope with two variables, _stack and _rethrow.
1318 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1319 buf += "int buf[18/*32-bit i386*/];\n";
1320 buf += "char *pointers[4];} _stack;\n";
1321 buf += "id volatile _rethrow = 0;\n";
1322 buf += "objc_exception_try_enter(&_stack);\n";
1323 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001324 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001325 startLoc = S->getSynchBody()->getLocEnd();
1326 startBuf = SM->getCharacterData(startLoc);
1327
Steve Naroffc7089f12008-08-19 13:04:19 +00001328 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001329 SourceLocation lastCurlyLoc = startLoc;
1330 buf = "}\nelse {\n";
1331 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1332 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001333 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001334 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1335 S->getSynchExpr(), SourceLocation());
Steve Naroffb2a39452008-07-16 19:47:39 +00001336 std::ostringstream syncExprBuf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001337 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001338 buf += syncExprBuf.str();
1339 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001340 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1341 buf += "}\n";
1342 buf += "}";
1343
Chris Lattneraadaf782008-01-31 19:51:04 +00001344 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001345 return 0;
1346}
1347
Steve Naroffb29b4272008-04-14 22:03:09 +00001348Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001349 // Get the start location and compute the semi location.
1350 SourceLocation startLoc = S->getLocStart();
1351 const char *startBuf = SM->getCharacterData(startLoc);
1352
1353 assert((*startBuf == '@') && "bogus @try location");
1354
1355 std::string buf;
1356 // declare a new scope with two variables, _stack and _rethrow.
1357 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1358 buf += "int buf[18/*32-bit i386*/];\n";
1359 buf += "char *pointers[4];} _stack;\n";
1360 buf += "id volatile _rethrow = 0;\n";
1361 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001362 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001363
Chris Lattneraadaf782008-01-31 19:51:04 +00001364 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001365
1366 startLoc = S->getTryBody()->getLocEnd();
1367 startBuf = SM->getCharacterData(startLoc);
1368
1369 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001370
Steve Naroff75730982007-11-07 04:08:17 +00001371 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001372 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1373 if (catchList) {
1374 startLoc = startLoc.getFileLocWithOffset(1);
1375 buf = " /* @catch begin */ else {\n";
1376 buf += " id _caught = objc_exception_extract(&_stack);\n";
1377 buf += " objc_exception_try_enter (&_stack);\n";
1378 buf += " if (_setjmp(_stack.buf))\n";
1379 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1380 buf += " else { /* @catch continue */";
1381
1382 InsertText(startLoc, buf.c_str(), buf.size());
1383 }
Steve Naroff75730982007-11-07 04:08:17 +00001384 bool sawIdTypedCatch = false;
1385 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001386 while (catchList) {
1387 Stmt *catchStmt = catchList->getCatchParamStmt();
1388
1389 if (catchList == S->getCatchStmts())
1390 buf = "if ("; // we are generating code for the first catch clause
1391 else
1392 buf = "else if (";
1393 startLoc = catchList->getLocStart();
1394 startBuf = SM->getCharacterData(startLoc);
1395
1396 assert((*startBuf == '@') && "bogus @catch location");
1397
1398 const char *lParenLoc = strchr(startBuf, '(');
1399
Steve Naroffbe4b3332008-02-01 22:08:12 +00001400 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001401 // Now rewrite the body...
1402 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001403 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1404 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001405 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1406 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001407 assert((*bodyBuf == '{') && "bogus @catch body location");
1408
1409 buf += "1) { id _tmp = _caught;";
1410 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1411 buf.c_str(), buf.size());
1412 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001413 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001414 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001415 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001416 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001417 sawIdTypedCatch = true;
1418 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001419 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001420
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001421 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001422 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001423 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001424 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001425 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001426 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001427 }
1428 }
1429 // Now rewrite the body...
1430 lastCatchBody = catchList->getCatchBody();
1431 SourceLocation rParenLoc = catchList->getRParenLoc();
1432 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1433 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1434 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1435 assert((*rParenBuf == ')') && "bogus @catch paren location");
1436 assert((*bodyBuf == '{') && "bogus @catch body location");
1437
1438 buf = " = _caught;";
1439 // Here we replace ") {" with "= _caught;" (which initializes and
1440 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001441 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001442 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001443 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001444 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001445 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001446 catchList = catchList->getNextCatchStmt();
1447 }
1448 // Complete the catch list...
1449 if (lastCatchBody) {
1450 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001451 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1452 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001453 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1454 buf = " } } /* @catch end */\n";
1455
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001456 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001457
1458 // Set lastCurlyLoc
1459 lastCurlyLoc = lastCatchBody->getLocEnd();
1460 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001461 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001462 startLoc = finalStmt->getLocStart();
1463 startBuf = SM->getCharacterData(startLoc);
1464 assert((*startBuf == '@') && "bogus @finally start");
1465
1466 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001467 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001468
1469 Stmt *body = finalStmt->getFinallyBody();
1470 SourceLocation startLoc = body->getLocStart();
1471 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001472 assert(*SM->getCharacterData(startLoc) == '{' &&
1473 "bogus @finally body location");
1474 assert(*SM->getCharacterData(endLoc) == '}' &&
1475 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001476
1477 startLoc = startLoc.getFileLocWithOffset(1);
1478 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001479 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001480 endLoc = endLoc.getFileLocWithOffset(-1);
1481 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001482 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001483
1484 // Set lastCurlyLoc
1485 lastCurlyLoc = body->getLocEnd();
1486 }
1487 // Now emit the final closing curly brace...
1488 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1489 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001490 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001491 return 0;
1492}
1493
Steve Naroffb29b4272008-04-14 22:03:09 +00001494Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001495 return 0;
1496}
1497
Steve Naroffb29b4272008-04-14 22:03:09 +00001498Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001499 return 0;
1500}
1501
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001502// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001503// the throw expression is typically a message expression that's already
1504// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001505Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001506 // Get the start location and compute the semi location.
1507 SourceLocation startLoc = S->getLocStart();
1508 const char *startBuf = SM->getCharacterData(startLoc);
1509
1510 assert((*startBuf == '@') && "bogus @throw location");
1511
1512 std::string buf;
1513 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001514 if (S->getThrowExpr())
1515 buf = "objc_exception_throw(";
1516 else // add an implicit argument
1517 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001518
1519 // handle "@ throw" correctly.
1520 const char *wBuf = strchr(startBuf, 'w');
1521 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1522 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1523
Steve Naroff2bd03922007-11-07 15:32:26 +00001524 const char *semiBuf = strchr(startBuf, ';');
1525 assert((*semiBuf == ';') && "@throw: can't find ';'");
1526 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1527 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001528 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001529 return 0;
1530}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001531
Steve Naroffb29b4272008-04-14 22:03:09 +00001532Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001533 // Create a new string expression.
1534 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001535 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001536 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1537 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001538 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1539 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001540 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001541 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001542
Chris Lattner07506182007-11-30 22:53:43 +00001543 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001544 delete Exp;
1545 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001546}
1547
Steve Naroffb29b4272008-04-14 22:03:09 +00001548Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001549 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1550 // Create a call to sel_registerName("selName").
1551 llvm::SmallVector<Expr*, 8> SelExprs;
1552 QualType argType = Context->getPointerType(Context->CharTy);
1553 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1554 Exp->getSelector().getName().size(),
1555 false, argType, SourceLocation(),
1556 SourceLocation()));
1557 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1558 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001559 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001560 delete Exp;
1561 return SelExp;
1562}
1563
Steve Naroffb29b4272008-04-14 22:03:09 +00001564CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001565 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001566 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001567 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001568
1569 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001570 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001571
1572 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001573 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001574 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1575
1576 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001577
Steve Naroff934f2762007-10-24 22:48:43 +00001578 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1579}
1580
Steve Naroffd5255f52007-11-01 13:24:47 +00001581static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1582 const char *&startRef, const char *&endRef) {
1583 while (startBuf < endBuf) {
1584 if (*startBuf == '<')
1585 startRef = startBuf; // mark the start.
1586 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001587 if (startRef && *startRef == '<') {
1588 endRef = startBuf; // mark the end.
1589 return true;
1590 }
1591 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001592 }
1593 startBuf++;
1594 }
1595 return false;
1596}
1597
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001598static void scanToNextArgument(const char *&argRef) {
1599 int angle = 0;
1600 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1601 if (*argRef == '<')
1602 angle++;
1603 else if (*argRef == '>')
1604 angle--;
1605 argRef++;
1606 }
1607 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1608}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001609
Steve Naroffb29b4272008-04-14 22:03:09 +00001610bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001611
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001612 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001613 return true;
1614
Steve Naroffd5255f52007-11-01 13:24:47 +00001615 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001616 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001617 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001618 return true; // we have "Class <Protocol> *".
1619 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001620 return false;
1621}
1622
Steve Naroff4f95b752008-07-29 18:15:38 +00001623void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1624 QualType Type = E->getType();
1625 if (needToScanForQualifiers(Type)) {
1626 SourceLocation Loc = E->getLocStart();
1627 const char *startBuf = SM->getCharacterData(Loc);
1628 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1629 const char *startRef = 0, *endRef = 0;
1630 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1631 // Get the locations of the startRef, endRef.
1632 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1633 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1634 // Comment out the protocol references.
1635 InsertText(LessLoc, "/*", 2);
1636 InsertText(GreaterLoc, "*/", 2);
1637 }
1638 }
1639}
1640
Steve Naroffb29b4272008-04-14 22:03:09 +00001641void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001642 SourceLocation Loc;
1643 QualType Type;
1644 const FunctionTypeProto *proto = 0;
1645 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1646 Loc = VD->getLocation();
1647 Type = VD->getType();
1648 }
1649 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1650 Loc = FD->getLocation();
1651 // Check for ObjC 'id' and class types that have been adorned with protocol
1652 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1653 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1654 assert(funcType && "missing function type");
1655 proto = dyn_cast<FunctionTypeProto>(funcType);
1656 if (!proto)
1657 return;
1658 Type = proto->getResultType();
1659 }
1660 else
1661 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001662
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001663 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001664 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001665
1666 const char *endBuf = SM->getCharacterData(Loc);
1667 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001668 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001669 startBuf--; // scan backward (from the decl location) for return type.
1670 const char *startRef = 0, *endRef = 0;
1671 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1672 // Get the locations of the startRef, endRef.
1673 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1674 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1675 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001676 InsertText(LessLoc, "/*", 2);
1677 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001678 }
1679 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001680 if (!proto)
1681 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001682 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001683 const char *startBuf = SM->getCharacterData(Loc);
1684 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001685 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1686 if (needToScanForQualifiers(proto->getArgType(i))) {
1687 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001688
Steve Naroffd5255f52007-11-01 13:24:47 +00001689 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001690 // scan forward (from the decl location) for argument types.
1691 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001692 const char *startRef = 0, *endRef = 0;
1693 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1694 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001695 SourceLocation LessLoc =
1696 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1697 SourceLocation GreaterLoc =
1698 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001699 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001700 InsertText(LessLoc, "/*", 2);
1701 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001702 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001703 startBuf = ++endBuf;
1704 }
1705 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001706 // If the function name is derived from a macro expansion, then the
1707 // argument buffer will not follow the name. Need to speak with Chris.
1708 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001709 startBuf++; // scan forward (from the decl location) for argument types.
1710 startBuf++;
1711 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001712 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001713}
1714
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001715// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001716void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001717 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1718 llvm::SmallVector<QualType, 16> ArgTys;
1719 ArgTys.push_back(Context->getPointerType(
1720 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001721 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001722 &ArgTys[0], ArgTys.size(),
1723 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001724 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001725 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001726 SelGetUidIdent, getFuncType,
1727 FunctionDecl::Extern, false, 0);
1728}
1729
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001730// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001731void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001732 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1733 llvm::SmallVector<QualType, 16> ArgTys;
1734 ArgTys.push_back(Context->getPointerType(
1735 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001736 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001737 &ArgTys[0], ArgTys.size(),
1738 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001739 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001740 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001741 SelGetProtoIdent, getFuncType,
1742 FunctionDecl::Extern, false, 0);
1743}
1744
Steve Naroffb29b4272008-04-14 22:03:09 +00001745void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001746 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001747 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001748 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001749 return;
1750 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001751 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001752}
1753
Steve Naroffc0a123c2008-03-11 17:37:02 +00001754// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001755void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001756 if (SuperContructorFunctionDecl)
1757 return;
1758 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1759 llvm::SmallVector<QualType, 16> ArgTys;
1760 QualType argT = Context->getObjCIdType();
1761 assert(!argT.isNull() && "Can't find 'id' type");
1762 ArgTys.push_back(argT);
1763 ArgTys.push_back(argT);
1764 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1765 &ArgTys[0], ArgTys.size(),
1766 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001767 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001768 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001769 msgSendIdent, msgSendType,
1770 FunctionDecl::Extern, false, 0);
1771}
1772
Steve Naroff09b266e2007-10-30 23:14:51 +00001773// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001774void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001775 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1776 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001777 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001778 assert(!argT.isNull() && "Can't find 'id' type");
1779 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001780 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001781 assert(!argT.isNull() && "Can't find 'SEL' type");
1782 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001783 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001784 &ArgTys[0], ArgTys.size(),
1785 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001786 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001787 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001788 msgSendIdent, msgSendType,
1789 FunctionDecl::Extern, false, 0);
1790}
1791
Steve Naroff874e2322007-11-15 10:28:18 +00001792// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001793void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001794 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1795 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001796 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001797 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001798 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001799 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1800 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1801 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001802 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001803 assert(!argT.isNull() && "Can't find 'SEL' type");
1804 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001805 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001806 &ArgTys[0], ArgTys.size(),
1807 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001808 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001809 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001810 msgSendIdent, msgSendType,
1811 FunctionDecl::Extern, false, 0);
1812}
1813
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001814// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001815void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001816 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1817 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001818 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001819 assert(!argT.isNull() && "Can't find 'id' type");
1820 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001821 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001822 assert(!argT.isNull() && "Can't find 'SEL' type");
1823 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001824 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001825 &ArgTys[0], ArgTys.size(),
1826 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001827 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001828 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001829 msgSendIdent, msgSendType,
1830 FunctionDecl::Extern, false, 0);
1831}
1832
1833// SynthMsgSendSuperStretFunctionDecl -
1834// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001835void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001836 IdentifierInfo *msgSendIdent =
1837 &Context->Idents.get("objc_msgSendSuper_stret");
1838 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001839 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001840 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001841 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001842 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1843 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1844 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001845 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001846 assert(!argT.isNull() && "Can't find 'SEL' type");
1847 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001849 &ArgTys[0], ArgTys.size(),
1850 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001851 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001852 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001853 msgSendIdent, msgSendType,
1854 FunctionDecl::Extern, false, 0);
1855}
1856
Steve Naroff1284db82008-05-08 22:02:18 +00001857// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001858void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001859 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1860 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001861 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001862 assert(!argT.isNull() && "Can't find 'id' type");
1863 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001865 assert(!argT.isNull() && "Can't find 'SEL' type");
1866 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001867 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001868 &ArgTys[0], ArgTys.size(),
1869 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001870 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001871 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001872 msgSendIdent, msgSendType,
1873 FunctionDecl::Extern, false, 0);
1874}
1875
Steve Naroff09b266e2007-10-30 23:14:51 +00001876// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001877void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001878 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1879 llvm::SmallVector<QualType, 16> ArgTys;
1880 ArgTys.push_back(Context->getPointerType(
1881 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001883 &ArgTys[0], ArgTys.size(),
1884 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001885 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001886 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001887 getClassIdent, getClassType,
1888 FunctionDecl::Extern, false, 0);
1889}
1890
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001891// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001892void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001893 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1894 llvm::SmallVector<QualType, 16> ArgTys;
1895 ArgTys.push_back(Context->getPointerType(
1896 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001898 &ArgTys[0], ArgTys.size(),
1899 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001900 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001901 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001902 getClassIdent, getClassType,
1903 FunctionDecl::Extern, false, 0);
1904}
1905
Steve Naroffb29b4272008-04-14 22:03:09 +00001906Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001907 QualType strType = getConstantStringStructType();
1908
1909 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001910
1911 std::string tmpName = InFileName;
1912 unsigned i;
1913 for (i=0; i < tmpName.length(); i++) {
1914 char c = tmpName.at(i);
1915 // replace any non alphanumeric characters with '_'.
1916 if (!isalpha(c) && (c < '0' || c > '9'))
1917 tmpName[i] = '_';
1918 }
1919 S += tmpName;
1920 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001921 S += utostr(NumObjCStringLiterals++);
1922
Steve Naroffba92b2e2008-03-27 22:29:16 +00001923 Preamble += "static __NSConstantStringImpl " + S;
1924 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1925 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001926 // The pretty printer for StringLiteral handles escape characters properly.
1927 std::ostringstream prettyBuf;
1928 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001929 Preamble += prettyBuf.str();
1930 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001931 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001932 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001933
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001934 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001935 &Context->Idents.get(S.c_str()), strType,
1936 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001937 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1938 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1939 Context->getPointerType(DRE->getType()),
1940 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001941 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001942 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001943 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001944 delete Exp;
1945 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001946}
1947
Steve Naroffb29b4272008-04-14 22:03:09 +00001948ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001949 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001950 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1951
Chris Lattnerd9f69102008-08-10 01:53:14 +00001952 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1953 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001954 const PointerType *PT = PDE->getType()->getAsPointerType();
1955 assert(PT);
1956 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1957 return IT->getDecl();
1958 }
1959 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001960}
1961
1962// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001963QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001964 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001965 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001966 SourceLocation(),
1967 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001968 QualType FieldTypes[2];
1969
1970 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001971 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001972 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001973 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001974 // Create fields
1975 FieldDecl *FieldDecls[2];
1976
1977 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001978 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001979 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001980
1981 SuperStructDecl->defineBody(FieldDecls, 4);
1982 }
1983 return Context->getTagDeclType(SuperStructDecl);
1984}
1985
Steve Naroffb29b4272008-04-14 22:03:09 +00001986QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001987 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001988 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001989 SourceLocation(),
1990 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001991 QualType FieldTypes[4];
1992
1993 // struct objc_object *receiver;
1994 FieldTypes[0] = Context->getObjCIdType();
1995 // int flags;
1996 FieldTypes[1] = Context->IntTy;
1997 // char *str;
1998 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1999 // long length;
2000 FieldTypes[3] = Context->LongTy;
2001 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002002 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002003
2004 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002005 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002006 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002007
2008 ConstantStringDecl->defineBody(FieldDecls, 4);
2009 }
2010 return Context->getTagDeclType(ConstantStringDecl);
2011}
2012
Steve Naroffb29b4272008-04-14 22:03:09 +00002013Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002014 if (!SelGetUidFunctionDecl)
2015 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002016 if (!MsgSendFunctionDecl)
2017 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002018 if (!MsgSendSuperFunctionDecl)
2019 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002020 if (!MsgSendStretFunctionDecl)
2021 SynthMsgSendStretFunctionDecl();
2022 if (!MsgSendSuperStretFunctionDecl)
2023 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002024 if (!MsgSendFpretFunctionDecl)
2025 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002026 if (!GetClassFunctionDecl)
2027 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002028 if (!GetMetaClassFunctionDecl)
2029 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002030
Steve Naroff874e2322007-11-15 10:28:18 +00002031 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002032 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2033 // May need to use objc_msgSend_stret() as well.
2034 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002036 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002037 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002038 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002039 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002040 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 }
Steve Naroff874e2322007-11-15 10:28:18 +00002042
Steve Naroff934f2762007-10-24 22:48:43 +00002043 // Synthesize a call to objc_msgSend().
2044 llvm::SmallVector<Expr*, 8> MsgExprs;
2045 IdentifierInfo *clsName = Exp->getClassName();
2046
2047 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2048 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002049 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2050 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002051 if (!strcmp(clsName->getName(), "super")) {
2052 MsgSendFlavor = MsgSendSuperFunctionDecl;
2053 if (MsgSendStretFlavor)
2054 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2055 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2056
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002057 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002058 CurMethodDecl->getClassInterface()->getSuperClass();
2059
2060 llvm::SmallVector<Expr*, 4> InitExprs;
2061
2062 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002063 InitExprs.push_back(new DeclRefExpr(
2064 CurMethodDecl->getSelfDecl(),
2065 Context->getObjCIdType(),
2066 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002067 llvm::SmallVector<Expr*, 8> ClsExprs;
2068 QualType argType = Context->getPointerType(Context->CharTy);
2069 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2070 SuperDecl->getIdentifier()->getLength(),
2071 false, argType, SourceLocation(),
2072 SourceLocation()));
2073 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2074 &ClsExprs[0],
2075 ClsExprs.size());
2076 // To turn off a warning, type-cast to 'id'
2077 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002078 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002079 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2080 // struct objc_super
2081 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002082 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002083
Steve Naroff23f41272008-03-11 18:14:26 +00002084 if (LangOpts.Microsoft) {
2085 SynthSuperContructorFunctionDecl();
2086 // Simulate a contructor call...
2087 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2088 superType, SourceLocation());
2089 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2090 superType, SourceLocation());
2091 } else {
2092 // (struct objc_super) { <exprs from above> }
2093 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2094 &InitExprs[0], InitExprs.size(),
2095 SourceLocation());
2096 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2097 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 // struct objc_super *
2099 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2100 Context->getPointerType(SuperRep->getType()),
2101 SourceLocation());
2102 MsgExprs.push_back(Unop);
2103 } else {
2104 llvm::SmallVector<Expr*, 8> ClsExprs;
2105 QualType argType = Context->getPointerType(Context->CharTy);
2106 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2107 clsName->getLength(),
2108 false, argType, SourceLocation(),
2109 SourceLocation()));
2110 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2111 &ClsExprs[0],
2112 ClsExprs.size());
2113 MsgExprs.push_back(Cls);
2114 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002115 } else { // instance message.
2116 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002117
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002118 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002119 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002120 if (MsgSendStretFlavor)
2121 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002122 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2123
2124 llvm::SmallVector<Expr*, 4> InitExprs;
2125
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002126 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002127 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002128 new DeclRefExpr(CurMethodDecl->getSelfDecl(),
2129 Context->getObjCIdType(),
2130 SourceLocation()),
2131 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002132
2133 llvm::SmallVector<Expr*, 8> ClsExprs;
2134 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002135 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2136 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002137 false, argType, SourceLocation(),
2138 SourceLocation()));
2139 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002140 &ClsExprs[0],
2141 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002142 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002143 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002144 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002145 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002146 // struct objc_super
2147 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002148 Expr *SuperRep;
2149
2150 if (LangOpts.Microsoft) {
2151 SynthSuperContructorFunctionDecl();
2152 // Simulate a contructor call...
2153 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2154 superType, SourceLocation());
2155 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2156 superType, SourceLocation());
2157 } else {
2158 // (struct objc_super) { <exprs from above> }
2159 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2160 &InitExprs[0], InitExprs.size(),
2161 SourceLocation());
2162 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2163 }
Steve Naroff874e2322007-11-15 10:28:18 +00002164 // struct objc_super *
2165 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2166 Context->getPointerType(SuperRep->getType()),
2167 SourceLocation());
2168 MsgExprs.push_back(Unop);
2169 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002170 // Remove all type-casts because it may contain objc-style types; e.g.
2171 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002172 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002173 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002174 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2175 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002176 MsgExprs.push_back(recExpr);
2177 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002178 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002179 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002180 llvm::SmallVector<Expr*, 8> SelExprs;
2181 QualType argType = Context->getPointerType(Context->CharTy);
2182 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2183 Exp->getSelector().getName().size(),
2184 false, argType, SourceLocation(),
2185 SourceLocation()));
2186 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2187 &SelExprs[0], SelExprs.size());
2188 MsgExprs.push_back(SelExp);
2189
2190 // Now push any user supplied arguments.
2191 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002192 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002193 // Make all implicit casts explicit...ICE comes in handy:-)
2194 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2195 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002196 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002198 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002199 }
2200 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002201 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002202 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002203 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002204 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002205 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002206 userExpr, SourceLocation());
2207 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002208 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002209 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002210 // We've transferred the ownership to MsgExprs. Null out the argument in
2211 // the original expression, since we will delete it below.
2212 Exp->setArg(i, 0);
2213 }
Steve Naroffab972d32007-11-04 22:37:50 +00002214 // Generate the funky cast.
2215 CastExpr *cast;
2216 llvm::SmallVector<QualType, 8> ArgTypes;
2217 QualType returnType;
2218
2219 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002220 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2221 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2222 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 ArgTypes.push_back(Context->getObjCIdType());
2224 ArgTypes.push_back(Context->getObjCSelType());
2225 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002226 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002227 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002228 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2229 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002230 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002231 ArgTypes.push_back(t);
2232 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2234 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002235 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002237 }
2238 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002239 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002240
2241 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2243 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002244
2245 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2246 // If we don't do this cast, we get the following bizarre warning/note:
2247 // xx.m:13: warning: function called through a non-compatible type
2248 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002249 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002250 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002251
Steve Naroffab972d32007-11-04 22:37:50 +00002252 // Now do the "normal" pointer to function cast.
2253 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002254 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002255 // If we don't have a method decl, force a variadic cast.
2256 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002257 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002258 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002259
2260 // Don't forget the parens to enforce the proper binding.
2261 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2262
2263 const FunctionType *FT = msgSendType->getAsFunctionType();
2264 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2265 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002266 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267 if (MsgSendStretFlavor) {
2268 // We have the method which returns a struct/union. Must also generate
2269 // call to objc_msgSend_stret and hang both varieties on a conditional
2270 // expression which dictate which one to envoke depending on size of
2271 // method's return type.
2272
2273 // Create a reference to the objc_msgSend_stret() declaration.
2274 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2275 SourceLocation());
2276 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002277 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002278 SourceLocation());
2279 // Now do the "normal" pointer to function cast.
2280 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002281 &ArgTypes[0], ArgTypes.size(),
2282 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002283 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002284 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002285
2286 // Don't forget the parens to enforce the proper binding.
2287 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2288
2289 FT = msgSendType->getAsFunctionType();
2290 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2291 FT->getResultType(), SourceLocation());
2292
2293 // Build sizeof(returnType)
2294 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2295 returnType, Context->getSizeType(),
2296 SourceLocation(), SourceLocation());
2297 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2298 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2299 // For X86 it is more complicated and some kind of target specific routine
2300 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002301 unsigned IntSize =
2302 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002303 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2304 Context->IntTy,
2305 SourceLocation());
2306 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2307 BinaryOperator::LE,
2308 Context->IntTy,
2309 SourceLocation());
2310 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2311 ConditionalOperator *CondExpr =
2312 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002313 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002314 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002315 return ReplacingStmt;
2316}
2317
Steve Naroffb29b4272008-04-14 22:03:09 +00002318Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002319 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002320 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002321 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002322
Chris Lattnere64b7772007-10-24 16:57:36 +00002323 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002324 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002325}
2326
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002327/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2328/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002329Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002330 if (!GetProtocolFunctionDecl)
2331 SynthGetProtocolFunctionDecl();
2332 // Create a call to objc_getProtocol("ProtocolName").
2333 llvm::SmallVector<Expr*, 8> ProtoExprs;
2334 QualType argType = Context->getPointerType(Context->CharTy);
2335 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2336 strlen(Exp->getProtocol()->getName()),
2337 false, argType, SourceLocation(),
2338 SourceLocation()));
2339 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2340 &ProtoExprs[0],
2341 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002342 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002343 delete Exp;
2344 return ProtoExp;
2345
2346}
2347
Steve Naroffbaf58c32008-05-31 14:15:04 +00002348bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2349 const char *endBuf) {
2350 while (startBuf < endBuf) {
2351 if (*startBuf == '#') {
2352 // Skip whitespace.
2353 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2354 ;
2355 if (!strncmp(startBuf, "if", strlen("if")) ||
2356 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2357 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2358 !strncmp(startBuf, "define", strlen("define")) ||
2359 !strncmp(startBuf, "undef", strlen("undef")) ||
2360 !strncmp(startBuf, "else", strlen("else")) ||
2361 !strncmp(startBuf, "elif", strlen("elif")) ||
2362 !strncmp(startBuf, "endif", strlen("endif")) ||
2363 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2364 !strncmp(startBuf, "include", strlen("include")) ||
2365 !strncmp(startBuf, "import", strlen("import")) ||
2366 !strncmp(startBuf, "include_next", strlen("include_next")))
2367 return true;
2368 }
2369 startBuf++;
2370 }
2371 return false;
2372}
2373
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002375/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002376void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002377 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2379 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002380 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002382 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002383 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002384 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002385 SourceLocation LocStart = CDecl->getLocStart();
2386 SourceLocation LocEnd = CDecl->getLocEnd();
2387
2388 const char *startBuf = SM->getCharacterData(LocStart);
2389 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002390
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002391 // If no ivars and no root or if its root, directly or indirectly,
2392 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002393 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2394 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002395 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002396 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002397 return;
2398 }
2399
2400 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002401 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002402 Result += "\nstruct ";
2403 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002404 if (LangOpts.Microsoft)
2405 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002406
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002407 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002408 const char *cursor = strchr(startBuf, '{');
2409 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002411 // If the buffer contains preprocessor directives, we do more fine-grained
2412 // rewrites. This is intended to fix code that looks like (which occurs in
2413 // NSURL.h, for example):
2414 //
2415 // #ifdef XYZ
2416 // @interface Foo : NSObject
2417 // #else
2418 // @interface FooBar : NSObject
2419 // #endif
2420 // {
2421 // int i;
2422 // }
2423 // @end
2424 //
2425 // This clause is segregated to avoid breaking the common case.
2426 if (BufferContainsPPDirectives(startBuf, cursor)) {
2427 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2428 CDecl->getClassLoc();
2429 const char *endHeader = SM->getCharacterData(L);
2430 endHeader += Lexer::MeasureTokenLength(L, *SM);
2431
Chris Lattner3db6cae2008-07-21 18:19:38 +00002432 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002433 // advance to the end of the referenced protocols.
2434 while (endHeader < cursor && *endHeader != '>') endHeader++;
2435 endHeader++;
2436 }
2437 // rewrite the original header
2438 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2439 } else {
2440 // rewrite the original header *without* disturbing the '{'
2441 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2442 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002444 Result = "\n struct ";
2445 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002446 Result += "_IMPL ";
2447 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002448 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002449
2450 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002451 SourceLocation OnePastCurly =
2452 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2453 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002454 }
2455 cursor++; // past '{'
2456
2457 // Now comment out any visibility specifiers.
2458 while (cursor < endBuf) {
2459 if (*cursor == '@') {
2460 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002461 // Skip whitespace.
2462 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2463 /*scan*/;
2464
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002465 // FIXME: presence of @public, etc. inside comment results in
2466 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002467 if (!strncmp(cursor, "public", strlen("public")) ||
2468 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002469 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002470 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002471 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002472 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002473 // FIXME: If there are cases where '<' is used in ivar declaration part
2474 // of user code, then scan the ivar list and use needToScanForQualifiers
2475 // for type checking.
2476 else if (*cursor == '<') {
2477 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002478 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002479 cursor = strchr(cursor, '>');
2480 cursor++;
2481 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002482 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002483 }
Steve Narofffea763e82007-11-14 19:25:57 +00002484 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002485 }
Steve Narofffea763e82007-11-14 19:25:57 +00002486 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002487 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002488 } else { // we don't have any instance variables - insert super struct.
2489 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2490 Result += " {\n struct ";
2491 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002492 Result += "_IMPL ";
2493 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002494 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002495 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002496 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002497 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002498 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002499 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002500}
2501
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002502// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002503/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002504void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002505 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002506 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002507 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002508 const char *ClassName,
2509 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002510 if (MethodBegin == MethodEnd) return;
2511
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002512 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002513 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002514 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002515 SEL _cmd;
2516 char *method_types;
2517 void *_imp;
2518 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002519 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002520 Result += "\nstruct _objc_method {\n";
2521 Result += "\tSEL _cmd;\n";
2522 Result += "\tchar *method_types;\n";
2523 Result += "\tvoid *_imp;\n";
2524 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002525
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002526 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002527 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002528
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002529 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002530
2531 /* struct {
2532 struct _objc_method_list *next_method;
2533 int method_count;
2534 struct _objc_method method_list[];
2535 }
2536 */
2537 Result += "\nstatic struct {\n";
2538 Result += "\tstruct _objc_method_list *next_method;\n";
2539 Result += "\tint method_count;\n";
2540 Result += "\tstruct _objc_method method_list[";
2541 Result += utostr(MethodEnd-MethodBegin);
2542 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002543 Result += prefix;
2544 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2545 Result += "_METHODS_";
2546 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002547 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002548 Result += IsInstanceMethod ? "inst" : "cls";
2549 Result += "_meth\")))= ";
2550 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002551
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002552 Result += "\t,{{(SEL)\"";
2553 Result += (*MethodBegin)->getSelector().getName().c_str();
2554 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002556 Result += "\", \"";
2557 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002558 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002559 Result += MethodInternalNames[*MethodBegin];
2560 Result += "}\n";
2561 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2562 Result += "\t ,{(SEL)\"";
2563 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002564 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002566 Result += "\", \"";
2567 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002568 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002569 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002570 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002571 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002572 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002573}
2574
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002575/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002576void RewriteObjC::
2577RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2578 const char *prefix,
2579 const char *ClassName,
2580 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002581 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002582 if (Protocols.empty()) return;
2583
2584 for (unsigned i = 0; i != Protocols.size(); i++) {
2585 ObjCProtocolDecl *PDecl = Protocols[i];
2586 // Output struct protocol_methods holder of method selector and type.
2587 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2588 /* struct protocol_methods {
2589 SEL _cmd;
2590 char *method_types;
2591 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002592 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002593 Result += "\nstruct protocol_methods {\n";
2594 Result += "\tSEL _cmd;\n";
2595 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002596 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002597
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002598 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002599 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002600 // Do not synthesize the protocol more than once.
2601 if (ObjCSynthesizedProtocols.count(PDecl))
2602 continue;
2603
2604 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2605 unsigned NumMethods = PDecl->getNumInstanceMethods();
2606 /* struct _objc_protocol_method_list {
2607 int protocol_method_count;
2608 struct protocol_methods protocols[];
2609 }
2610 */
2611 Result += "\nstatic struct {\n";
2612 Result += "\tint protocol_method_count;\n";
2613 Result += "\tstruct protocol_methods protocols[";
2614 Result += utostr(NumMethods);
2615 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2616 Result += PDecl->getName();
2617 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2618 "{\n\t" + utostr(NumMethods) + "\n";
2619
2620 // Output instance methods declared in this protocol.
2621 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2622 E = PDecl->instmeth_end(); I != E; ++I) {
2623 if (I == PDecl->instmeth_begin())
2624 Result += "\t ,{{(SEL)\"";
2625 else
2626 Result += "\t ,{(SEL)\"";
2627 Result += (*I)->getSelector().getName().c_str();
2628 std::string MethodTypeString;
2629 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2630 Result += "\", \"";
2631 Result += MethodTypeString;
2632 Result += "\"}\n";
2633 }
2634 Result += "\t }\n};\n";
2635 }
2636
2637 // Output class methods declared in this protocol.
2638 int NumMethods = PDecl->getNumClassMethods();
2639 if (NumMethods > 0) {
2640 /* struct _objc_protocol_method_list {
2641 int protocol_method_count;
2642 struct protocol_methods protocols[];
2643 }
2644 */
2645 Result += "\nstatic struct {\n";
2646 Result += "\tint protocol_method_count;\n";
2647 Result += "\tstruct protocol_methods protocols[";
2648 Result += utostr(NumMethods);
2649 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2650 Result += PDecl->getName();
2651 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2652 "{\n\t";
2653 Result += utostr(NumMethods);
2654 Result += "\n";
2655
2656 // Output instance methods declared in this protocol.
2657 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2658 E = PDecl->classmeth_end(); I != E; ++I) {
2659 if (I == PDecl->classmeth_begin())
2660 Result += "\t ,{{(SEL)\"";
2661 else
2662 Result += "\t ,{(SEL)\"";
2663 Result += (*I)->getSelector().getName().c_str();
2664 std::string MethodTypeString;
2665 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2666 Result += "\", \"";
2667 Result += MethodTypeString;
2668 Result += "\"}\n";
2669 }
2670 Result += "\t }\n};\n";
2671 }
2672
2673 // Output:
2674 /* struct _objc_protocol {
2675 // Objective-C 1.0 extensions
2676 struct _objc_protocol_extension *isa;
2677 char *protocol_name;
2678 struct _objc_protocol **protocol_list;
2679 struct _objc_protocol_method_list *instance_methods;
2680 struct _objc_protocol_method_list *class_methods;
2681 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002682 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002683 static bool objc_protocol = false;
2684 if (!objc_protocol) {
2685 Result += "\nstruct _objc_protocol {\n";
2686 Result += "\tstruct _objc_protocol_extension *isa;\n";
2687 Result += "\tchar *protocol_name;\n";
2688 Result += "\tstruct _objc_protocol **protocol_list;\n";
2689 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2690 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2691 Result += "};\n";
2692
2693 objc_protocol = true;
2694 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002695
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002696 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2697 Result += PDecl->getName();
2698 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2699 "{\n\t0, \"";
2700 Result += PDecl->getName();
2701 Result += "\", 0, ";
2702 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2703 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2704 Result += PDecl->getName();
2705 Result += ", ";
2706 }
2707 else
2708 Result += "0, ";
2709 if (PDecl->getNumClassMethods() > 0) {
2710 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2711 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002712 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002713 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002714 else
2715 Result += "0\n";
2716 Result += "};\n";
2717
2718 // Mark this protocol as having been generated.
2719 if (!ObjCSynthesizedProtocols.insert(PDecl))
2720 assert(false && "protocol already synthesized");
2721 }
2722 // Output the top lovel protocol meta-data for the class.
2723 /* struct _objc_protocol_list {
2724 struct _objc_protocol_list *next;
2725 int protocol_count;
2726 struct _objc_protocol *class_protocols[];
2727 }
2728 */
2729 Result += "\nstatic struct {\n";
2730 Result += "\tstruct _objc_protocol_list *next;\n";
2731 Result += "\tint protocol_count;\n";
2732 Result += "\tstruct _objc_protocol *class_protocols[";
2733 Result += utostr(Protocols.size());
2734 Result += "];\n} _OBJC_";
2735 Result += prefix;
2736 Result += "_PROTOCOLS_";
2737 Result += ClassName;
2738 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2739 "{\n\t0, ";
2740 Result += utostr(Protocols.size());
2741 Result += "\n";
2742
2743 Result += "\t,{&_OBJC_PROTOCOL_";
2744 Result += Protocols[0]->getName();
2745 Result += " \n";
2746
2747 for (unsigned i = 1; i != Protocols.size(); i++) {
2748 Result += "\t ,&_OBJC_PROTOCOL_";
2749 Result += Protocols[i]->getName();
2750 Result += "\n";
2751 }
2752 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002753}
2754
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002757void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002758 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002759 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002760 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002761 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002762 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2763 CDecl = CDecl->getNextClassCategory())
2764 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2765 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002766
Chris Lattnereb44eee2007-12-23 01:40:15 +00002767 std::string FullCategoryName = ClassDecl->getName();
2768 FullCategoryName += '_';
2769 FullCategoryName += IDecl->getName();
2770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002771 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002772 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002773 true, "CATEGORY_", FullCategoryName.c_str(),
2774 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002775
2776 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002777 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002778 false, "CATEGORY_", FullCategoryName.c_str(),
2779 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002780
2781 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002782 // Null CDecl is case of a category implementation with no category interface
2783 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002784 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002785 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786
2787 /* struct _objc_category {
2788 char *category_name;
2789 char *class_name;
2790 struct _objc_method_list *instance_methods;
2791 struct _objc_method_list *class_methods;
2792 struct _objc_protocol_list *protocols;
2793 // Objective-C 1.0 extensions
2794 uint32_t size; // sizeof (struct _objc_category)
2795 struct _objc_property_list *instance_properties; // category's own
2796 // @property decl.
2797 };
2798 */
2799
2800 static bool objc_category = false;
2801 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002802 Result += "\nstruct _objc_category {\n";
2803 Result += "\tchar *category_name;\n";
2804 Result += "\tchar *class_name;\n";
2805 Result += "\tstruct _objc_method_list *instance_methods;\n";
2806 Result += "\tstruct _objc_method_list *class_methods;\n";
2807 Result += "\tstruct _objc_protocol_list *protocols;\n";
2808 Result += "\tunsigned int size;\n";
2809 Result += "\tstruct _objc_property_list *instance_properties;\n";
2810 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002812 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002813 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2814 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002815 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002816 Result += IDecl->getName();
2817 Result += "\"\n\t, \"";
2818 Result += ClassDecl->getName();
2819 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002820
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002821 if (IDecl->getNumInstanceMethods() > 0) {
2822 Result += "\t, (struct _objc_method_list *)"
2823 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2824 Result += FullCategoryName;
2825 Result += "\n";
2826 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002827 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 Result += "\t, 0\n";
2829 if (IDecl->getNumClassMethods() > 0) {
2830 Result += "\t, (struct _objc_method_list *)"
2831 "&_OBJC_CATEGORY_CLASS_METHODS_";
2832 Result += FullCategoryName;
2833 Result += "\n";
2834 }
2835 else
2836 Result += "\t, 0\n";
2837
Chris Lattner780f3292008-07-21 21:32:27 +00002838 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2840 Result += FullCategoryName;
2841 Result += "\n";
2842 }
2843 else
2844 Result += "\t, 0\n";
2845 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002846}
2847
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002848/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2849/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002850void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002852 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002853 if (ivar->isBitField()) {
2854 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2855 // place all bitfields at offset 0.
2856 Result += "0";
2857 } else {
2858 Result += "__OFFSETOFIVAR__(struct ";
2859 Result += IDecl->getName();
2860 if (LangOpts.Microsoft)
2861 Result += "_IMPL";
2862 Result += ", ";
2863 Result += ivar->getName();
2864 Result += ")";
2865 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002866}
2867
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002868//===----------------------------------------------------------------------===//
2869// Meta Data Emission
2870//===----------------------------------------------------------------------===//
2871
Steve Naroffb29b4272008-04-14 22:03:09 +00002872void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002873 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002874 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002875
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002876 // Explictly declared @interface's are already synthesized.
2877 if (CDecl->ImplicitInterfaceDecl()) {
2878 // FIXME: Implementation of a class with no @interface (legacy) doese not
2879 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002880 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002881 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002882
Chris Lattnerbe6df082007-12-12 07:56:42 +00002883 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002884 unsigned NumIvars = !IDecl->ivar_empty()
2885 ? IDecl->ivar_size()
2886 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002887 if (NumIvars > 0) {
2888 static bool objc_ivar = false;
2889 if (!objc_ivar) {
2890 /* struct _objc_ivar {
2891 char *ivar_name;
2892 char *ivar_type;
2893 int ivar_offset;
2894 };
2895 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002896 Result += "\nstruct _objc_ivar {\n";
2897 Result += "\tchar *ivar_name;\n";
2898 Result += "\tchar *ivar_type;\n";
2899 Result += "\tint ivar_offset;\n";
2900 Result += "};\n";
2901
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002902 objc_ivar = true;
2903 }
2904
Steve Naroff946a6932008-03-11 00:12:29 +00002905 /* struct {
2906 int ivar_count;
2907 struct _objc_ivar ivar_list[nIvars];
2908 };
2909 */
2910 Result += "\nstatic struct {\n";
2911 Result += "\tint ivar_count;\n";
2912 Result += "\tstruct _objc_ivar ivar_list[";
2913 Result += utostr(NumIvars);
2914 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002915 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002916 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002917 "{\n\t";
2918 Result += utostr(NumIvars);
2919 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002920
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002921 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002922 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002923 IVI = IDecl->ivar_begin();
2924 IVE = IDecl->ivar_end();
2925 } else {
2926 IVI = CDecl->ivar_begin();
2927 IVE = CDecl->ivar_end();
2928 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002929 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002930 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002931 Result += "\", \"";
2932 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002933 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2934 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002935 Result += StrEncoding;
2936 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002937 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002938 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002939 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002941 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002942 Result += "\", \"";
2943 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002944 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2945 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002946 Result += StrEncoding;
2947 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002948 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002949 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002950 }
2951
2952 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002953 }
2954
2955 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002956 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002957 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002958
2959 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002960 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002961 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002962
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002963 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002964 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002965 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002966
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002967
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002968 // Declaration of class/meta-class metadata
2969 /* struct _objc_class {
2970 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002971 const char *super_class_name;
2972 char *name;
2973 long version;
2974 long info;
2975 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002976 struct _objc_ivar_list *ivars;
2977 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002978 struct objc_cache *cache;
2979 struct objc_protocol_list *protocols;
2980 const char *ivar_layout;
2981 struct _objc_class_ext *ext;
2982 };
2983 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002984 static bool objc_class = false;
2985 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002986 Result += "\nstruct _objc_class {\n";
2987 Result += "\tstruct _objc_class *isa;\n";
2988 Result += "\tconst char *super_class_name;\n";
2989 Result += "\tchar *name;\n";
2990 Result += "\tlong version;\n";
2991 Result += "\tlong info;\n";
2992 Result += "\tlong instance_size;\n";
2993 Result += "\tstruct _objc_ivar_list *ivars;\n";
2994 Result += "\tstruct _objc_method_list *methods;\n";
2995 Result += "\tstruct objc_cache *cache;\n";
2996 Result += "\tstruct _objc_protocol_list *protocols;\n";
2997 Result += "\tconst char *ivar_layout;\n";
2998 Result += "\tstruct _objc_class_ext *ext;\n";
2999 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003000 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003001 }
3002
3003 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003004 ObjCInterfaceDecl *RootClass = 0;
3005 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003006 while (SuperClass) {
3007 RootClass = SuperClass;
3008 SuperClass = SuperClass->getSuperClass();
3009 }
3010 SuperClass = CDecl->getSuperClass();
3011
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003012 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3013 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003014 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003015 "{\n\t(struct _objc_class *)\"";
3016 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3017 Result += "\"";
3018
3019 if (SuperClass) {
3020 Result += ", \"";
3021 Result += SuperClass->getName();
3022 Result += "\", \"";
3023 Result += CDecl->getName();
3024 Result += "\"";
3025 }
3026 else {
3027 Result += ", 0, \"";
3028 Result += CDecl->getName();
3029 Result += "\"";
3030 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003031 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003032 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003033 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003034 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003035 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003036 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003037 Result += "\n";
3038 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003039 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003040 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003041 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003042 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003043 Result += CDecl->getName();
3044 Result += ",0,0\n";
3045 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003046 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003047 Result += "\t,0,0,0,0\n";
3048 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003049
3050 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003051 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3052 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003053 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003054 "{\n\t&_OBJC_METACLASS_";
3055 Result += CDecl->getName();
3056 if (SuperClass) {
3057 Result += ", \"";
3058 Result += SuperClass->getName();
3059 Result += "\", \"";
3060 Result += CDecl->getName();
3061 Result += "\"";
3062 }
3063 else {
3064 Result += ", 0, \"";
3065 Result += CDecl->getName();
3066 Result += "\"";
3067 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003068 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003069 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003071 Result += ",0";
3072 else {
3073 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003074 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003075 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003076 if (LangOpts.Microsoft)
3077 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003078 Result += ")";
3079 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003081 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003082 Result += CDecl->getName();
3083 Result += "\n\t";
3084 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003085 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003086 Result += ",0";
3087 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003088 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003089 Result += CDecl->getName();
3090 Result += ", 0\n\t";
3091 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003092 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003093 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003094 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003095 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003096 Result += CDecl->getName();
3097 Result += ", 0,0\n";
3098 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003099 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003100 Result += ",0,0,0\n";
3101 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003102}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003103
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003104/// RewriteImplementations - This routine rewrites all method implementations
3105/// and emits meta-data.
3106
Steve Naroffb29b4272008-04-14 22:03:09 +00003107void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003108 int ClsDefCount = ClassImplementation.size();
3109 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003110
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003111 if (ClsDefCount == 0 && CatDefCount == 0)
3112 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003113 // Rewrite implemented methods
3114 for (int i = 0; i < ClsDefCount; i++)
3115 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003116
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003117 for (int i = 0; i < CatDefCount; i++)
3118 RewriteImplementationDecl(CategoryImplementation[i]);
3119
Steve Naroff5df5b762008-05-07 21:23:49 +00003120 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003121 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003122 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003123 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003124 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003125
3126 // For each implemented category, write out all its meta data.
3127 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003129
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003130 // Write objc_symtab metadata
3131 /*
3132 struct _objc_symtab
3133 {
3134 long sel_ref_cnt;
3135 SEL *refs;
3136 short cls_def_cnt;
3137 short cat_def_cnt;
3138 void *defs[cls_def_cnt + cat_def_cnt];
3139 };
3140 */
3141
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 Result += "\nstruct _objc_symtab {\n";
3143 Result += "\tlong sel_ref_cnt;\n";
3144 Result += "\tSEL *refs;\n";
3145 Result += "\tshort cls_def_cnt;\n";
3146 Result += "\tshort cat_def_cnt;\n";
3147 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3148 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003149
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003150 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003151 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003152 Result += "\t0, 0, " + utostr(ClsDefCount)
3153 + ", " + utostr(CatDefCount) + "\n";
3154 for (int i = 0; i < ClsDefCount; i++) {
3155 Result += "\t,&_OBJC_CLASS_";
3156 Result += ClassImplementation[i]->getName();
3157 Result += "\n";
3158 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003160 for (int i = 0; i < CatDefCount; i++) {
3161 Result += "\t,&_OBJC_CATEGORY_";
3162 Result += CategoryImplementation[i]->getClassInterface()->getName();
3163 Result += "_";
3164 Result += CategoryImplementation[i]->getName();
3165 Result += "\n";
3166 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003167
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003168 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003169
3170 // Write objc_module metadata
3171
3172 /*
3173 struct _objc_module {
3174 long version;
3175 long size;
3176 const char *name;
3177 struct _objc_symtab *symtab;
3178 }
3179 */
3180
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181 Result += "\nstruct _objc_module {\n";
3182 Result += "\tlong version;\n";
3183 Result += "\tlong size;\n";
3184 Result += "\tconst char *name;\n";
3185 Result += "\tstruct _objc_symtab *symtab;\n";
3186 Result += "};\n\n";
3187 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003188 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003189 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3190 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003191 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003192
3193 if (LangOpts.Microsoft) {
3194 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003195 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003196 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3197 Result += "&_OBJC_MODULES;\n";
3198 Result += "#pragma data_seg(pop)\n\n";
3199 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003200}
Chris Lattner311ff022007-10-16 22:36:42 +00003201
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003202
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003203
3204