blob: e50ba66761434ba64c3f3033ec06ef8d1bee6dae [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"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000026#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000027#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000028#include <fstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Steve Naroff0113c9d2008-01-28 21:34:52 +000032static llvm::cl::opt<bool>
33SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
34 llvm::cl::desc("Silence ObjC rewriting warnings"));
35
Chris Lattner77cd2a02007-10-11 00:43:27 +000036namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000037 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000038 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000039 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000040 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000041 unsigned RewriteFailedDiag;
42
Chris Lattner01c57482007-10-17 22:35:30 +000043 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000044 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000045 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000046 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000047 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000048 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000049
Ted Kremeneka526c5c2008-01-07 19:49:32 +000050 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
51 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
52 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000053 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
55 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000056 llvm::SmallVector<Stmt *, 32> Stmts;
57 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000058 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000059
Steve Naroffd82a9ab2008-03-15 00:55:56 +000060 unsigned NumObjCStringLiterals;
61
Steve Naroffebf2b562007-10-23 23:50:29 +000062 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000063 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064 FunctionDecl *MsgSendStretFunctionDecl;
65 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000066 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000067 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000068 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000069 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000070 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000071 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000072 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000073
Steve Naroffbeaf2992007-11-03 11:27:19 +000074 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000075 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000077
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000078 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000079 int BcLabelCount;
80
Steve Naroff874e2322007-11-15 10:28:18 +000081 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000082 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000083 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000084 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000086 // Needed for header files being rewritten
87 bool IsHeader;
88
Steve Naroffa7b402d2008-03-28 22:26:09 +000089 std::string InFileName;
90 std::string OutFileName;
91
Steve Naroffba92b2e2008-03-27 22:29:16 +000092 std::string Preamble;
93
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000094 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000095 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000096 void Initialize(ASTContext &context);
97
Chris Lattner8a12c272007-10-11 18:38:32 +000098
Chris Lattnerf04da132007-10-24 17:06:59 +000099 // Top Level Driver code.
100 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000101 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000102 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000103 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000104 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000105
106 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000107 // If replacement succeeded or warning disabled return with no warning.
108 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000109 return;
110
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000111 SourceRange Range = Old->getSourceRange();
112 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
113 0, 0, &Range, 1);
114 }
115
Steve Naroffba92b2e2008-03-27 22:29:16 +0000116 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
117 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000118 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000120 SilenceRewriteMacroWarning)
121 return;
122
123 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
124 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000125
Chris Lattneraadaf782008-01-31 19:51:04 +0000126 void RemoveText(SourceLocation Loc, unsigned StrLen) {
127 // If removal succeeded or warning disabled return with no warning.
128 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
129 return;
130
131 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
132 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000133
Chris Lattneraadaf782008-01-31 19:51:04 +0000134 void ReplaceText(SourceLocation Start, unsigned OrigLength,
135 const char *NewStr, unsigned NewLength) {
136 // If removal succeeded or warning disabled return with no warning.
137 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
138 SilenceRewriteMacroWarning)
139 return;
140
141 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
142 }
143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000145 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000146 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000147 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
149 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000150 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000151 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
152 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
153 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
154 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
155 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000156 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000157 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000159 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000161 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000162 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000163
Chris Lattnerf04da132007-10-24 17:06:59 +0000164 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000165 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000166 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000167 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000168 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000169 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000170 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000171 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000173 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
175 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
176 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000177 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
178 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000179 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
180 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000181 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000182 Stmt *RewriteBreakStmt(BreakStmt *S);
183 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000184 void SynthCountByEnumWithState(std::string &buf);
185
Steve Naroff09b266e2007-10-30 23:14:51 +0000186 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000187 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000188 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000189 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000190 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000191 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000192 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000193 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000194 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000195 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000196
Chris Lattnerf04da132007-10-24 17:06:59 +0000197 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000199 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000200
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000201 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000202 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000204 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
205 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000206 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000207 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000208 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000209 const char *ClassName,
210 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000212 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000213 int NumProtocols,
214 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000215 const char *ClassName,
216 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000218 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
220 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000221 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000222 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000223 };
224}
225
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000226static bool IsHeaderFile(const std::string &Filename) {
227 std::string::size_type DotPos = Filename.rfind('.');
228
229 if (DotPos == std::string::npos) {
230 // no file extension
231 return false;
232 }
233
234 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
235 // C header: .h
236 // C++ header: .hh or .H;
237 return Ext == "h" || Ext == "hh" || Ext == "H";
238}
239
Steve Naroffb29b4272008-04-14 22:03:09 +0000240RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000241 Diagnostic &D, const LangOptions &LOpts)
242 : Diags(D), LangOpts(LOpts) {
243 IsHeader = IsHeaderFile(inFile);
244 InFileName = inFile;
245 OutFileName = outFile;
246 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
247 "rewriting sub-expression within a macro (may not be correct)");
248}
249
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000250ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000251 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000252 Diagnostic &Diags,
253 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000254 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000255}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000256
Steve Naroffb29b4272008-04-14 22:03:09 +0000257void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000258 Context = &context;
259 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000260 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000261 MsgSendFunctionDecl = 0;
262 MsgSendSuperFunctionDecl = 0;
263 MsgSendStretFunctionDecl = 0;
264 MsgSendSuperStretFunctionDecl = 0;
265 MsgSendFpretFunctionDecl = 0;
266 GetClassFunctionDecl = 0;
267 GetMetaClassFunctionDecl = 0;
268 SelGetUidFunctionDecl = 0;
269 CFStringFunctionDecl = 0;
270 GetProtocolFunctionDecl = 0;
271 ConstantStringClassReference = 0;
272 NSStringRecord = 0;
273 CurMethodDecl = 0;
274 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000275 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000276 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000277 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000278 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000279
280 // Get the ID and start/end of the main file.
281 MainFileID = SM->getMainFileID();
282 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
283 MainFileStart = MainBuf->getBufferStart();
284 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000285
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000286 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000287
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000288 // declaring objc_selector outside the parameter list removes a silly
289 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000290 if (IsHeader)
291 Preamble = "#pragma once\n";
292 Preamble += "struct objc_selector; struct objc_class;\n";
293 Preamble += "#ifndef OBJC_SUPER\n";
294 Preamble += "struct objc_super { struct objc_object *object; ";
295 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000296 if (LangOpts.Microsoft) {
297 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
299 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000300 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000301 Preamble += "};\n";
302 Preamble += "#define OBJC_SUPER\n";
303 Preamble += "#endif\n";
304 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
305 Preamble += "typedef struct objc_object Protocol;\n";
306 Preamble += "#define _REWRITER_typedef_Protocol\n";
307 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000308 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000309 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
310 else
311 Preamble += "#define __OBJC_RW_EXTERN extern\n";
312 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000313 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000314 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000315 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000316 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000317 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000318 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000319 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000320 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000321 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000322 Preamble += "__OBJC_RW_EXTERN objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000323 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000324 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000325 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000326 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
327 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
328 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
329 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
330 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000331 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000332 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000333 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000334 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000335 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
336 Preamble += "struct __objcFastEnumerationState {\n\t";
337 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000338 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000339 Preamble += "unsigned long *mutationsPtr;\n\t";
340 Preamble += "unsigned long extra[5];\n};\n";
341 Preamble += "#define __FASTENUMERATIONSTATE\n";
342 Preamble += "#endif\n";
343 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
344 Preamble += "struct __NSConstantStringImpl {\n";
345 Preamble += " int *isa;\n";
346 Preamble += " int flags;\n";
347 Preamble += " char *str;\n";
348 Preamble += " long length;\n";
349 Preamble += "};\n";
350 Preamble += "extern int __CFConstantStringClassReference[];\n";
351 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
352 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000353 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000355}
356
357
Chris Lattnerf04da132007-10-24 17:06:59 +0000358//===----------------------------------------------------------------------===//
359// Top Level Driver Code
360//===----------------------------------------------------------------------===//
361
Steve Naroffb29b4272008-04-14 22:03:09 +0000362void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000363 // Two cases: either the decl could be in the main file, or it could be in a
364 // #included file. If the former, rewrite it now. If the later, check to see
365 // if we rewrote the #include/#import.
366 SourceLocation Loc = D->getLocation();
367 Loc = SM->getLogicalLoc(Loc);
368
369 // If this is for a builtin, ignore it.
370 if (Loc.isInvalid()) return;
371
Steve Naroffebf2b562007-10-23 23:50:29 +0000372 // Look for built-in declarations that we need to refer during the rewrite.
373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000374 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000375 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000376 // declared in <Foundation/NSString.h>
377 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
378 ConstantStringClassReference = FVD;
379 return;
380 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000381 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000382 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000383 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000384 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000385 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000386 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 } else if (ObjCForwardProtocolDecl *FP =
388 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000389 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000390 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000391 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000392 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000393 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000394}
395
Chris Lattnerf04da132007-10-24 17:06:59 +0000396/// HandleDeclInMainFile - This is called for each top-level decl defined in the
397/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000398void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000399 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
400 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000401 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000402
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000403 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000404 if (Stmt *Body = MD->getBody()) {
405 //Body->dump();
406 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000407 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000408 CurMethodDecl = 0;
409 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000410 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000411 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000412 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000413 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000414 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000416 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000417 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000418 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000419 if (VD->getInit())
420 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
421 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000422 // Nothing yet.
423}
424
Steve Naroffb29b4272008-04-14 22:03:09 +0000425RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000426 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000427
428 // Rewrite tabs if we care.
429 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000430
Steve Naroffa7b402d2008-03-28 22:26:09 +0000431 if (Diags.hasErrorOccurred())
432 return;
433
434 // Create the output file.
435
436 std::ostream *OutFile;
437 if (OutFileName == "-") {
438 OutFile = llvm::cout.stream();
439 } else if (!OutFileName.empty()) {
440 OutFile = new std::ofstream(OutFileName.c_str(),
441 std::ios_base::binary|std::ios_base::out);
442 } else if (InFileName == "-") {
443 OutFile = llvm::cout.stream();
444 } else {
445 llvm::sys::Path Path(InFileName);
446 Path.eraseSuffix();
447 Path.appendSuffix("cpp");
448 OutFile = new std::ofstream(Path.toString().c_str(),
449 std::ios_base::binary|std::ios_base::out);
450 }
451
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000452 RewriteInclude();
453
Steve Naroffba92b2e2008-03-27 22:29:16 +0000454 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
455 Preamble.c_str(), Preamble.size(), false);
456
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000457 // Rewrite Objective-c meta data*
458 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000459 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000460
Chris Lattnerf04da132007-10-24 17:06:59 +0000461 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
462 // we are done.
463 if (const RewriteBuffer *RewriteBuf =
464 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000465 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000466 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000467 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000468 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000469 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000470 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000471 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000472}
473
Chris Lattnerf04da132007-10-24 17:06:59 +0000474//===----------------------------------------------------------------------===//
475// Syntactic (non-AST) Rewriting Code
476//===----------------------------------------------------------------------===//
477
Steve Naroffb29b4272008-04-14 22:03:09 +0000478void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000479 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
480 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
481 const char *MainBufStart = MainBuf.first;
482 const char *MainBufEnd = MainBuf.second;
483 size_t ImportLen = strlen("import");
484 size_t IncludeLen = strlen("include");
485
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000486 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000487 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
488 if (*BufPtr == '#') {
489 if (++BufPtr == MainBufEnd)
490 return;
491 while (*BufPtr == ' ' || *BufPtr == '\t')
492 if (++BufPtr == MainBufEnd)
493 return;
494 if (!strncmp(BufPtr, "import", ImportLen)) {
495 // replace import with include
496 SourceLocation ImportLoc =
497 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000498 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000499 BufPtr += ImportLen;
500 }
501 }
502 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000503}
504
Steve Naroffb29b4272008-04-14 22:03:09 +0000505void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000506 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
507 const char *MainBufStart = MainBuf.first;
508 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000509
Chris Lattnerf04da132007-10-24 17:06:59 +0000510 // Loop over the whole file, looking for tabs.
511 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
512 if (*BufPtr != '\t')
513 continue;
514
515 // Okay, we found a tab. This tab will turn into at least one character,
516 // but it depends on which 'virtual column' it is in. Compute that now.
517 unsigned VCol = 0;
518 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
519 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
520 ++VCol;
521
522 // Okay, now that we know the virtual column, we know how many spaces to
523 // insert. We assume 8-character tab-stops.
524 unsigned Spaces = 8-(VCol & 7);
525
526 // Get the location of the tab.
527 SourceLocation TabLoc =
528 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
529
530 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000531 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000532 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000533}
534
535
Steve Naroffb29b4272008-04-14 22:03:09 +0000536void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000537 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000539
540 // Get the start location and compute the semi location.
541 SourceLocation startLoc = ClassDecl->getLocation();
542 const char *startBuf = SM->getCharacterData(startLoc);
543 const char *semiPtr = strchr(startBuf, ';');
544
545 // Translate to typedef's that forward reference structs with the same name
546 // as the class. As a convenience, we include the original declaration
547 // as a comment.
548 std::string typedefString;
549 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000550 typedefString.append(startBuf, semiPtr-startBuf+1);
551 typedefString += "\n";
552 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000554 typedefString += "#ifndef _REWRITER_typedef_";
555 typedefString += ForwardDecl->getName();
556 typedefString += "\n";
557 typedefString += "#define _REWRITER_typedef_";
558 typedefString += ForwardDecl->getName();
559 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000560 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000561 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000562 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000563 }
564
565 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000566 ReplaceText(startLoc, semiPtr-startBuf+1,
567 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000568}
569
Steve Naroffb29b4272008-04-14 22:03:09 +0000570void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000571 SourceLocation LocStart = Method->getLocStart();
572 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000573
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000574 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000575 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000576 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000577 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000578 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000579 }
580}
581
Steve Naroffb29b4272008-04-14 22:03:09 +0000582void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000583{
Chris Lattner55d13b42008-03-16 21:23:50 +0000584 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000586 SourceLocation Loc = Property->getLocation();
587
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000589
590 // FIXME: handle properties that are declared across multiple lines.
591 }
592}
593
Steve Naroffb29b4272008-04-14 22:03:09 +0000594void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000595 SourceLocation LocStart = CatDecl->getLocStart();
596
597 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000598 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000599
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000600 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000601 E = CatDecl->instmeth_end(); I != E; ++I)
602 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000603 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000604 E = CatDecl->classmeth_end(); I != E; ++I)
605 RewriteMethodDeclaration(*I);
606
Steve Naroff423cb562007-10-30 13:30:57 +0000607 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000608 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000609}
610
Steve Naroffb29b4272008-04-14 22:03:09 +0000611void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000612 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000613
Steve Naroff752d6ef2007-10-30 16:42:30 +0000614 SourceLocation LocStart = PDecl->getLocStart();
615
616 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000617 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000618
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000619 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000620 E = PDecl->instmeth_end(); I != E; ++I)
621 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000622 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000623 E = PDecl->classmeth_end(); I != E; ++I)
624 RewriteMethodDeclaration(*I);
625
Steve Naroff752d6ef2007-10-30 16:42:30 +0000626 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000627 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000628 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000629
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000630 // Must comment out @optional/@required
631 const char *startBuf = SM->getCharacterData(LocStart);
632 const char *endBuf = SM->getCharacterData(LocEnd);
633 for (const char *p = startBuf; p < endBuf; p++) {
634 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
635 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000636 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000637 ReplaceText(OptionalLoc, strlen("@optional"),
638 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000639
640 }
641 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
642 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000643 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000644 ReplaceText(OptionalLoc, strlen("@required"),
645 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000646
647 }
648 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000649}
650
Steve Naroffb29b4272008-04-14 22:03:09 +0000651void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000652 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000653 if (LocStart.isInvalid())
654 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000655 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000656 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000657}
658
Steve Naroffb29b4272008-04-14 22:03:09 +0000659void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000660 std::string &ResultStr) {
661 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000663 ResultStr += "id";
664 else
665 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000666 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000667
668 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000669 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000671 if (OMD->isInstance())
672 NameStr += "_I_";
673 else
674 NameStr += "_C_";
675
676 NameStr += OMD->getClassInterface()->getName();
677 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000678
679 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 if (ObjCCategoryImplDecl *CID =
681 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000682 NameStr += CID->getName();
683 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000684 }
Steve Naroff563b8282008-04-04 22:23:44 +0000685 // Append selector names, replacing ':' with '_'
686 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000687 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000688 else {
689 std::string selString = OMD->getSelector().getName();
690 int len = selString.size();
691 for (int i = 0; i < len; i++)
692 if (selString[i] == ':')
693 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000694 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000695 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000696 // Remember this name for metadata emission
697 MethodInternalNames[OMD] = NameStr;
698 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000699
700 // Rewrite arguments
701 ResultStr += "(";
702
703 // invisible arguments
704 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000705 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000706 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000707 if (!LangOpts.Microsoft) {
708 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
709 ResultStr += "struct ";
710 }
711 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000712 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000713 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714 }
715 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717
718 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000719 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000720 ResultStr += " _cmd";
721
722 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000723 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000724 ParmVarDecl *PDecl = OMD->getParamDecl(i);
725 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000726 if (PDecl->getType()->isObjCQualifiedIdType()) {
727 ResultStr += "id ";
728 ResultStr += PDecl->getName();
729 } else {
730 std::string Name = PDecl->getName();
731 PDecl->getType().getAsStringInternal(Name);
732 ResultStr += Name;
733 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000735 if (OMD->isVariadic())
736 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000737 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738
739}
Steve Naroffb29b4272008-04-14 22:03:09 +0000740void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000741 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
742 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000743
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000744 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000745 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000746 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000747 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000748
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000749 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000750 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
751 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 ObjCMethodDecl *OMD = *I;
754 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 SourceLocation LocStart = OMD->getLocStart();
756 SourceLocation LocEnd = OMD->getBody()->getLocStart();
757
758 const char *startBuf = SM->getCharacterData(LocStart);
759 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(LocStart, endBuf-startBuf,
761 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762 }
763
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000764 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000765 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
766 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000767 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 ObjCMethodDecl *OMD = *I;
769 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 SourceLocation LocStart = OMD->getLocStart();
771 SourceLocation LocEnd = OMD->getBody()->getLocStart();
772
773 const char *startBuf = SM->getCharacterData(LocStart);
774 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000775 ReplaceText(LocStart, endBuf-startBuf,
776 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000777 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000778 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000779 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000780 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000781 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000782}
783
Steve Naroffb29b4272008-04-14 22:03:09 +0000784void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000785 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000786 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000787 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000788 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000789 ResultStr += ClassDecl->getName();
790 ResultStr += "\n";
791 ResultStr += "#define _REWRITER_typedef_";
792 ResultStr += ClassDecl->getName();
793 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000794 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000795 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000796 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000797 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000798 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000799 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000801
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000802 RewriteProperties(ClassDecl->getNumPropertyDecl(),
803 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000805 E = ClassDecl->instmeth_end(); I != E; ++I)
806 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000807 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000808 E = ClassDecl->classmeth_end(); I != E; ++I)
809 RewriteMethodDeclaration(*I);
810
Steve Naroff2feac5e2007-10-30 03:43:13 +0000811 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000812 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000813}
814
Steve Naroffb29b4272008-04-14 22:03:09 +0000815Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000817 if (CurMethodDecl) {
818 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
819 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
820 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000821 // lookup which class implements the instance variable.
822 ObjCInterfaceDecl *clsDeclared = 0;
823 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
824 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000825
826 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000827 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000828 RecName += "_IMPL";
829 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000830 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000831 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000832 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
833 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
834 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
835 // Don't forget the parens to enforce the proper binding.
836 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
837 if (IV->isFreeIvar()) {
838 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
839 ReplaceStmt(IV, ME);
840 delete IV;
841 return ME;
842 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000843 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000844 // Cannot delete IV->getBase(), since PE points to it.
845 // Replace the old base with the cast. This is important when doing
846 // embedded rewrites. For example, [newInv->_container addObject:0].
847 IV->setBase(PE);
848 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000849 }
850 }
851 }
Steve Naroff84472a82008-04-18 21:55:08 +0000852 } else { // we are outside a method.
853 if (IV->isFreeIvar())
854 assert(1 && "Cannot have a free standing ivar outside a method");
855 // Explicit ivar refs do not need to be rewritten. Do nothing.
Steve Naroffc2a689b2007-11-15 11:33:00 +0000856 }
Steve Naroff84472a82008-04-18 21:55:08 +0000857 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000858}
859
Chris Lattnerf04da132007-10-24 17:06:59 +0000860//===----------------------------------------------------------------------===//
861// Function Body / Expression rewriting
862//===----------------------------------------------------------------------===//
863
Steve Naroffb29b4272008-04-14 22:03:09 +0000864Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000865 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
866 isa<DoStmt>(S) || isa<ForStmt>(S))
867 Stmts.push_back(S);
868 else if (isa<ObjCForCollectionStmt>(S)) {
869 Stmts.push_back(S);
870 ObjCBcLabelNo.push_back(++BcLabelCount);
871 }
872
Chris Lattner338d1e22008-01-31 05:10:40 +0000873 SourceLocation OrigStmtEnd = S->getLocEnd();
874
875 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000876 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
877 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000878 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000879 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000880 if (newStmt)
881 *CI = newStmt;
882 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000883
884 // Handle specific things.
885 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
886 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000887
888 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
889 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000890
891 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
892 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000893
Steve Naroffbeaf2992007-11-03 11:27:19 +0000894 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
895 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000896
Steve Naroff934f2762007-10-24 22:48:43 +0000897 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
898 // Before we rewrite it, put the original message expression in a comment.
899 SourceLocation startLoc = MessExpr->getLocStart();
900 SourceLocation endLoc = MessExpr->getLocEnd();
901
902 const char *startBuf = SM->getCharacterData(startLoc);
903 const char *endBuf = SM->getCharacterData(endLoc);
904
905 std::string messString;
906 messString += "// ";
907 messString.append(startBuf, endBuf-startBuf+1);
908 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000909
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000910 // FIXME: Missing definition of
911 // InsertText(clang::SourceLocation, char const*, unsigned int).
912 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000913 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000914 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000915 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000916 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000917
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000918 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
919 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000920
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000921 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
922 return RewriteObjCSynchronizedStmt(StmtTry);
923
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
925 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000926
927 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
928 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000929
930 if (ObjCForCollectionStmt *StmtForCollection =
931 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000932 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000933 if (BreakStmt *StmtBreakStmt =
934 dyn_cast<BreakStmt>(S))
935 return RewriteBreakStmt(StmtBreakStmt);
936 if (ContinueStmt *StmtContinueStmt =
937 dyn_cast<ContinueStmt>(S))
938 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000939
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000940 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
941 isa<DoStmt>(S) || isa<ForStmt>(S)) {
942 assert(!Stmts.empty() && "Statement stack is empty");
943 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
944 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
945 && "Statement stack mismatch");
946 Stmts.pop_back();
947 }
Steve Naroff874e2322007-11-15 10:28:18 +0000948#if 0
949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
950 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
951 // Get the new text.
952 std::ostringstream Buf;
953 Replacement->printPretty(Buf);
954 const std::string &Str = Buf.str();
955
956 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000957 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000958 delete S;
959 return Replacement;
960 }
961#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000962 // Return this stmt unmodified.
963 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000964}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000965
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000966/// SynthCountByEnumWithState - To print:
967/// ((unsigned int (*)
968/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
969/// (void *)objc_msgSend)((id)l_collection,
970/// sel_registerName(
971/// "countByEnumeratingWithState:objects:count:"),
972/// &enumState,
973/// (id *)items, (unsigned int)16)
974///
Steve Naroffb29b4272008-04-14 22:03:09 +0000975void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000976 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
977 "id *, unsigned int))(void *)objc_msgSend)";
978 buf += "\n\t\t";
979 buf += "((id)l_collection,\n\t\t";
980 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
981 buf += "\n\t\t";
982 buf += "&enumState, "
983 "(id *)items, (unsigned int)16)";
984}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000985
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000986/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
987/// statement to exit to its outer synthesized loop.
988///
Steve Naroffb29b4272008-04-14 22:03:09 +0000989Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000990 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
991 return S;
992 // replace break with goto __break_label
993 std::string buf;
994
995 SourceLocation startLoc = S->getLocStart();
996 buf = "goto __break_label_";
997 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000998 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000999
1000 return 0;
1001}
1002
1003/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1004/// statement to continue with its inner synthesized loop.
1005///
Steve Naroffb29b4272008-04-14 22:03:09 +00001006Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001007 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1008 return S;
1009 // replace continue with goto __continue_label
1010 std::string buf;
1011
1012 SourceLocation startLoc = S->getLocStart();
1013 buf = "goto __continue_label_";
1014 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001015 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001016
1017 return 0;
1018}
1019
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001020/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001021/// It rewrites:
1022/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001023
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001024/// Into:
1025/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001026/// type elem;
1027/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001028/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001029/// id l_collection = (id)collection;
1030/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1031/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001032/// if (limit) {
1033/// unsigned long startMutations = *enumState.mutationsPtr;
1034/// do {
1035/// unsigned long counter = 0;
1036/// do {
1037/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001038/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001039/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001040/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001041/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001042/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001043/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1044/// objects:items count:16]);
1045/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001046/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001047/// }
1048/// else
1049/// elem = nil;
1050/// }
1051///
Steve Naroffb29b4272008-04-14 22:03:09 +00001052Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001053 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001054 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1055 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1056 "ObjCForCollectionStmt Statement stack mismatch");
1057 assert(!ObjCBcLabelNo.empty() &&
1058 "ObjCForCollectionStmt - Label No stack empty");
1059
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001060 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001061 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001062 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001063 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001064 std::string buf;
1065 buf = "\n{\n\t";
1066 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1067 // type elem;
1068 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001069 elementTypeAsString = ElementType.getAsString();
1070 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001071 buf += " ";
1072 elementName = DS->getDecl()->getName();
1073 buf += elementName;
1074 buf += ";\n\t";
1075 }
Chris Lattner06767512008-04-08 05:52:18 +00001076 else {
1077 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001078 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001079 elementTypeAsString = DR->getDecl()->getType().getAsString();
1080 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001081
1082 // struct __objcFastEnumerationState enumState = { 0 };
1083 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1084 // id items[16];
1085 buf += "id items[16];\n\t";
1086 // id l_collection = (id)
1087 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001088 // Find start location of 'collection' the hard way!
1089 const char *startCollectionBuf = startBuf;
1090 startCollectionBuf += 3; // skip 'for'
1091 startCollectionBuf = strchr(startCollectionBuf, '(');
1092 startCollectionBuf++; // skip '('
1093 // find 'in' and skip it.
1094 while (*startCollectionBuf != ' ' ||
1095 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1096 (*(startCollectionBuf+3) != ' ' &&
1097 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1098 startCollectionBuf++;
1099 startCollectionBuf += 3;
1100
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001102 ReplaceText(startLoc, startCollectionBuf - startBuf,
1103 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001104 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001105 SourceLocation rightParenLoc = S->getRParenLoc();
1106 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1107 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001108 buf = ";\n\t";
1109
1110 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1111 // objects:items count:16];
1112 // which is synthesized into:
1113 // unsigned int limit =
1114 // ((unsigned int (*)
1115 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1116 // (void *)objc_msgSend)((id)l_collection,
1117 // sel_registerName(
1118 // "countByEnumeratingWithState:objects:count:"),
1119 // (struct __objcFastEnumerationState *)&state,
1120 // (id *)items, (unsigned int)16);
1121 buf += "unsigned long limit =\n\t\t";
1122 SynthCountByEnumWithState(buf);
1123 buf += ";\n\t";
1124 /// if (limit) {
1125 /// unsigned long startMutations = *enumState.mutationsPtr;
1126 /// do {
1127 /// unsigned long counter = 0;
1128 /// do {
1129 /// if (startMutations != *enumState.mutationsPtr)
1130 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001131 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001132 buf += "if (limit) {\n\t";
1133 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1134 buf += "do {\n\t\t";
1135 buf += "unsigned long counter = 0;\n\t\t";
1136 buf += "do {\n\t\t\t";
1137 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1138 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1139 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001140 buf += " = (";
1141 buf += elementTypeAsString;
1142 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001143 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001144 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001145
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001146 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001147 /// } while (counter < limit);
1148 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1149 /// objects:items count:16]);
1150 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001151 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001152 /// }
1153 /// else
1154 /// elem = nil;
1155 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001156 ///
1157 buf = ";\n\t";
1158 buf += "__continue_label_";
1159 buf += utostr(ObjCBcLabelNo.back());
1160 buf += ": ;";
1161 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 buf += "} while (counter < limit);\n\t";
1163 buf += "} while (limit = ";
1164 SynthCountByEnumWithState(buf);
1165 buf += ");\n\t";
1166 buf += elementName;
1167 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001168 buf += "__break_label_";
1169 buf += utostr(ObjCBcLabelNo.back());
1170 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001171 buf += "}\n\t";
1172 buf += "else\n\t\t";
1173 buf += elementName;
1174 buf += " = nil;\n";
1175 buf += "}\n";
1176 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001177 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001178 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001179 Stmts.pop_back();
1180 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001181 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001182}
1183
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001184/// RewriteObjCSynchronizedStmt -
1185/// This routine rewrites @synchronized(expr) stmt;
1186/// into:
1187/// objc_sync_enter(expr);
1188/// @try stmt @finally { objc_sync_exit(expr); }
1189///
Steve Naroffb29b4272008-04-14 22:03:09 +00001190Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001191 // Get the start location and compute the semi location.
1192 SourceLocation startLoc = S->getLocStart();
1193 const char *startBuf = SM->getCharacterData(startLoc);
1194
1195 assert((*startBuf == '@') && "bogus @synchronized location");
1196
1197 std::string buf;
1198 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001199 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001200 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1201 const char *endBuf = SM->getCharacterData(endLoc);
1202 endBuf++;
1203 const char *rparenBuf = strchr(endBuf, ')');
1204 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1205 buf = ");\n";
1206 // declare a new scope with two variables, _stack and _rethrow.
1207 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1208 buf += "int buf[18/*32-bit i386*/];\n";
1209 buf += "char *pointers[4];} _stack;\n";
1210 buf += "id volatile _rethrow = 0;\n";
1211 buf += "objc_exception_try_enter(&_stack);\n";
1212 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001213 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001214 startLoc = S->getSynchBody()->getLocEnd();
1215 startBuf = SM->getCharacterData(startLoc);
1216
1217 assert((*startBuf == '}') && "bogus @try block");
1218 SourceLocation lastCurlyLoc = startLoc;
1219 buf = "}\nelse {\n";
1220 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1221 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1222 // FIXME: This must be objc_sync_exit(syncExpr);
1223 buf += " objc_sync_exit();\n";
1224 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1225 buf += "}\n";
1226 buf += "}";
1227
Chris Lattneraadaf782008-01-31 19:51:04 +00001228 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001229 return 0;
1230}
1231
Steve Naroffb29b4272008-04-14 22:03:09 +00001232Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001233 // Get the start location and compute the semi location.
1234 SourceLocation startLoc = S->getLocStart();
1235 const char *startBuf = SM->getCharacterData(startLoc);
1236
1237 assert((*startBuf == '@') && "bogus @try location");
1238
1239 std::string buf;
1240 // declare a new scope with two variables, _stack and _rethrow.
1241 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1242 buf += "int buf[18/*32-bit i386*/];\n";
1243 buf += "char *pointers[4];} _stack;\n";
1244 buf += "id volatile _rethrow = 0;\n";
1245 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001246 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001247
Chris Lattneraadaf782008-01-31 19:51:04 +00001248 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001249
1250 startLoc = S->getTryBody()->getLocEnd();
1251 startBuf = SM->getCharacterData(startLoc);
1252
1253 assert((*startBuf == '}') && "bogus @try block");
1254
1255 SourceLocation lastCurlyLoc = startLoc;
1256
1257 startLoc = startLoc.getFileLocWithOffset(1);
1258 buf = " /* @catch begin */ else {\n";
1259 buf += " id _caught = objc_exception_extract(&_stack);\n";
1260 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001261 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001262 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1263 buf += " else { /* @catch continue */";
1264
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001265 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001266
1267 bool sawIdTypedCatch = false;
1268 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001269 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001270 while (catchList) {
1271 Stmt *catchStmt = catchList->getCatchParamStmt();
1272
1273 if (catchList == S->getCatchStmts())
1274 buf = "if ("; // we are generating code for the first catch clause
1275 else
1276 buf = "else if (";
1277 startLoc = catchList->getLocStart();
1278 startBuf = SM->getCharacterData(startLoc);
1279
1280 assert((*startBuf == '@') && "bogus @catch location");
1281
1282 const char *lParenLoc = strchr(startBuf, '(');
1283
Steve Naroffbe4b3332008-02-01 22:08:12 +00001284 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001285 // Now rewrite the body...
1286 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001287 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1288 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001289 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1290 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001291 assert((*bodyBuf == '{') && "bogus @catch body location");
1292
1293 buf += "1) { id _tmp = _caught;";
1294 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1295 buf.c_str(), buf.size());
1296 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001297 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001298 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001299 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001300 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001301 sawIdTypedCatch = true;
1302 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001303 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001304
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001305 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001306 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001307 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001308 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001309 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001310 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001311 }
1312 }
1313 // Now rewrite the body...
1314 lastCatchBody = catchList->getCatchBody();
1315 SourceLocation rParenLoc = catchList->getRParenLoc();
1316 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1317 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1318 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1319 assert((*rParenBuf == ')') && "bogus @catch paren location");
1320 assert((*bodyBuf == '{') && "bogus @catch body location");
1321
1322 buf = " = _caught;";
1323 // Here we replace ") {" with "= _caught;" (which initializes and
1324 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001325 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001326 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001327 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001328 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001329 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001330 catchList = catchList->getNextCatchStmt();
1331 }
1332 // Complete the catch list...
1333 if (lastCatchBody) {
1334 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001335 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1336 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001337 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1338 buf = " } } /* @catch end */\n";
1339
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001340 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001341
1342 // Set lastCurlyLoc
1343 lastCurlyLoc = lastCatchBody->getLocEnd();
1344 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001345 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001346 startLoc = finalStmt->getLocStart();
1347 startBuf = SM->getCharacterData(startLoc);
1348 assert((*startBuf == '@') && "bogus @finally start");
1349
1350 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001351 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001352
1353 Stmt *body = finalStmt->getFinallyBody();
1354 SourceLocation startLoc = body->getLocStart();
1355 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001356 assert(*SM->getCharacterData(startLoc) == '{' &&
1357 "bogus @finally body location");
1358 assert(*SM->getCharacterData(endLoc) == '}' &&
1359 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001360
1361 startLoc = startLoc.getFileLocWithOffset(1);
1362 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001363 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001364 endLoc = endLoc.getFileLocWithOffset(-1);
1365 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001366 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001367
1368 // Set lastCurlyLoc
1369 lastCurlyLoc = body->getLocEnd();
1370 }
1371 // Now emit the final closing curly brace...
1372 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1373 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001374 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001375 return 0;
1376}
1377
Steve Naroffb29b4272008-04-14 22:03:09 +00001378Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001379 return 0;
1380}
1381
Steve Naroffb29b4272008-04-14 22:03:09 +00001382Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001383 return 0;
1384}
1385
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001386// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001387// the throw expression is typically a message expression that's already
1388// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001389Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001390 // Get the start location and compute the semi location.
1391 SourceLocation startLoc = S->getLocStart();
1392 const char *startBuf = SM->getCharacterData(startLoc);
1393
1394 assert((*startBuf == '@') && "bogus @throw location");
1395
1396 std::string buf;
1397 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001398 if (S->getThrowExpr())
1399 buf = "objc_exception_throw(";
1400 else // add an implicit argument
1401 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001402 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001403 const char *semiBuf = strchr(startBuf, ';');
1404 assert((*semiBuf == ';') && "@throw: can't find ';'");
1405 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1406 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001407 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001408 return 0;
1409}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001410
Steve Naroffb29b4272008-04-14 22:03:09 +00001411Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001412 // Create a new string expression.
1413 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001414 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001415 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1416 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001417 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1418 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001419 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001420 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001421
Chris Lattner07506182007-11-30 22:53:43 +00001422 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001423 delete Exp;
1424 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001425}
1426
Steve Naroffb29b4272008-04-14 22:03:09 +00001427Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001428 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1429 // Create a call to sel_registerName("selName").
1430 llvm::SmallVector<Expr*, 8> SelExprs;
1431 QualType argType = Context->getPointerType(Context->CharTy);
1432 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1433 Exp->getSelector().getName().size(),
1434 false, argType, SourceLocation(),
1435 SourceLocation()));
1436 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1437 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001438 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001439 delete Exp;
1440 return SelExp;
1441}
1442
Steve Naroffb29b4272008-04-14 22:03:09 +00001443CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001444 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001445 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001446 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001447
1448 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001449 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001450
1451 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001452 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001453 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1454
1455 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001456
Steve Naroff934f2762007-10-24 22:48:43 +00001457 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1458}
1459
Steve Naroffd5255f52007-11-01 13:24:47 +00001460static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1461 const char *&startRef, const char *&endRef) {
1462 while (startBuf < endBuf) {
1463 if (*startBuf == '<')
1464 startRef = startBuf; // mark the start.
1465 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001466 if (startRef && *startRef == '<') {
1467 endRef = startBuf; // mark the end.
1468 return true;
1469 }
1470 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001471 }
1472 startBuf++;
1473 }
1474 return false;
1475}
1476
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001477static void scanToNextArgument(const char *&argRef) {
1478 int angle = 0;
1479 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1480 if (*argRef == '<')
1481 angle++;
1482 else if (*argRef == '>')
1483 angle--;
1484 argRef++;
1485 }
1486 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1487}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001488
Steve Naroffb29b4272008-04-14 22:03:09 +00001489bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001490
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001491 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001492 return true;
1493
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001494 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001495 return true;
1496
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001498 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001499 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001500 return true; // we have "Class <Protocol> *".
1501 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001502 return false;
1503}
1504
Steve Naroffb29b4272008-04-14 22:03:09 +00001505void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001506 SourceLocation Loc;
1507 QualType Type;
1508 const FunctionTypeProto *proto = 0;
1509 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1510 Loc = VD->getLocation();
1511 Type = VD->getType();
1512 }
1513 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1514 Loc = FD->getLocation();
1515 // Check for ObjC 'id' and class types that have been adorned with protocol
1516 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1517 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1518 assert(funcType && "missing function type");
1519 proto = dyn_cast<FunctionTypeProto>(funcType);
1520 if (!proto)
1521 return;
1522 Type = proto->getResultType();
1523 }
1524 else
1525 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001526
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001527 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001528 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001529
1530 const char *endBuf = SM->getCharacterData(Loc);
1531 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001532 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001533 startBuf--; // scan backward (from the decl location) for return type.
1534 const char *startRef = 0, *endRef = 0;
1535 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1536 // Get the locations of the startRef, endRef.
1537 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1538 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1539 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001540 InsertText(LessLoc, "/*", 2);
1541 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001542 }
1543 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001544 if (!proto)
1545 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001546 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001547 const char *startBuf = SM->getCharacterData(Loc);
1548 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001549 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1550 if (needToScanForQualifiers(proto->getArgType(i))) {
1551 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001552
Steve Naroffd5255f52007-11-01 13:24:47 +00001553 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001554 // scan forward (from the decl location) for argument types.
1555 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001556 const char *startRef = 0, *endRef = 0;
1557 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1558 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001559 SourceLocation LessLoc =
1560 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1561 SourceLocation GreaterLoc =
1562 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001563 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001564 InsertText(LessLoc, "/*", 2);
1565 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001566 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001567 startBuf = ++endBuf;
1568 }
1569 else {
1570 while (*startBuf != ')' && *startBuf != ',')
1571 startBuf++; // scan forward (from the decl location) for argument types.
1572 startBuf++;
1573 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001574 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001575}
1576
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001577// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001578void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001579 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1580 llvm::SmallVector<QualType, 16> ArgTys;
1581 ArgTys.push_back(Context->getPointerType(
1582 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001584 &ArgTys[0], ArgTys.size(),
1585 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001586 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001587 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001588 SelGetUidIdent, getFuncType,
1589 FunctionDecl::Extern, false, 0);
1590}
1591
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001592// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001593void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001594 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1595 llvm::SmallVector<QualType, 16> ArgTys;
1596 ArgTys.push_back(Context->getPointerType(
1597 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001598 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001599 &ArgTys[0], ArgTys.size(),
1600 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001601 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001602 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001603 SelGetProtoIdent, getFuncType,
1604 FunctionDecl::Extern, false, 0);
1605}
1606
Steve Naroffb29b4272008-04-14 22:03:09 +00001607void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001608 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001609 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001610 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001611 return;
1612 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001613 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001614}
1615
Steve Naroffc0a123c2008-03-11 17:37:02 +00001616// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001617void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001618 if (SuperContructorFunctionDecl)
1619 return;
1620 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1621 llvm::SmallVector<QualType, 16> ArgTys;
1622 QualType argT = Context->getObjCIdType();
1623 assert(!argT.isNull() && "Can't find 'id' type");
1624 ArgTys.push_back(argT);
1625 ArgTys.push_back(argT);
1626 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1627 &ArgTys[0], ArgTys.size(),
1628 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001629 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001630 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001631 msgSendIdent, msgSendType,
1632 FunctionDecl::Extern, false, 0);
1633}
1634
Steve Naroff09b266e2007-10-30 23:14:51 +00001635// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001636void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001637 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1638 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001640 assert(!argT.isNull() && "Can't find 'id' type");
1641 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001643 assert(!argT.isNull() && "Can't find 'SEL' type");
1644 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001645 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001646 &ArgTys[0], ArgTys.size(),
1647 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001648 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001649 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001650 msgSendIdent, msgSendType,
1651 FunctionDecl::Extern, false, 0);
1652}
1653
Steve Naroff874e2322007-11-15 10:28:18 +00001654// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001655void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001656 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1657 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001658 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001659 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001660 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001661 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1662 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1663 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001665 assert(!argT.isNull() && "Can't find 'SEL' type");
1666 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001667 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001668 &ArgTys[0], ArgTys.size(),
1669 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001670 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001671 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001672 msgSendIdent, msgSendType,
1673 FunctionDecl::Extern, false, 0);
1674}
1675
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001676// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001677void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001678 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1679 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001680 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001681 assert(!argT.isNull() && "Can't find 'id' type");
1682 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001683 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001684 assert(!argT.isNull() && "Can't find 'SEL' type");
1685 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001686 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001687 &ArgTys[0], ArgTys.size(),
1688 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001689 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001690 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001691 msgSendIdent, msgSendType,
1692 FunctionDecl::Extern, false, 0);
1693}
1694
1695// SynthMsgSendSuperStretFunctionDecl -
1696// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001697void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001698 IdentifierInfo *msgSendIdent =
1699 &Context->Idents.get("objc_msgSendSuper_stret");
1700 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001701 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001702 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001703 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001704 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1705 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1706 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001708 assert(!argT.isNull() && "Can't find 'SEL' type");
1709 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001710 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001711 &ArgTys[0], ArgTys.size(),
1712 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001713 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001714 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001715 msgSendIdent, msgSendType,
1716 FunctionDecl::Extern, false, 0);
1717}
1718
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001719// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001720void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001721 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1722 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001723 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001724 assert(!argT.isNull() && "Can't find 'id' type");
1725 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001726 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001727 assert(!argT.isNull() && "Can't find 'SEL' type");
1728 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001729 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001730 &ArgTys[0], ArgTys.size(),
1731 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001732 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001733 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001734 msgSendIdent, msgSendType,
1735 FunctionDecl::Extern, false, 0);
1736}
1737
Steve Naroff09b266e2007-10-30 23:14:51 +00001738// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001739void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001740 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1741 llvm::SmallVector<QualType, 16> ArgTys;
1742 ArgTys.push_back(Context->getPointerType(
1743 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001745 &ArgTys[0], ArgTys.size(),
1746 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001747 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001748 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001749 getClassIdent, getClassType,
1750 FunctionDecl::Extern, false, 0);
1751}
1752
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001753// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001754void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001755 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1756 llvm::SmallVector<QualType, 16> ArgTys;
1757 ArgTys.push_back(Context->getPointerType(
1758 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001759 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001760 &ArgTys[0], ArgTys.size(),
1761 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001762 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001763 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001764 getClassIdent, getClassType,
1765 FunctionDecl::Extern, false, 0);
1766}
1767
Steve Naroffb29b4272008-04-14 22:03:09 +00001768Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001769 QualType strType = getConstantStringStructType();
1770
1771 std::string S = "__NSConstantStringImpl_";
1772 S += utostr(NumObjCStringLiterals++);
1773
Steve Naroffba92b2e2008-03-27 22:29:16 +00001774 Preamble += "static __NSConstantStringImpl " + S;
1775 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1776 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001777 // The pretty printer for StringLiteral handles escape characters properly.
1778 std::ostringstream prettyBuf;
1779 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001780 Preamble += prettyBuf.str();
1781 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001782 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001783 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001784
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001785 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001786 &Context->Idents.get(S.c_str()), strType,
1787 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001788 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1789 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1790 Context->getPointerType(DRE->getType()),
1791 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001792 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001793 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001794 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001795 delete Exp;
1796 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001797}
1798
Steve Naroffb29b4272008-04-14 22:03:09 +00001799ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001800 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001801 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1802
1803 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1804 if (!CE) return 0;
1805
1806 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1807 if (!DRE) return 0;
1808
1809 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1810 if (!PVD) return 0;
1811
1812 if (strcmp(PVD->getName(), "self") != 0)
1813 return 0;
1814
1815 // is this id<P1..> type?
1816 if (CE->getType()->isObjCQualifiedIdType())
1817 return 0;
1818 const PointerType *PT = CE->getType()->getAsPointerType();
1819 if (!PT) return 0;
1820
1821 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1822 if (!IT) return 0;
1823
1824 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1825 return 0;
1826
1827 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001828}
1829
1830// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001831QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001832 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001833 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001834 SourceLocation(),
1835 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001836 QualType FieldTypes[2];
1837
1838 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001839 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001840 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001841 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001842 // Create fields
1843 FieldDecl *FieldDecls[2];
1844
1845 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001846 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001847 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001848
1849 SuperStructDecl->defineBody(FieldDecls, 4);
1850 }
1851 return Context->getTagDeclType(SuperStructDecl);
1852}
1853
Steve Naroffb29b4272008-04-14 22:03:09 +00001854QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001855 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001856 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001857 SourceLocation(),
1858 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001859 QualType FieldTypes[4];
1860
1861 // struct objc_object *receiver;
1862 FieldTypes[0] = Context->getObjCIdType();
1863 // int flags;
1864 FieldTypes[1] = Context->IntTy;
1865 // char *str;
1866 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1867 // long length;
1868 FieldTypes[3] = Context->LongTy;
1869 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001870 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001871
1872 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001873 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001874 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001875
1876 ConstantStringDecl->defineBody(FieldDecls, 4);
1877 }
1878 return Context->getTagDeclType(ConstantStringDecl);
1879}
1880
Steve Naroffb29b4272008-04-14 22:03:09 +00001881Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001882 if (!SelGetUidFunctionDecl)
1883 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001884 if (!MsgSendFunctionDecl)
1885 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001886 if (!MsgSendSuperFunctionDecl)
1887 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001888 if (!MsgSendStretFunctionDecl)
1889 SynthMsgSendStretFunctionDecl();
1890 if (!MsgSendSuperStretFunctionDecl)
1891 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001892 if (!MsgSendFpretFunctionDecl)
1893 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001894 if (!GetClassFunctionDecl)
1895 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001896 if (!GetMetaClassFunctionDecl)
1897 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001898
Steve Naroff874e2322007-11-15 10:28:18 +00001899 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001900 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1901 // May need to use objc_msgSend_stret() as well.
1902 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001903 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001904 QualType resultType = mDecl->getResultType();
1905 if (resultType.getCanonicalType()->isStructureType()
1906 || resultType.getCanonicalType()->isUnionType())
1907 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001908 else if (resultType.getCanonicalType()->isRealFloatingType())
1909 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001910 }
Steve Naroff874e2322007-11-15 10:28:18 +00001911
Steve Naroff934f2762007-10-24 22:48:43 +00001912 // Synthesize a call to objc_msgSend().
1913 llvm::SmallVector<Expr*, 8> MsgExprs;
1914 IdentifierInfo *clsName = Exp->getClassName();
1915
1916 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1917 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001918 if (!strcmp(clsName->getName(), "super")) {
1919 MsgSendFlavor = MsgSendSuperFunctionDecl;
1920 if (MsgSendStretFlavor)
1921 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1922 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1923
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001925 CurMethodDecl->getClassInterface()->getSuperClass();
1926
1927 llvm::SmallVector<Expr*, 4> InitExprs;
1928
1929 // set the receiver to self, the first argument to all methods.
1930 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001932 SourceLocation()));
1933 llvm::SmallVector<Expr*, 8> ClsExprs;
1934 QualType argType = Context->getPointerType(Context->CharTy);
1935 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1936 SuperDecl->getIdentifier()->getLength(),
1937 false, argType, SourceLocation(),
1938 SourceLocation()));
1939 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1940 &ClsExprs[0],
1941 ClsExprs.size());
1942 // To turn off a warning, type-cast to 'id'
1943 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001945 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1946 // struct objc_super
1947 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001948 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001949
Steve Naroff23f41272008-03-11 18:14:26 +00001950 if (LangOpts.Microsoft) {
1951 SynthSuperContructorFunctionDecl();
1952 // Simulate a contructor call...
1953 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1954 superType, SourceLocation());
1955 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1956 superType, SourceLocation());
1957 } else {
1958 // (struct objc_super) { <exprs from above> }
1959 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1960 &InitExprs[0], InitExprs.size(),
1961 SourceLocation());
1962 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1963 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001964 // struct objc_super *
1965 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1966 Context->getPointerType(SuperRep->getType()),
1967 SourceLocation());
1968 MsgExprs.push_back(Unop);
1969 } else {
1970 llvm::SmallVector<Expr*, 8> ClsExprs;
1971 QualType argType = Context->getPointerType(Context->CharTy);
1972 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1973 clsName->getLength(),
1974 false, argType, SourceLocation(),
1975 SourceLocation()));
1976 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1977 &ClsExprs[0],
1978 ClsExprs.size());
1979 MsgExprs.push_back(Cls);
1980 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001981 } else { // instance message.
1982 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001983
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001985 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001986 if (MsgSendStretFlavor)
1987 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001988 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1989
1990 llvm::SmallVector<Expr*, 4> InitExprs;
1991
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001992 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001994 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001995
1996 llvm::SmallVector<Expr*, 8> ClsExprs;
1997 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001998 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1999 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002000 false, argType, SourceLocation(),
2001 SourceLocation()));
2002 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002003 &ClsExprs[0],
2004 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002005 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002006 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002007 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002008 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002009 // struct objc_super
2010 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002011 Expr *SuperRep;
2012
2013 if (LangOpts.Microsoft) {
2014 SynthSuperContructorFunctionDecl();
2015 // Simulate a contructor call...
2016 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2017 superType, SourceLocation());
2018 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2019 superType, SourceLocation());
2020 } else {
2021 // (struct objc_super) { <exprs from above> }
2022 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2023 &InitExprs[0], InitExprs.size(),
2024 SourceLocation());
2025 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2026 }
Steve Naroff874e2322007-11-15 10:28:18 +00002027 // struct objc_super *
2028 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2029 Context->getPointerType(SuperRep->getType()),
2030 SourceLocation());
2031 MsgExprs.push_back(Unop);
2032 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002033 // Remove all type-casts because it may contain objc-style types; e.g.
2034 // Foo<Proto> *.
2035 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2036 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002037 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002038 MsgExprs.push_back(recExpr);
2039 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002040 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002041 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002042 llvm::SmallVector<Expr*, 8> SelExprs;
2043 QualType argType = Context->getPointerType(Context->CharTy);
2044 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2045 Exp->getSelector().getName().size(),
2046 false, argType, SourceLocation(),
2047 SourceLocation()));
2048 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2049 &SelExprs[0], SelExprs.size());
2050 MsgExprs.push_back(SelExp);
2051
2052 // Now push any user supplied arguments.
2053 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002054 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002055 // Make all implicit casts explicit...ICE comes in handy:-)
2056 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2057 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2059 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002060 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002061 }
2062 // Make id<P...> cast into an 'id' cast.
2063 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002065 while ((CE = dyn_cast<CastExpr>(userExpr)))
2066 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002068 userExpr, SourceLocation());
2069 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002070 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002071 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002072 // We've transferred the ownership to MsgExprs. Null out the argument in
2073 // the original expression, since we will delete it below.
2074 Exp->setArg(i, 0);
2075 }
Steve Naroffab972d32007-11-04 22:37:50 +00002076 // Generate the funky cast.
2077 CastExpr *cast;
2078 llvm::SmallVector<QualType, 8> ArgTypes;
2079 QualType returnType;
2080
2081 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002082 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2083 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2084 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002085 ArgTypes.push_back(Context->getObjCIdType());
2086 ArgTypes.push_back(Context->getObjCSelType());
2087 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002088 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002089 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002090 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2091 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002092 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002093 ArgTypes.push_back(t);
2094 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2096 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002097 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002099 }
2100 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002101 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002102
2103 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002104 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2105 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002106
2107 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2108 // If we don't do this cast, we get the following bizarre warning/note:
2109 // xx.m:13: warning: function called through a non-compatible type
2110 // xx.m:13: note: if this code is reached, the program will abort
2111 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2112 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002113
Steve Naroffab972d32007-11-04 22:37:50 +00002114 // Now do the "normal" pointer to function cast.
2115 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002116 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002117 // If we don't have a method decl, force a variadic cast.
2118 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002119 castType = Context->getPointerType(castType);
2120 cast = new CastExpr(castType, cast, SourceLocation());
2121
2122 // Don't forget the parens to enforce the proper binding.
2123 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2124
2125 const FunctionType *FT = msgSendType->getAsFunctionType();
2126 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2127 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002128 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002129 if (MsgSendStretFlavor) {
2130 // We have the method which returns a struct/union. Must also generate
2131 // call to objc_msgSend_stret and hang both varieties on a conditional
2132 // expression which dictate which one to envoke depending on size of
2133 // method's return type.
2134
2135 // Create a reference to the objc_msgSend_stret() declaration.
2136 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2137 SourceLocation());
2138 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2139 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2140 SourceLocation());
2141 // Now do the "normal" pointer to function cast.
2142 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002143 &ArgTypes[0], ArgTypes.size(),
2144 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002145 castType = Context->getPointerType(castType);
2146 cast = new CastExpr(castType, cast, SourceLocation());
2147
2148 // Don't forget the parens to enforce the proper binding.
2149 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2150
2151 FT = msgSendType->getAsFunctionType();
2152 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2153 FT->getResultType(), SourceLocation());
2154
2155 // Build sizeof(returnType)
2156 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2157 returnType, Context->getSizeType(),
2158 SourceLocation(), SourceLocation());
2159 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2160 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2161 // For X86 it is more complicated and some kind of target specific routine
2162 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002163 unsigned IntSize =
2164 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002165 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2166 Context->IntTy,
2167 SourceLocation());
2168 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2169 BinaryOperator::LE,
2170 Context->IntTy,
2171 SourceLocation());
2172 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2173 ConditionalOperator *CondExpr =
2174 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002175 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002176 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002177 return ReplacingStmt;
2178}
2179
Steve Naroffb29b4272008-04-14 22:03:09 +00002180Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002181 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002182 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002183 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002184
Chris Lattnere64b7772007-10-24 16:57:36 +00002185 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002186 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002187}
2188
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002189/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2190/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002191Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002192 if (!GetProtocolFunctionDecl)
2193 SynthGetProtocolFunctionDecl();
2194 // Create a call to objc_getProtocol("ProtocolName").
2195 llvm::SmallVector<Expr*, 8> ProtoExprs;
2196 QualType argType = Context->getPointerType(Context->CharTy);
2197 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2198 strlen(Exp->getProtocol()->getName()),
2199 false, argType, SourceLocation(),
2200 SourceLocation()));
2201 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2202 &ProtoExprs[0],
2203 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002204 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002205 delete Exp;
2206 return ProtoExp;
2207
2208}
2209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002211/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002212void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002213 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002214 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2215 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002216 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002218 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002220 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002221 SourceLocation LocStart = CDecl->getLocStart();
2222 SourceLocation LocEnd = CDecl->getLocEnd();
2223
2224 const char *startBuf = SM->getCharacterData(LocStart);
2225 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002226 // If no ivars and no root or if its root, directly or indirectly,
2227 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002228 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2229 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002231 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002232 return;
2233 }
2234
2235 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002237 Result += "\nstruct ";
2238 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002239 if (LangOpts.Microsoft)
2240 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002241
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002242 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002243 const char *cursor = strchr(startBuf, '{');
2244 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002246
2247 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002248 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002250 Result = "\n struct ";
2251 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002252 Result += "_IMPL ";
2253 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002254 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002255
2256 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002257 SourceLocation OnePastCurly =
2258 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2259 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002260 }
2261 cursor++; // past '{'
2262
2263 // Now comment out any visibility specifiers.
2264 while (cursor < endBuf) {
2265 if (*cursor == '@') {
2266 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002267 // Skip whitespace.
2268 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2269 /*scan*/;
2270
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002271 // FIXME: presence of @public, etc. inside comment results in
2272 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002273 if (!strncmp(cursor, "public", strlen("public")) ||
2274 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002275 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002276 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002277 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002278 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002279 // FIXME: If there are cases where '<' is used in ivar declaration part
2280 // of user code, then scan the ivar list and use needToScanForQualifiers
2281 // for type checking.
2282 else if (*cursor == '<') {
2283 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002284 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002285 cursor = strchr(cursor, '>');
2286 cursor++;
2287 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002288 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002289 }
Steve Narofffea763e82007-11-14 19:25:57 +00002290 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002291 }
Steve Narofffea763e82007-11-14 19:25:57 +00002292 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002293 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002294 } else { // we don't have any instance variables - insert super struct.
2295 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2296 Result += " {\n struct ";
2297 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002298 Result += "_IMPL ";
2299 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002300 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002301 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002302 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002303 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002304 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002305 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002306}
2307
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002308// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002309/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002310void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002311 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002312 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002313 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002314 const char *ClassName,
2315 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002316 if (MethodBegin == MethodEnd) return;
2317
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002318 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002319 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002320 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002321 SEL _cmd;
2322 char *method_types;
2323 void *_imp;
2324 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002325 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002326 Result += "\nstruct _objc_method {\n";
2327 Result += "\tSEL _cmd;\n";
2328 Result += "\tchar *method_types;\n";
2329 Result += "\tvoid *_imp;\n";
2330 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002331
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002332 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002333 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002334
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002335 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002336
2337 /* struct {
2338 struct _objc_method_list *next_method;
2339 int method_count;
2340 struct _objc_method method_list[];
2341 }
2342 */
2343 Result += "\nstatic struct {\n";
2344 Result += "\tstruct _objc_method_list *next_method;\n";
2345 Result += "\tint method_count;\n";
2346 Result += "\tstruct _objc_method method_list[";
2347 Result += utostr(MethodEnd-MethodBegin);
2348 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002349 Result += prefix;
2350 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2351 Result += "_METHODS_";
2352 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002353 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002354 Result += IsInstanceMethod ? "inst" : "cls";
2355 Result += "_meth\")))= ";
2356 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002357
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002358 Result += "\t,{{(SEL)\"";
2359 Result += (*MethodBegin)->getSelector().getName().c_str();
2360 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002361 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002362 Result += "\", \"";
2363 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002364 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002365 Result += MethodInternalNames[*MethodBegin];
2366 Result += "}\n";
2367 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2368 Result += "\t ,{(SEL)\"";
2369 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002370 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002372 Result += "\", \"";
2373 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002374 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002375 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002376 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002377 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002378 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002379}
2380
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002382void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002383 int NumProtocols,
2384 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002385 const char *ClassName,
2386 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002387 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002388 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002389 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002390 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002391 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002392 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002393 /* struct protocol_methods {
2394 SEL _cmd;
2395 char *method_types;
2396 }
2397 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002398 Result += "\nstruct protocol_methods {\n";
2399 Result += "\tSEL _cmd;\n";
2400 Result += "\tchar *method_types;\n";
2401 Result += "};\n";
2402
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002403 objc_protocol_methods = true;
2404 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002405 // Do not synthesize the protocol more than once.
2406 if (ObjCSynthesizedProtocols.count(PDecl))
2407 continue;
2408
Chris Lattnerc8581052008-03-16 20:19:15 +00002409 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2410 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002411 /* struct _objc_protocol_method_list {
2412 int protocol_method_count;
2413 struct protocol_methods protocols[];
2414 }
2415 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002416 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002417 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002418 Result += "\tstruct protocol_methods protocols[";
2419 Result += utostr(NumMethods);
2420 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002421 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002422 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002423 "{\n\t" + utostr(NumMethods) + "\n";
2424
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002425 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002426 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002427 E = PDecl->instmeth_end(); I != E; ++I) {
2428 if (I == PDecl->instmeth_begin())
2429 Result += "\t ,{{(SEL)\"";
2430 else
2431 Result += "\t ,{(SEL)\"";
2432 Result += (*I)->getSelector().getName().c_str();
2433 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002435 Result += "\", \"";
2436 Result += MethodTypeString;
2437 Result += "\"}\n";
2438 }
2439 Result += "\t }\n};\n";
2440 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002441
2442 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002443 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002444 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002445 /* struct _objc_protocol_method_list {
2446 int protocol_method_count;
2447 struct protocol_methods protocols[];
2448 }
2449 */
2450 Result += "\nstatic struct {\n";
2451 Result += "\tint protocol_method_count;\n";
2452 Result += "\tstruct protocol_methods protocols[";
2453 Result += utostr(NumMethods);
2454 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002456 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002457 "{\n\t";
2458 Result += utostr(NumMethods);
2459 Result += "\n";
2460
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002461 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002463 E = PDecl->classmeth_end(); I != E; ++I) {
2464 if (I == PDecl->classmeth_begin())
2465 Result += "\t ,{{(SEL)\"";
2466 else
2467 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002468 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002469 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002470 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002471 Result += "\", \"";
2472 Result += MethodTypeString;
2473 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002474 }
2475 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002476 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002477
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002478 // Output:
2479 /* struct _objc_protocol {
2480 // Objective-C 1.0 extensions
2481 struct _objc_protocol_extension *isa;
2482 char *protocol_name;
2483 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484 struct _objc_protocol_method_list *instance_methods;
2485 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002486 };
2487 */
2488 static bool objc_protocol = false;
2489 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002490 Result += "\nstruct _objc_protocol {\n";
2491 Result += "\tstruct _objc_protocol_extension *isa;\n";
2492 Result += "\tchar *protocol_name;\n";
2493 Result += "\tstruct _objc_protocol **protocol_list;\n";
2494 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2495 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2496 Result += "};\n";
2497
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002498 objc_protocol = true;
2499 }
2500
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002501 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2502 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002503 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002504 "{\n\t0, \"";
2505 Result += PDecl->getName();
2506 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002507 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002508 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 Result += PDecl->getName();
2510 Result += ", ";
2511 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002512 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002514 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002515 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002516 Result += PDecl->getName();
2517 Result += "\n";
2518 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002519 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002520 Result += "0\n";
2521 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002522
2523 // Mark this protocol as having been generated.
2524 if (!ObjCSynthesizedProtocols.insert(PDecl))
2525 assert(false && "protocol already synthesized");
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002526 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002527 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002528 /* struct _objc_protocol_list {
2529 struct _objc_protocol_list *next;
2530 int protocol_count;
2531 struct _objc_protocol *class_protocols[];
2532 }
2533 */
2534 Result += "\nstatic struct {\n";
2535 Result += "\tstruct _objc_protocol_list *next;\n";
2536 Result += "\tint protocol_count;\n";
2537 Result += "\tstruct _objc_protocol *class_protocols[";
2538 Result += utostr(NumProtocols);
2539 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002540 Result += prefix;
2541 Result += "_PROTOCOLS_";
2542 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002543 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544 "{\n\t0, ";
2545 Result += utostr(NumProtocols);
2546 Result += "\n";
2547
2548 Result += "\t,{&_OBJC_PROTOCOL_";
2549 Result += Protocols[0]->getName();
2550 Result += " \n";
2551
2552 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Narofffa8ec622008-04-18 22:15:15 +00002554 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002555 Result += PDecl->getName();
2556 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002557 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002558 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002559 }
2560}
2561
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002562/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002563/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002564void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002565 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002566 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002567 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002569 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2570 CDecl = CDecl->getNextClassCategory())
2571 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2572 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002573
Chris Lattnereb44eee2007-12-23 01:40:15 +00002574 std::string FullCategoryName = ClassDecl->getName();
2575 FullCategoryName += '_';
2576 FullCategoryName += IDecl->getName();
2577
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002578 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002579 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002580 true, "CATEGORY_", FullCategoryName.c_str(),
2581 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002582
2583 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002584 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002585 false, "CATEGORY_", FullCategoryName.c_str(),
2586 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002587
2588 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002589 // Null CDecl is case of a category implementation with no category interface
2590 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002591 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002592 CDecl->getNumReferencedProtocols(),
2593 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002594 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002595
2596 /* struct _objc_category {
2597 char *category_name;
2598 char *class_name;
2599 struct _objc_method_list *instance_methods;
2600 struct _objc_method_list *class_methods;
2601 struct _objc_protocol_list *protocols;
2602 // Objective-C 1.0 extensions
2603 uint32_t size; // sizeof (struct _objc_category)
2604 struct _objc_property_list *instance_properties; // category's own
2605 // @property decl.
2606 };
2607 */
2608
2609 static bool objc_category = false;
2610 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002611 Result += "\nstruct _objc_category {\n";
2612 Result += "\tchar *category_name;\n";
2613 Result += "\tchar *class_name;\n";
2614 Result += "\tstruct _objc_method_list *instance_methods;\n";
2615 Result += "\tstruct _objc_method_list *class_methods;\n";
2616 Result += "\tstruct _objc_protocol_list *protocols;\n";
2617 Result += "\tunsigned int size;\n";
2618 Result += "\tstruct _objc_property_list *instance_properties;\n";
2619 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002620 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002621 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002622 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2623 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002624 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002625 Result += IDecl->getName();
2626 Result += "\"\n\t, \"";
2627 Result += ClassDecl->getName();
2628 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002629
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002630 if (IDecl->getNumInstanceMethods() > 0) {
2631 Result += "\t, (struct _objc_method_list *)"
2632 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2633 Result += FullCategoryName;
2634 Result += "\n";
2635 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002636 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002637 Result += "\t, 0\n";
2638 if (IDecl->getNumClassMethods() > 0) {
2639 Result += "\t, (struct _objc_method_list *)"
2640 "&_OBJC_CATEGORY_CLASS_METHODS_";
2641 Result += FullCategoryName;
2642 Result += "\n";
2643 }
2644 else
2645 Result += "\t, 0\n";
2646
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002647 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002648 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2649 Result += FullCategoryName;
2650 Result += "\n";
2651 }
2652 else
2653 Result += "\t, 0\n";
2654 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002655}
2656
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002657/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2658/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002659void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002660 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002661 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002662 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002663 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002664 if (LangOpts.Microsoft)
2665 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002666 Result += ", ";
2667 Result += ivar->getName();
2668 Result += ")";
2669}
2670
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002671//===----------------------------------------------------------------------===//
2672// Meta Data Emission
2673//===----------------------------------------------------------------------===//
2674
Steve Naroffb29b4272008-04-14 22:03:09 +00002675void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002676 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002677 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002678
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002679 // Explictly declared @interface's are already synthesized.
2680 if (CDecl->ImplicitInterfaceDecl()) {
2681 // FIXME: Implementation of a class with no @interface (legacy) doese not
2682 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002683 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002684 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002685
Chris Lattnerbe6df082007-12-12 07:56:42 +00002686 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002687 unsigned NumIvars = !IDecl->ivar_empty()
2688 ? IDecl->ivar_size()
2689 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002690 if (NumIvars > 0) {
2691 static bool objc_ivar = false;
2692 if (!objc_ivar) {
2693 /* struct _objc_ivar {
2694 char *ivar_name;
2695 char *ivar_type;
2696 int ivar_offset;
2697 };
2698 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002699 Result += "\nstruct _objc_ivar {\n";
2700 Result += "\tchar *ivar_name;\n";
2701 Result += "\tchar *ivar_type;\n";
2702 Result += "\tint ivar_offset;\n";
2703 Result += "};\n";
2704
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002705 objc_ivar = true;
2706 }
2707
Steve Naroff946a6932008-03-11 00:12:29 +00002708 /* struct {
2709 int ivar_count;
2710 struct _objc_ivar ivar_list[nIvars];
2711 };
2712 */
2713 Result += "\nstatic struct {\n";
2714 Result += "\tint ivar_count;\n";
2715 Result += "\tstruct _objc_ivar ivar_list[";
2716 Result += utostr(NumIvars);
2717 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002718 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002719 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002720 "{\n\t";
2721 Result += utostr(NumIvars);
2722 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002723
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002724 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002725 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002726 IVI = IDecl->ivar_begin();
2727 IVE = IDecl->ivar_end();
2728 } else {
2729 IVI = CDecl->ivar_begin();
2730 IVE = CDecl->ivar_end();
2731 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002733 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002734 Result += "\", \"";
2735 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002736 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2737 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002738 Result += StrEncoding;
2739 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002740 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002741 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002742 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002743 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002744 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002745 Result += "\", \"";
2746 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002747 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2748 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002749 Result += StrEncoding;
2750 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002751 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002752 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002753 }
2754
2755 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756 }
2757
2758 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002759 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002760 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002761
2762 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002763 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002764 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002765
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002766 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002767 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002768 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002769 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002770
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002771
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002772 // Declaration of class/meta-class metadata
2773 /* struct _objc_class {
2774 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002775 const char *super_class_name;
2776 char *name;
2777 long version;
2778 long info;
2779 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002780 struct _objc_ivar_list *ivars;
2781 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002782 struct objc_cache *cache;
2783 struct objc_protocol_list *protocols;
2784 const char *ivar_layout;
2785 struct _objc_class_ext *ext;
2786 };
2787 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002788 static bool objc_class = false;
2789 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002790 Result += "\nstruct _objc_class {\n";
2791 Result += "\tstruct _objc_class *isa;\n";
2792 Result += "\tconst char *super_class_name;\n";
2793 Result += "\tchar *name;\n";
2794 Result += "\tlong version;\n";
2795 Result += "\tlong info;\n";
2796 Result += "\tlong instance_size;\n";
2797 Result += "\tstruct _objc_ivar_list *ivars;\n";
2798 Result += "\tstruct _objc_method_list *methods;\n";
2799 Result += "\tstruct objc_cache *cache;\n";
2800 Result += "\tstruct _objc_protocol_list *protocols;\n";
2801 Result += "\tconst char *ivar_layout;\n";
2802 Result += "\tstruct _objc_class_ext *ext;\n";
2803 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002804 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002805 }
2806
2807 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002808 ObjCInterfaceDecl *RootClass = 0;
2809 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002810 while (SuperClass) {
2811 RootClass = SuperClass;
2812 SuperClass = SuperClass->getSuperClass();
2813 }
2814 SuperClass = CDecl->getSuperClass();
2815
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002816 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2817 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002818 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002819 "{\n\t(struct _objc_class *)\"";
2820 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2821 Result += "\"";
2822
2823 if (SuperClass) {
2824 Result += ", \"";
2825 Result += SuperClass->getName();
2826 Result += "\", \"";
2827 Result += CDecl->getName();
2828 Result += "\"";
2829 }
2830 else {
2831 Result += ", 0, \"";
2832 Result += CDecl->getName();
2833 Result += "\"";
2834 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002835 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002836 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002837 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002838 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002839 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002840 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002841 Result += "\n";
2842 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002843 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 Result += ", 0\n";
2845 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002846 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 Result += CDecl->getName();
2848 Result += ",0,0\n";
2849 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002850 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002851 Result += "\t,0,0,0,0\n";
2852 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002853
2854 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2856 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002857 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002858 "{\n\t&_OBJC_METACLASS_";
2859 Result += CDecl->getName();
2860 if (SuperClass) {
2861 Result += ", \"";
2862 Result += SuperClass->getName();
2863 Result += "\", \"";
2864 Result += CDecl->getName();
2865 Result += "\"";
2866 }
2867 else {
2868 Result += ", 0, \"";
2869 Result += CDecl->getName();
2870 Result += "\"";
2871 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002872 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002873 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002874 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002875 Result += ",0";
2876 else {
2877 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002878 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002879 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002880 if (LangOpts.Microsoft)
2881 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002882 Result += ")";
2883 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002884 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002885 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += CDecl->getName();
2887 Result += "\n\t";
2888 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002889 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002890 Result += ",0";
2891 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002892 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002893 Result += CDecl->getName();
2894 Result += ", 0\n\t";
2895 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002896 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 Result += ",0,0";
2898 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002899 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002900 Result += CDecl->getName();
2901 Result += ", 0,0\n";
2902 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002903 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002904 Result += ",0,0,0\n";
2905 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002906}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002907
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002908/// RewriteImplementations - This routine rewrites all method implementations
2909/// and emits meta-data.
2910
Steve Naroffb29b4272008-04-14 22:03:09 +00002911void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002912 int ClsDefCount = ClassImplementation.size();
2913 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002914
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002915 if (ClsDefCount == 0 && CatDefCount == 0)
2916 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002917 // Rewrite implemented methods
2918 for (int i = 0; i < ClsDefCount; i++)
2919 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002920
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002921 for (int i = 0; i < CatDefCount; i++)
2922 RewriteImplementationDecl(CategoryImplementation[i]);
2923
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002924 // This is needed for use of offsetof
Steve Naroffb10f2732008-04-04 22:58:22 +00002925 Result += "#define offsetof(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002926 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002927 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002928 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002929
2930 // For each implemented category, write out all its meta data.
2931 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002932 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002933
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002934 // Write objc_symtab metadata
2935 /*
2936 struct _objc_symtab
2937 {
2938 long sel_ref_cnt;
2939 SEL *refs;
2940 short cls_def_cnt;
2941 short cat_def_cnt;
2942 void *defs[cls_def_cnt + cat_def_cnt];
2943 };
2944 */
2945
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002946 Result += "\nstruct _objc_symtab {\n";
2947 Result += "\tlong sel_ref_cnt;\n";
2948 Result += "\tSEL *refs;\n";
2949 Result += "\tshort cls_def_cnt;\n";
2950 Result += "\tshort cat_def_cnt;\n";
2951 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2952 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002953
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002954 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002955 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002956 Result += "\t0, 0, " + utostr(ClsDefCount)
2957 + ", " + utostr(CatDefCount) + "\n";
2958 for (int i = 0; i < ClsDefCount; i++) {
2959 Result += "\t,&_OBJC_CLASS_";
2960 Result += ClassImplementation[i]->getName();
2961 Result += "\n";
2962 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002963
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002964 for (int i = 0; i < CatDefCount; i++) {
2965 Result += "\t,&_OBJC_CATEGORY_";
2966 Result += CategoryImplementation[i]->getClassInterface()->getName();
2967 Result += "_";
2968 Result += CategoryImplementation[i]->getName();
2969 Result += "\n";
2970 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002971
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002972 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002973
2974 // Write objc_module metadata
2975
2976 /*
2977 struct _objc_module {
2978 long version;
2979 long size;
2980 const char *name;
2981 struct _objc_symtab *symtab;
2982 }
2983 */
2984
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002985 Result += "\nstruct _objc_module {\n";
2986 Result += "\tlong version;\n";
2987 Result += "\tlong size;\n";
2988 Result += "\tconst char *name;\n";
2989 Result += "\tstruct _objc_symtab *symtab;\n";
2990 Result += "};\n\n";
2991 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002992 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002993 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2994 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002995 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002996
2997 if (LangOpts.Microsoft) {
2998 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2999 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
3000 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3001 Result += "&_OBJC_MODULES;\n";
3002 Result += "#pragma data_seg(pop)\n\n";
3003 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003004}
Chris Lattner311ff022007-10-16 22:36:42 +00003005
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003006