blob: eabc87bef2db95f6af35438614cb5cddb2fa96b8 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Steve Naroff0113c9d2008-01-28 21:34:52 +000035static llvm::cl::opt<bool>
36SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
37 llvm::cl::desc("Silence ObjC rewriting warnings"));
38
Chris Lattner77cd2a02007-10-11 00:43:27 +000039namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattner01c57482007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000050 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000053
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000062
Steve Naroffd82a9ab2008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000076
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000080
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff874e2322007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffa7b402d2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Naroffba92b2e2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000096
97 // Block expressions.
98 llvm::SmallVector<BlockExpr *, 32> Blocks;
99 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
100 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000101
Steve Naroff54055232008-10-27 17:20:55 +0000102 // Block related declarations.
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
106
107 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
108
Steve Naroffc77a6362008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000111 // This maps a property to it's synthesied message expression.
112 // This allows us to rewrite chained getters (e.g. o.a.b.c).
113 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
114
Steve Naroff4c3580e2008-12-04 23:50:32 +0000115 // This maps an original source AST to it's rewritten form. This allows
116 // us to avoid rewriting the same node twice (which is very uncommon).
117 // This is needed to support some of the exotic property rewriting.
118 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000119
Steve Naroff54055232008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000124 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
127 virtual void InitializeTU(TranslationUnit &TU) {
128 TU.SetOwnsDecls(false);
129 Initialize(TU.getContext());
130 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000131
Chris Lattner8a12c272007-10-11 18:38:32 +0000132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133 // Top Level Driver code.
134 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000135 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000136 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000137 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000138
139 ~RewriteObjC() {}
140
141 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142
143 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000144 Stmt *ReplacingStmt = ReplacedNodes[Old];
145
146 if (ReplacingStmt)
147 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Steve Naroff4c3580e2008-12-04 23:50:32 +0000149 // If replacement succeeded or warning disabled return with no warning.
150 if (!Rewrite.ReplaceStmt(Old, New)) {
151 ReplacedNodes[Old] = New;
152 return;
153 }
154 if (SilenceRewriteMacroWarning)
155 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000156 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
157 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000158 }
159
Steve Naroffba92b2e2008-03-27 22:29:16 +0000160 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
161 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000162 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000163 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000164 SilenceRewriteMacroWarning)
165 return;
166
167 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
168 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000169
Chris Lattneraadaf782008-01-31 19:51:04 +0000170 void RemoveText(SourceLocation Loc, unsigned StrLen) {
171 // If removal succeeded or warning disabled return with no warning.
172 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
173 return;
174
175 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
176 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000177
Chris Lattneraadaf782008-01-31 19:51:04 +0000178 void ReplaceText(SourceLocation Start, unsigned OrigLength,
179 const char *NewStr, unsigned NewLength) {
180 // If removal succeeded or warning disabled return with no warning.
181 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
182 SilenceRewriteMacroWarning)
183 return;
184
185 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
186 }
187
Chris Lattnerf04da132007-10-24 17:06:59 +0000188 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000189 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000190 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000191 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000193 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
194 ObjCImplementationDecl *IMD,
195 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000197 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
199 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
200 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
201 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
202 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000203 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000204 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000206 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000207 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000208 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000209 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000210 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000211 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000214 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000215 void CollectPropertySetters(Stmt *S);
216
Steve Naroff8599e7a2008-12-08 16:43:47 +0000217 Stmt *CurrentBody;
218 ParentMap *PropParentMap; // created lazily.
219
Chris Lattnere64b7772007-10-24 16:57:36 +0000220 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000221 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000222 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
223 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt);
Steve Naroffb42f8412007-11-05 14:50:49 +0000224 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000225 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000226 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000227 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000228 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000230 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
232 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
233 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000234 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
235 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000236 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
237 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000238 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000239 Stmt *RewriteBreakStmt(BreakStmt *S);
240 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000241 void SynthCountByEnumWithState(std::string &buf);
242
Steve Naroff09b266e2007-10-30 23:14:51 +0000243 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000244 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000245 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000246 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000247 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000248 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000249 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000250 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000251 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000252 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000253
Chris Lattnerf04da132007-10-24 17:06:59 +0000254 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000256 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000257
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000259 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000260
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000261 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
262 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000263 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000264 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000265 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000266 const char *ClassName,
267 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000268
Chris Lattner780f3292008-07-21 21:32:27 +0000269 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
270 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000271 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000272 const char *ClassName,
273 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000275 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
277 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000278 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000279 void RewriteImplementations();
280 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000281
282 // Block rewriting.
283 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
284 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
285
286 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
287 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
288
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000289 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000290 void RewriteBlockCall(CallExpr *Exp);
291 void RewriteBlockPointerDecl(NamedDecl *VD);
292 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
293 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
294
295 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
296 const char *funcName, std::string Tag);
297 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
298 const char *funcName, std::string Tag);
299 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
300 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000301 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000302 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
303 const char *FunName);
304
305 void CollectBlockDeclRefInfo(BlockExpr *Exp);
306 void GetBlockCallExprs(Stmt *S);
307 void GetBlockDeclRefExprs(Stmt *S);
308
309 // We avoid calling Type::isBlockPointerType(), since it operates on the
310 // canonical type. We only care if the top-level type is a closure pointer.
311 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
312
313 // FIXME: This predicate seems like it would be useful to add to ASTContext.
314 bool isObjCType(QualType T) {
315 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
316 return false;
317
318 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
319
320 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
321 OCT == Context->getCanonicalType(Context->getObjCClassType()))
322 return true;
323
324 if (const PointerType *PT = OCT->getAsPointerType()) {
325 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
326 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
327 return true;
328 }
329 return false;
330 }
331 bool PointerTypeTakesAnyBlockArguments(QualType QT);
332 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000333 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000334
335 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000336 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000337 };
338}
339
Steve Naroff54055232008-10-27 17:20:55 +0000340void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
341 NamedDecl *D) {
342 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
343 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
344 E = fproto->arg_type_end(); I && (I != E); ++I)
345 if (isBlockPointerType(*I)) {
346 // All the args are checked/rewritten. Don't call twice!
347 RewriteBlockPointerDecl(D);
348 break;
349 }
350 }
351}
352
353void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
354 const PointerType *PT = funcType->getAsPointerType();
355 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
356 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
357}
358
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000359static bool IsHeaderFile(const std::string &Filename) {
360 std::string::size_type DotPos = Filename.rfind('.');
361
362 if (DotPos == std::string::npos) {
363 // no file extension
364 return false;
365 }
366
367 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
368 // C header: .h
369 // C++ header: .hh or .H;
370 return Ext == "h" || Ext == "hh" || Ext == "H";
371}
372
Steve Naroffb29b4272008-04-14 22:03:09 +0000373RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000374 Diagnostic &D, const LangOptions &LOpts)
375 : Diags(D), LangOpts(LOpts) {
376 IsHeader = IsHeaderFile(inFile);
377 InFileName = inFile;
378 OutFileName = outFile;
379 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
380 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000381 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
382 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000383}
384
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000385ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000386 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000387 Diagnostic &Diags,
388 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000389 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000390}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000391
Steve Naroffb29b4272008-04-14 22:03:09 +0000392void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000393 Context = &context;
394 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000395 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000396 MsgSendFunctionDecl = 0;
397 MsgSendSuperFunctionDecl = 0;
398 MsgSendStretFunctionDecl = 0;
399 MsgSendSuperStretFunctionDecl = 0;
400 MsgSendFpretFunctionDecl = 0;
401 GetClassFunctionDecl = 0;
402 GetMetaClassFunctionDecl = 0;
403 SelGetUidFunctionDecl = 0;
404 CFStringFunctionDecl = 0;
405 GetProtocolFunctionDecl = 0;
406 ConstantStringClassReference = 0;
407 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000408 CurMethodDef = 0;
409 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000410 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000411 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000412 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000413 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000414 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000415 PropParentMap = 0;
416 CurrentBody = 0;
417
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000418 // Get the ID and start/end of the main file.
419 MainFileID = SM->getMainFileID();
420 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
421 MainFileStart = MainBuf->getBufferStart();
422 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000425
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000426 // declaring objc_selector outside the parameter list removes a silly
427 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000428 if (IsHeader)
429 Preamble = "#pragma once\n";
430 Preamble += "struct objc_selector; struct objc_class;\n";
431 Preamble += "#ifndef OBJC_SUPER\n";
432 Preamble += "struct objc_super { struct objc_object *object; ";
433 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000434 if (LangOpts.Microsoft) {
435 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000436 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
437 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000438 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "};\n";
440 Preamble += "#define OBJC_SUPER\n";
441 Preamble += "#endif\n";
442 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
443 Preamble += "typedef struct objc_object Protocol;\n";
444 Preamble += "#define _REWRITER_typedef_Protocol\n";
445 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000446 if (LangOpts.Microsoft) {
447 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
448 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
449 } else
450 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
451 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000452 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000453 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000454 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000455 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000457 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000458 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000459 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000461 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000462 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000463 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000464 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000465 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
466 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
467 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
468 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
469 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000470 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000471 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000472 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
473 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
474 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000475 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
476 Preamble += "struct __objcFastEnumerationState {\n\t";
477 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000478 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000479 Preamble += "unsigned long *mutationsPtr;\n\t";
480 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000481 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000482 Preamble += "#define __FASTENUMERATIONSTATE\n";
483 Preamble += "#endif\n";
484 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
485 Preamble += "struct __NSConstantStringImpl {\n";
486 Preamble += " int *isa;\n";
487 Preamble += " int flags;\n";
488 Preamble += " char *str;\n";
489 Preamble += " long length;\n";
490 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000491 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
492 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
493 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000495 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000496 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
497 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000498 // Blocks preamble.
499 Preamble += "#ifndef BLOCK_IMPL\n";
500 Preamble += "#define BLOCK_IMPL\n";
501 Preamble += "struct __block_impl {\n";
502 Preamble += " void *isa;\n";
503 Preamble += " int Flags;\n";
504 Preamble += " int Size;\n";
505 Preamble += " void *FuncPtr;\n";
506 Preamble += "};\n";
507 Preamble += "enum {\n";
508 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
509 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
510 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000511 Preamble += "// Runtime copy/destroy helper functions\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000512 Preamble += "__OBJC_RW_STATICIMPORT void _Block_copy_assign(void *, void *);\n";
513 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_assign_copy(void *, void *);\n";
514 Preamble += "__OBJC_RW_STATICIMPORT void _Block_destroy(void *);\n";
515 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_release(void *);\n";
516 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock;\n";
517 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000518 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000519 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000520 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
521 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000522 Preamble += "#define __attribute__(X)\n";
523 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000524}
525
526
Chris Lattnerf04da132007-10-24 17:06:59 +0000527//===----------------------------------------------------------------------===//
528// Top Level Driver Code
529//===----------------------------------------------------------------------===//
530
Steve Naroffb29b4272008-04-14 22:03:09 +0000531void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000532 // Two cases: either the decl could be in the main file, or it could be in a
533 // #included file. If the former, rewrite it now. If the later, check to see
534 // if we rewrote the #include/#import.
535 SourceLocation Loc = D->getLocation();
536 Loc = SM->getLogicalLoc(Loc);
537
538 // If this is for a builtin, ignore it.
539 if (Loc.isInvalid()) return;
540
Steve Naroffebf2b562007-10-23 23:50:29 +0000541 // Look for built-in declarations that we need to refer during the rewrite.
542 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000543 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000544 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000545 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000546 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000547 ConstantStringClassReference = FVD;
548 return;
549 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000550 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000551 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000552 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000553 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000555 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000556 } else if (ObjCForwardProtocolDecl *FP =
557 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000558 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000559 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000561 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000562 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000563}
564
Chris Lattnerf04da132007-10-24 17:06:59 +0000565//===----------------------------------------------------------------------===//
566// Syntactic (non-AST) Rewriting Code
567//===----------------------------------------------------------------------===//
568
Steve Naroffb29b4272008-04-14 22:03:09 +0000569void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000570 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
571 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
572 const char *MainBufStart = MainBuf.first;
573 const char *MainBufEnd = MainBuf.second;
574 size_t ImportLen = strlen("import");
575 size_t IncludeLen = strlen("include");
576
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000577 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000578 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
579 if (*BufPtr == '#') {
580 if (++BufPtr == MainBufEnd)
581 return;
582 while (*BufPtr == ' ' || *BufPtr == '\t')
583 if (++BufPtr == MainBufEnd)
584 return;
585 if (!strncmp(BufPtr, "import", ImportLen)) {
586 // replace import with include
587 SourceLocation ImportLoc =
588 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000589 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000590 BufPtr += ImportLen;
591 }
592 }
593 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000594}
595
Steve Naroffb29b4272008-04-14 22:03:09 +0000596void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000597 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
598 const char *MainBufStart = MainBuf.first;
599 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000600
Chris Lattnerf04da132007-10-24 17:06:59 +0000601 // Loop over the whole file, looking for tabs.
602 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
603 if (*BufPtr != '\t')
604 continue;
605
606 // Okay, we found a tab. This tab will turn into at least one character,
607 // but it depends on which 'virtual column' it is in. Compute that now.
608 unsigned VCol = 0;
609 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
610 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
611 ++VCol;
612
613 // Okay, now that we know the virtual column, we know how many spaces to
614 // insert. We assume 8-character tab-stops.
615 unsigned Spaces = 8-(VCol & 7);
616
617 // Get the location of the tab.
618 SourceLocation TabLoc =
619 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
620
621 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000622 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000623 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000624}
625
Steve Naroffeb0646c2008-12-02 15:48:25 +0000626static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
627 ObjCIvarDecl *OID) {
628 std::string S;
629 S = "((struct ";
630 S += ClassDecl->getIdentifier()->getName();
631 S += "_IMPL *)self)->";
632 S += OID->getNameAsCString();
633 return S;
634}
635
Steve Naroffa0876e82008-12-02 17:36:43 +0000636void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
637 ObjCImplementationDecl *IMD,
638 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000639 SourceLocation startLoc = PID->getLocStart();
640 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000641 const char *startBuf = SM->getCharacterData(startLoc);
642 assert((*startBuf == '@') && "bogus @synthesize location");
643 const char *semiBuf = strchr(startBuf, ';');
644 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
645 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
646
647 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
648 return; // FIXME: is this correct?
649
650 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000651 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000652 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000653 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000654
655 if (!OID)
656 return;
657
658 std::string Getr;
659 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
660 Getr += "{ ";
661 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000662 // FIXME: deal with code generation implications for various property
663 // attributes (copy, retain, nonatomic).
664 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000665 Getr += "return " + getIvarAccessString(ClassDecl, OID);
666 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000667 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000668
669 // Add the rewritten getter to trigger meta data generation. An alternate, and
670 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
671 // with properties explicitly. The following addInstanceMethod() required far
672 // less code change (and actually models what the rewriter is doing).
673 if (IMD)
674 IMD->addInstanceMethod(PD->getGetterMethodDecl());
675 else
676 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000677
678 if (PD->isReadOnly())
679 return;
680
681 // Generate the 'setter' function.
682 std::string Setr;
683 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000684 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000685 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000686 // FIXME: deal with code generation implications for various property
687 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000688 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000689 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
690 Setr += OID->getNameAsCString();
691 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000692 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000693
694 // Add the rewritten setter to trigger meta data generation.
695 if (IMD)
696 IMD->addInstanceMethod(PD->getSetterMethodDecl());
697 else
698 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000699}
Chris Lattner8a12c272007-10-11 18:38:32 +0000700
Steve Naroffb29b4272008-04-14 22:03:09 +0000701void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000702 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000704
705 // Get the start location and compute the semi location.
706 SourceLocation startLoc = ClassDecl->getLocation();
707 const char *startBuf = SM->getCharacterData(startLoc);
708 const char *semiPtr = strchr(startBuf, ';');
709
710 // Translate to typedef's that forward reference structs with the same name
711 // as the class. As a convenience, we include the original declaration
712 // as a comment.
713 std::string typedefString;
714 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000715 typedefString.append(startBuf, semiPtr-startBuf+1);
716 typedefString += "\n";
717 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000719 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000720 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000721 typedefString += "\n";
722 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000723 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000724 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000725 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000726 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000727 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000728 }
729
730 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000731 ReplaceText(startLoc, semiPtr-startBuf+1,
732 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000736 SourceLocation LocStart = Method->getLocStart();
737 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000738
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000739 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000740 InsertText(LocStart, "#if 0\n", 6);
741 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000742 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000743 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000744 }
745}
746
Steve Naroffb29b4272008-04-14 22:03:09 +0000747void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000748{
Chris Lattner55d13b42008-03-16 21:23:50 +0000749 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000750 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000751 SourceLocation Loc = Property->getLocation();
752
Chris Lattneraadaf782008-01-31 19:51:04 +0000753 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000754
755 // FIXME: handle properties that are declared across multiple lines.
756 }
757}
758
Steve Naroffb29b4272008-04-14 22:03:09 +0000759void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000760 SourceLocation LocStart = CatDecl->getLocStart();
761
762 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000763 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000764
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000765 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000766 E = CatDecl->instmeth_end(); I != E; ++I)
767 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 E = CatDecl->classmeth_end(); I != E; ++I)
770 RewriteMethodDeclaration(*I);
771
Steve Naroff423cb562007-10-30 13:30:57 +0000772 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000773 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000774}
775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000777 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000778
Steve Naroff752d6ef2007-10-30 16:42:30 +0000779 SourceLocation LocStart = PDecl->getLocStart();
780
781 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000782 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000783
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000784 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000785 E = PDecl->instmeth_end(); I != E; ++I)
786 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000787 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000788 E = PDecl->classmeth_end(); I != E; ++I)
789 RewriteMethodDeclaration(*I);
790
Steve Naroff752d6ef2007-10-30 16:42:30 +0000791 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000792 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000793 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000794
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000795 // Must comment out @optional/@required
796 const char *startBuf = SM->getCharacterData(LocStart);
797 const char *endBuf = SM->getCharacterData(LocEnd);
798 for (const char *p = startBuf; p < endBuf; p++) {
799 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
800 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000801 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000802 ReplaceText(OptionalLoc, strlen("@optional"),
803 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000804
805 }
806 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
807 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000808 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000809 ReplaceText(OptionalLoc, strlen("@required"),
810 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811
812 }
813 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000814}
815
Steve Naroffb29b4272008-04-14 22:03:09 +0000816void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000817 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000818 if (LocStart.isInvalid())
819 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000820 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000821 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000822}
823
Steve Naroffb29b4272008-04-14 22:03:09 +0000824void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000825 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000826 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000827 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000828 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000829 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000830 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000831 else if (OMD->getResultType()->isFunctionPointerType()) {
832 // needs special handling, since pointer-to-functions have special
833 // syntax (where a decaration models use).
834 QualType retType = OMD->getResultType();
835 if (const PointerType* PT = retType->getAsPointerType()) {
836 QualType PointeeTy = PT->getPointeeType();
837 if ((FPRetType = PointeeTy->getAsFunctionType())) {
838 ResultStr += FPRetType->getResultType().getAsString();
839 ResultStr += "(*";
840 }
841 }
842 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000843 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000844 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000845
846 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000847 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000848
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000849 if (OMD->isInstance())
850 NameStr += "_I_";
851 else
852 NameStr += "_C_";
853
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000854 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000855 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856
857 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000858 if (ObjCCategoryImplDecl *CID =
859 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000860 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000861 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 }
Steve Naroff563b8282008-04-04 22:23:44 +0000863 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000864 {
865 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000866 int len = selString.size();
867 for (int i = 0; i < len; i++)
868 if (selString[i] == ':')
869 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000870 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000871 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000872 // Remember this name for metadata emission
873 MethodInternalNames[OMD] = NameStr;
874 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000875
876 // Rewrite arguments
877 ResultStr += "(";
878
879 // invisible arguments
880 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000881 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000882 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000883 if (!LangOpts.Microsoft) {
884 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
885 ResultStr += "struct ";
886 }
887 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000888 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000889 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000890 }
891 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000893
894 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000895 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 ResultStr += " _cmd";
897
898 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000899 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000900 ParmVarDecl *PDecl = OMD->getParamDecl(i);
901 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000902 if (PDecl->getType()->isObjCQualifiedIdType()) {
903 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000904 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000905 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000906 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000907 if (isBlockPointerType(PDecl->getType())) {
908 // Make sure we convert "t (^)(...)" to "t (*)(...)".
909 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
910 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
911 } else
912 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000913 ResultStr += Name;
914 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000915 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000916 if (OMD->isVariadic())
917 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000918 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000919
Steve Naroff76e429d2008-07-16 14:40:40 +0000920 if (FPRetType) {
921 ResultStr += ")"; // close the precedence "scope" for "*".
922
923 // Now, emit the argument types (if any).
924 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
925 ResultStr += "(";
926 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
927 if (i) ResultStr += ", ";
928 std::string ParamStr = FT->getArgType(i).getAsString();
929 ResultStr += ParamStr;
930 }
931 if (FT->isVariadic()) {
932 if (FT->getNumArgs()) ResultStr += ", ";
933 ResultStr += "...";
934 }
935 ResultStr += ")";
936 } else {
937 ResultStr += "()";
938 }
939 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940}
Steve Naroffb29b4272008-04-14 22:03:09 +0000941void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000942 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
943 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000945 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000946 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000947 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000948 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000949
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000950 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000951 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
952 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000953 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000954 ObjCMethodDecl *OMD = *I;
955 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000956 SourceLocation LocStart = OMD->getLocStart();
957 SourceLocation LocEnd = OMD->getBody()->getLocStart();
958
959 const char *startBuf = SM->getCharacterData(LocStart);
960 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000961 ReplaceText(LocStart, endBuf-startBuf,
962 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000963 }
964
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000965 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000966 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
967 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000968 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000969 ObjCMethodDecl *OMD = *I;
970 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000971 SourceLocation LocStart = OMD->getLocStart();
972 SourceLocation LocEnd = OMD->getBody()->getLocStart();
973
974 const char *startBuf = SM->getCharacterData(LocStart);
975 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000976 ReplaceText(LocStart, endBuf-startBuf,
977 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000979 for (ObjCCategoryImplDecl::propimpl_iterator
980 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
981 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000982 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000983 }
984
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000985 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000986 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000987 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000988 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989}
990
Steve Naroffb29b4272008-04-14 22:03:09 +0000991void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000992 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000993 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000994 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000995 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000996 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000997 ResultStr += "\n";
998 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000999 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001000 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001001 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001002 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001003 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001004 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001006 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001007 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001008
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001009 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1010 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001011 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001012 E = ClassDecl->instmeth_end(); I != E; ++I)
1013 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001014 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001015 E = ClassDecl->classmeth_end(); I != E; ++I)
1016 RewriteMethodDeclaration(*I);
1017
Steve Naroff2feac5e2007-10-30 03:43:13 +00001018 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001019 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001020}
1021
Steve Naroffc77a6362008-12-04 16:24:46 +00001022Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
1023 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1024 // This allows us to reuse all the fun and games in SynthMessageExpr().
1025 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1026 ObjCMessageExpr *MsgExpr;
1027 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1028 llvm::SmallVector<Expr *, 1> ExprVec;
1029 ExprVec.push_back(newStmt);
1030
Steve Naroff8599e7a2008-12-08 16:43:47 +00001031 Stmt *Receiver = PropRefExpr->getBase();
1032 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1033 if (PRE && PropGetters[PRE]) {
1034 // This allows us to handle chain/nested property getters.
1035 Receiver = PropGetters[PRE];
1036 }
1037 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001038 PDecl->getSetterName(), PDecl->getType(),
1039 PDecl->getSetterMethodDecl(),
1040 SourceLocation(), SourceLocation(),
1041 &ExprVec[0], 1);
1042 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1043
1044 // Now do the actual rewrite.
1045 ReplaceStmt(BinOp, ReplacingStmt);
1046 delete BinOp;
1047 delete MsgExpr;
1048 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001049}
1050
Steve Naroffc77a6362008-12-04 16:24:46 +00001051Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001052 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1053 // This allows us to reuse all the fun and games in SynthMessageExpr().
1054 ObjCMessageExpr *MsgExpr;
1055 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1056
Steve Naroff8599e7a2008-12-08 16:43:47 +00001057 Stmt *Receiver = PropRefExpr->getBase();
1058
1059 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1060 if (PRE && PropGetters[PRE]) {
1061 // This allows us to handle chain/nested property getters.
1062 Receiver = PropGetters[PRE];
1063 }
1064 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001065 PDecl->getGetterName(), PDecl->getType(),
1066 PDecl->getGetterMethodDecl(),
1067 SourceLocation(), SourceLocation(),
1068 0, 0);
1069
Steve Naroff4c3580e2008-12-04 23:50:32 +00001070 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001071
1072 if (!PropParentMap)
1073 PropParentMap = new ParentMap(CurrentBody);
1074
1075 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1076 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1077 // We stash away the ReplacingStmt since actually doing the
1078 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1079 PropGetters[PropRefExpr] = ReplacingStmt;
1080 delete MsgExpr;
1081 return PropRefExpr; // return the original...
1082 } else {
1083 ReplaceStmt(PropRefExpr, ReplacingStmt);
1084 // delete PropRefExpr; elsewhere...
1085 delete MsgExpr;
1086 return ReplacingStmt;
1087 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001088}
1089
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001090Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1091 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001092 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001093 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001094 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001095 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1096 // lookup which class implements the instance variable.
1097 ObjCInterfaceDecl *clsDeclared = 0;
1098 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1099 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1100
1101 // Synthesize an explicit cast to gain access to the ivar.
1102 std::string RecName = clsDeclared->getIdentifier()->getName();
1103 RecName += "_IMPL";
1104 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001105 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001106 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001107 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1108 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001109 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001110 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001111 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001112 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1113 IV->getBase()->getLocEnd(),
1114 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001115 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001116 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001117 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1118 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001119 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001120 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001121 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001122 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001123
1124 ReplaceStmt(IV->getBase(), PE);
1125 // Cannot delete IV->getBase(), since PE points to it.
1126 // Replace the old base with the cast. This is important when doing
1127 // embedded rewrites. For example, [newInv->_container addObject:0].
1128 IV->setBase(PE);
1129 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001130 }
Steve Naroff84472a82008-04-18 21:55:08 +00001131 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001132 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1133
1134 // Explicit ivar refs need to have a cast inserted.
1135 // FIXME: consider sharing some of this code with the code above.
1136 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001137 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001138 // lookup which class implements the instance variable.
1139 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001140 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001141 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1142
1143 // Synthesize an explicit cast to gain access to the ivar.
1144 std::string RecName = clsDeclared->getIdentifier()->getName();
1145 RecName += "_IMPL";
1146 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001147 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001148 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001149 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1150 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001151 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001152 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001153 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001154 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1155 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001156 ReplaceStmt(IV->getBase(), PE);
1157 // Cannot delete IV->getBase(), since PE points to it.
1158 // Replace the old base with the cast. This is important when doing
1159 // embedded rewrites. For example, [newInv->_container addObject:0].
1160 IV->setBase(PE);
1161 return IV;
1162 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001163 }
Steve Naroff84472a82008-04-18 21:55:08 +00001164 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001165}
1166
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001167/// SynthCountByEnumWithState - To print:
1168/// ((unsigned int (*)
1169/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1170/// (void *)objc_msgSend)((id)l_collection,
1171/// sel_registerName(
1172/// "countByEnumeratingWithState:objects:count:"),
1173/// &enumState,
1174/// (id *)items, (unsigned int)16)
1175///
Steve Naroffb29b4272008-04-14 22:03:09 +00001176void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001177 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1178 "id *, unsigned int))(void *)objc_msgSend)";
1179 buf += "\n\t\t";
1180 buf += "((id)l_collection,\n\t\t";
1181 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1182 buf += "\n\t\t";
1183 buf += "&enumState, "
1184 "(id *)items, (unsigned int)16)";
1185}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001186
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001187/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1188/// statement to exit to its outer synthesized loop.
1189///
Steve Naroffb29b4272008-04-14 22:03:09 +00001190Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001191 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1192 return S;
1193 // replace break with goto __break_label
1194 std::string buf;
1195
1196 SourceLocation startLoc = S->getLocStart();
1197 buf = "goto __break_label_";
1198 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001199 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001200
1201 return 0;
1202}
1203
1204/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1205/// statement to continue with its inner synthesized loop.
1206///
Steve Naroffb29b4272008-04-14 22:03:09 +00001207Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001208 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1209 return S;
1210 // replace continue with goto __continue_label
1211 std::string buf;
1212
1213 SourceLocation startLoc = S->getLocStart();
1214 buf = "goto __continue_label_";
1215 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001216 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001217
1218 return 0;
1219}
1220
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001221/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001222/// It rewrites:
1223/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001224
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001225/// Into:
1226/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001227/// type elem;
1228/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001229/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001230/// id l_collection = (id)collection;
1231/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1232/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001233/// if (limit) {
1234/// unsigned long startMutations = *enumState.mutationsPtr;
1235/// do {
1236/// unsigned long counter = 0;
1237/// do {
1238/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001239/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001240/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001241/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001242/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001243/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001244/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1245/// objects:items count:16]);
1246/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001247/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001248/// }
1249/// else
1250/// elem = nil;
1251/// }
1252///
Steve Naroffb29b4272008-04-14 22:03:09 +00001253Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001254 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001255 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1256 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1257 "ObjCForCollectionStmt Statement stack mismatch");
1258 assert(!ObjCBcLabelNo.empty() &&
1259 "ObjCForCollectionStmt - Label No stack empty");
1260
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001262 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001263 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001264 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001265 std::string buf;
1266 buf = "\n{\n\t";
1267 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1268 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001269 ScopedDecl* D = DS->getSolitaryDecl();
1270 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001271 elementTypeAsString = ElementType.getAsString();
1272 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001274 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275 buf += elementName;
1276 buf += ";\n\t";
1277 }
Chris Lattner06767512008-04-08 05:52:18 +00001278 else {
1279 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001280 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001281 elementTypeAsString
1282 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001283 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001284
1285 // struct __objcFastEnumerationState enumState = { 0 };
1286 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1287 // id items[16];
1288 buf += "id items[16];\n\t";
1289 // id l_collection = (id)
1290 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001291 // Find start location of 'collection' the hard way!
1292 const char *startCollectionBuf = startBuf;
1293 startCollectionBuf += 3; // skip 'for'
1294 startCollectionBuf = strchr(startCollectionBuf, '(');
1295 startCollectionBuf++; // skip '('
1296 // find 'in' and skip it.
1297 while (*startCollectionBuf != ' ' ||
1298 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1299 (*(startCollectionBuf+3) != ' ' &&
1300 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1301 startCollectionBuf++;
1302 startCollectionBuf += 3;
1303
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001304 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001305 ReplaceText(startLoc, startCollectionBuf - startBuf,
1306 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001308 SourceLocation rightParenLoc = S->getRParenLoc();
1309 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1310 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001311 buf = ";\n\t";
1312
1313 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1314 // objects:items count:16];
1315 // which is synthesized into:
1316 // unsigned int limit =
1317 // ((unsigned int (*)
1318 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1319 // (void *)objc_msgSend)((id)l_collection,
1320 // sel_registerName(
1321 // "countByEnumeratingWithState:objects:count:"),
1322 // (struct __objcFastEnumerationState *)&state,
1323 // (id *)items, (unsigned int)16);
1324 buf += "unsigned long limit =\n\t\t";
1325 SynthCountByEnumWithState(buf);
1326 buf += ";\n\t";
1327 /// if (limit) {
1328 /// unsigned long startMutations = *enumState.mutationsPtr;
1329 /// do {
1330 /// unsigned long counter = 0;
1331 /// do {
1332 /// if (startMutations != *enumState.mutationsPtr)
1333 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001334 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001335 buf += "if (limit) {\n\t";
1336 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1337 buf += "do {\n\t\t";
1338 buf += "unsigned long counter = 0;\n\t\t";
1339 buf += "do {\n\t\t\t";
1340 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1341 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1342 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001343 buf += " = (";
1344 buf += elementTypeAsString;
1345 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001347 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001348
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001349 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001350 /// } while (counter < limit);
1351 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1352 /// objects:items count:16]);
1353 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001354 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001355 /// }
1356 /// else
1357 /// elem = nil;
1358 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001359 ///
1360 buf = ";\n\t";
1361 buf += "__continue_label_";
1362 buf += utostr(ObjCBcLabelNo.back());
1363 buf += ": ;";
1364 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001365 buf += "} while (counter < limit);\n\t";
1366 buf += "} while (limit = ";
1367 SynthCountByEnumWithState(buf);
1368 buf += ");\n\t";
1369 buf += elementName;
1370 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001371 buf += "__break_label_";
1372 buf += utostr(ObjCBcLabelNo.back());
1373 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001374 buf += "}\n\t";
1375 buf += "else\n\t\t";
1376 buf += elementName;
1377 buf += " = nil;\n";
1378 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001379
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001381 if (isa<CompoundStmt>(S->getBody())) {
1382 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1383 InsertText(endBodyLoc, buf.c_str(), buf.size());
1384 } else {
1385 /* Need to treat single statements specially. For example:
1386 *
1387 * for (A *a in b) if (stuff()) break;
1388 * for (A *a in b) xxxyy;
1389 *
1390 * The following code simply scans ahead to the semi to find the actual end.
1391 */
1392 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1393 const char *semiBuf = strchr(stmtBuf, ';');
1394 assert(semiBuf && "Can't find ';'");
1395 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1396 InsertText(endBodyLoc, buf.c_str(), buf.size());
1397 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001398 Stmts.pop_back();
1399 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001400 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001401}
1402
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001403/// RewriteObjCSynchronizedStmt -
1404/// This routine rewrites @synchronized(expr) stmt;
1405/// into:
1406/// objc_sync_enter(expr);
1407/// @try stmt @finally { objc_sync_exit(expr); }
1408///
Steve Naroffb29b4272008-04-14 22:03:09 +00001409Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001410 // Get the start location and compute the semi location.
1411 SourceLocation startLoc = S->getLocStart();
1412 const char *startBuf = SM->getCharacterData(startLoc);
1413
1414 assert((*startBuf == '@') && "bogus @synchronized location");
1415
1416 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001417 buf = "objc_sync_enter((id)";
1418 const char *lparenBuf = startBuf;
1419 while (*lparenBuf != '(') lparenBuf++;
1420 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001421 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1422 // the sync expression is typically a message expression that's already
1423 // been rewritten! (which implies the SourceLocation's are invalid).
1424 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001425 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001426 while (*endBuf != ')') endBuf--;
1427 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001428 buf = ");\n";
1429 // declare a new scope with two variables, _stack and _rethrow.
1430 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1431 buf += "int buf[18/*32-bit i386*/];\n";
1432 buf += "char *pointers[4];} _stack;\n";
1433 buf += "id volatile _rethrow = 0;\n";
1434 buf += "objc_exception_try_enter(&_stack);\n";
1435 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001436 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001437 startLoc = S->getSynchBody()->getLocEnd();
1438 startBuf = SM->getCharacterData(startLoc);
1439
Steve Naroffc7089f12008-08-19 13:04:19 +00001440 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001441 SourceLocation lastCurlyLoc = startLoc;
1442 buf = "}\nelse {\n";
1443 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1444 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001445 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001446 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001447 S->getSynchExpr(),
1448 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001449 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001450 std::string syncExprBufS;
1451 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001452 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001453 buf += syncExprBuf.str();
1454 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001455 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1456 buf += "}\n";
1457 buf += "}";
1458
Chris Lattneraadaf782008-01-31 19:51:04 +00001459 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001460 return 0;
1461}
1462
Steve Naroff8c565152008-12-05 17:03:39 +00001463void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1464 // Perform a bottom up traversal of all children.
1465 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1466 CI != E; ++CI)
1467 if (*CI)
1468 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1469
1470 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1471 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1472 Diags.Report(Context->getFullLoc(S->getLocStart()),
1473 TryFinallyContainsReturnDiag);
1474 }
1475 return;
1476}
1477
Steve Naroffb29b4272008-04-14 22:03:09 +00001478Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001479 // Get the start location and compute the semi location.
1480 SourceLocation startLoc = S->getLocStart();
1481 const char *startBuf = SM->getCharacterData(startLoc);
1482
1483 assert((*startBuf == '@') && "bogus @try location");
1484
1485 std::string buf;
1486 // declare a new scope with two variables, _stack and _rethrow.
1487 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1488 buf += "int buf[18/*32-bit i386*/];\n";
1489 buf += "char *pointers[4];} _stack;\n";
1490 buf += "id volatile _rethrow = 0;\n";
1491 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001492 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001493
Chris Lattneraadaf782008-01-31 19:51:04 +00001494 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001495
1496 startLoc = S->getTryBody()->getLocEnd();
1497 startBuf = SM->getCharacterData(startLoc);
1498
1499 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001500
Steve Naroff75730982007-11-07 04:08:17 +00001501 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001502 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1503 if (catchList) {
1504 startLoc = startLoc.getFileLocWithOffset(1);
1505 buf = " /* @catch begin */ else {\n";
1506 buf += " id _caught = objc_exception_extract(&_stack);\n";
1507 buf += " objc_exception_try_enter (&_stack);\n";
1508 buf += " if (_setjmp(_stack.buf))\n";
1509 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1510 buf += " else { /* @catch continue */";
1511
1512 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001513 } else { /* no catch list */
1514 buf = "}\nelse {\n";
1515 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1516 buf += "}";
1517 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001518 }
Steve Naroff75730982007-11-07 04:08:17 +00001519 bool sawIdTypedCatch = false;
1520 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001521 while (catchList) {
1522 Stmt *catchStmt = catchList->getCatchParamStmt();
1523
1524 if (catchList == S->getCatchStmts())
1525 buf = "if ("; // we are generating code for the first catch clause
1526 else
1527 buf = "else if (";
1528 startLoc = catchList->getLocStart();
1529 startBuf = SM->getCharacterData(startLoc);
1530
1531 assert((*startBuf == '@') && "bogus @catch location");
1532
1533 const char *lParenLoc = strchr(startBuf, '(');
1534
Steve Naroffbe4b3332008-02-01 22:08:12 +00001535 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001536 // Now rewrite the body...
1537 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001538 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1539 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001540 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1541 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001542 assert((*bodyBuf == '{') && "bogus @catch body location");
1543
1544 buf += "1) { id _tmp = _caught;";
1545 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1546 buf.c_str(), buf.size());
1547 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001548 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001549 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001550 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001551 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001552 sawIdTypedCatch = true;
1553 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001554 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001555
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001556 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001557 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001558 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001559 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001560 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001561 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001562 }
1563 }
1564 // Now rewrite the body...
1565 lastCatchBody = catchList->getCatchBody();
1566 SourceLocation rParenLoc = catchList->getRParenLoc();
1567 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1568 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1569 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1570 assert((*rParenBuf == ')') && "bogus @catch paren location");
1571 assert((*bodyBuf == '{') && "bogus @catch body location");
1572
1573 buf = " = _caught;";
1574 // Here we replace ") {" with "= _caught;" (which initializes and
1575 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001576 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001577 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001578 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001579 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001580 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001581 catchList = catchList->getNextCatchStmt();
1582 }
1583 // Complete the catch list...
1584 if (lastCatchBody) {
1585 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001586 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1587 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001588
Steve Naroff378f47a2008-09-11 15:29:03 +00001589 // Insert the last (implicit) else clause *before* the right curly brace.
1590 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1591 buf = "} /* last catch end */\n";
1592 buf += "else {\n";
1593 buf += " _rethrow = _caught;\n";
1594 buf += " objc_exception_try_exit(&_stack);\n";
1595 buf += "} } /* @catch end */\n";
1596 if (!S->getFinallyStmt())
1597 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001598 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001599
1600 // Set lastCurlyLoc
1601 lastCurlyLoc = lastCatchBody->getLocEnd();
1602 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001603 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001604 startLoc = finalStmt->getLocStart();
1605 startBuf = SM->getCharacterData(startLoc);
1606 assert((*startBuf == '@') && "bogus @finally start");
1607
1608 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001609 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001610
1611 Stmt *body = finalStmt->getFinallyBody();
1612 SourceLocation startLoc = body->getLocStart();
1613 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001614 assert(*SM->getCharacterData(startLoc) == '{' &&
1615 "bogus @finally body location");
1616 assert(*SM->getCharacterData(endLoc) == '}' &&
1617 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001618
1619 startLoc = startLoc.getFileLocWithOffset(1);
1620 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001621 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001622 endLoc = endLoc.getFileLocWithOffset(-1);
1623 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001624 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001625
1626 // Set lastCurlyLoc
1627 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001628
1629 // Now check for any return/continue/go statements within the @try.
1630 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001631 } else { /* no finally clause - make sure we synthesize an implicit one */
1632 buf = "{ /* implicit finally clause */\n";
1633 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1634 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1635 buf += "}";
1636 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001637 }
1638 // Now emit the final closing curly brace...
1639 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1640 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001641 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001642 return 0;
1643}
1644
Steve Naroffb29b4272008-04-14 22:03:09 +00001645Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001646 return 0;
1647}
1648
Steve Naroffb29b4272008-04-14 22:03:09 +00001649Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001650 return 0;
1651}
1652
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001653// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001654// the throw expression is typically a message expression that's already
1655// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001656Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001657 // Get the start location and compute the semi location.
1658 SourceLocation startLoc = S->getLocStart();
1659 const char *startBuf = SM->getCharacterData(startLoc);
1660
1661 assert((*startBuf == '@') && "bogus @throw location");
1662
1663 std::string buf;
1664 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001665 if (S->getThrowExpr())
1666 buf = "objc_exception_throw(";
1667 else // add an implicit argument
1668 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001669
1670 // handle "@ throw" correctly.
1671 const char *wBuf = strchr(startBuf, 'w');
1672 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1673 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1674
Steve Naroff2bd03922007-11-07 15:32:26 +00001675 const char *semiBuf = strchr(startBuf, ';');
1676 assert((*semiBuf == ';') && "@throw: can't find ';'");
1677 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1678 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001679 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001680 return 0;
1681}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001682
Steve Naroffb29b4272008-04-14 22:03:09 +00001683Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001684 // Create a new string expression.
1685 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001686 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001687 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001688 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1689 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001690 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001691 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001692
Chris Lattner07506182007-11-30 22:53:43 +00001693 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001694 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001695 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001696}
1697
Steve Naroffb29b4272008-04-14 22:03:09 +00001698Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001699 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1700 // Create a call to sel_registerName("selName").
1701 llvm::SmallVector<Expr*, 8> SelExprs;
1702 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001703 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1704 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001705 false, argType, SourceLocation(),
1706 SourceLocation()));
1707 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1708 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001709 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001710 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001711 return SelExp;
1712}
1713
Steve Naroffb29b4272008-04-14 22:03:09 +00001714CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001715 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001716 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001717 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001718
1719 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001720 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001721
1722 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001723 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001724 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1725 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001726
1727 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001728
Steve Naroff934f2762007-10-24 22:48:43 +00001729 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1730}
1731
Steve Naroffd5255f52007-11-01 13:24:47 +00001732static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1733 const char *&startRef, const char *&endRef) {
1734 while (startBuf < endBuf) {
1735 if (*startBuf == '<')
1736 startRef = startBuf; // mark the start.
1737 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001738 if (startRef && *startRef == '<') {
1739 endRef = startBuf; // mark the end.
1740 return true;
1741 }
1742 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001743 }
1744 startBuf++;
1745 }
1746 return false;
1747}
1748
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001749static void scanToNextArgument(const char *&argRef) {
1750 int angle = 0;
1751 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1752 if (*argRef == '<')
1753 angle++;
1754 else if (*argRef == '>')
1755 angle--;
1756 argRef++;
1757 }
1758 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1759}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001760
Steve Naroffb29b4272008-04-14 22:03:09 +00001761bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001762
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001763 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001764 return true;
1765
Steve Naroffd5255f52007-11-01 13:24:47 +00001766 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001767 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001768 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001769 return true; // we have "Class <Protocol> *".
1770 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001771 return false;
1772}
1773
Steve Naroff4f95b752008-07-29 18:15:38 +00001774void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1775 QualType Type = E->getType();
1776 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001777 SourceLocation Loc, EndLoc;
1778
1779 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1780 Loc = ECE->getLParenLoc();
1781 EndLoc = ECE->getRParenLoc();
1782 } else {
1783 Loc = E->getLocStart();
1784 EndLoc = E->getLocEnd();
1785 }
1786 // This will defend against trying to rewrite synthesized expressions.
1787 if (Loc.isInvalid() || EndLoc.isInvalid())
1788 return;
1789
Steve Naroff4f95b752008-07-29 18:15:38 +00001790 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001791 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001792 const char *startRef = 0, *endRef = 0;
1793 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1794 // Get the locations of the startRef, endRef.
1795 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1796 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1797 // Comment out the protocol references.
1798 InsertText(LessLoc, "/*", 2);
1799 InsertText(GreaterLoc, "*/", 2);
1800 }
1801 }
1802}
1803
Steve Naroffb29b4272008-04-14 22:03:09 +00001804void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001805 SourceLocation Loc;
1806 QualType Type;
1807 const FunctionTypeProto *proto = 0;
1808 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1809 Loc = VD->getLocation();
1810 Type = VD->getType();
1811 }
1812 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1813 Loc = FD->getLocation();
1814 // Check for ObjC 'id' and class types that have been adorned with protocol
1815 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1816 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1817 assert(funcType && "missing function type");
1818 proto = dyn_cast<FunctionTypeProto>(funcType);
1819 if (!proto)
1820 return;
1821 Type = proto->getResultType();
1822 }
1823 else
1824 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001825
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001826 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001827 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001828
1829 const char *endBuf = SM->getCharacterData(Loc);
1830 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001831 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001832 startBuf--; // scan backward (from the decl location) for return type.
1833 const char *startRef = 0, *endRef = 0;
1834 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1835 // Get the locations of the startRef, endRef.
1836 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1837 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1838 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001839 InsertText(LessLoc, "/*", 2);
1840 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001841 }
1842 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001843 if (!proto)
1844 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001845 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001846 const char *startBuf = SM->getCharacterData(Loc);
1847 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001848 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1849 if (needToScanForQualifiers(proto->getArgType(i))) {
1850 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001851
Steve Naroffd5255f52007-11-01 13:24:47 +00001852 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001853 // scan forward (from the decl location) for argument types.
1854 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001855 const char *startRef = 0, *endRef = 0;
1856 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1857 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001858 SourceLocation LessLoc =
1859 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1860 SourceLocation GreaterLoc =
1861 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001862 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001863 InsertText(LessLoc, "/*", 2);
1864 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001865 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001866 startBuf = ++endBuf;
1867 }
1868 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001869 // If the function name is derived from a macro expansion, then the
1870 // argument buffer will not follow the name. Need to speak with Chris.
1871 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001872 startBuf++; // scan forward (from the decl location) for argument types.
1873 startBuf++;
1874 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001875 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001876}
1877
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001878// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001879void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001880 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1881 llvm::SmallVector<QualType, 16> ArgTys;
1882 ArgTys.push_back(Context->getPointerType(
1883 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001885 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001886 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001887 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001888 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001889 SelGetUidIdent, getFuncType,
1890 FunctionDecl::Extern, false, 0);
1891}
1892
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001893// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001894void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001895 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1896 llvm::SmallVector<QualType, 16> ArgTys;
1897 ArgTys.push_back(Context->getPointerType(
1898 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001899 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001900 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001901 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001902 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001903 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001904 SelGetProtoIdent, getFuncType,
1905 FunctionDecl::Extern, false, 0);
1906}
1907
Steve Naroffb29b4272008-04-14 22:03:09 +00001908void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001909 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001910 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001911 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001912 return;
1913 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001915}
1916
Steve Naroffc0a123c2008-03-11 17:37:02 +00001917// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001918void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001919 if (SuperContructorFunctionDecl)
1920 return;
1921 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1922 llvm::SmallVector<QualType, 16> ArgTys;
1923 QualType argT = Context->getObjCIdType();
1924 assert(!argT.isNull() && "Can't find 'id' type");
1925 ArgTys.push_back(argT);
1926 ArgTys.push_back(argT);
1927 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1928 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001929 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001930 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001931 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001932 msgSendIdent, msgSendType,
1933 FunctionDecl::Extern, false, 0);
1934}
1935
Steve Naroff09b266e2007-10-30 23:14:51 +00001936// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001937void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001938 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1939 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001940 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001941 assert(!argT.isNull() && "Can't find 'id' type");
1942 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001943 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001944 assert(!argT.isNull() && "Can't find 'SEL' type");
1945 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001946 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001947 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001948 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001949 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001950 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001951 msgSendIdent, msgSendType,
1952 FunctionDecl::Extern, false, 0);
1953}
1954
Steve Naroff874e2322007-11-15 10:28:18 +00001955// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001956void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001957 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1958 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001959 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001960 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001961 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001962 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1963 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1964 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001965 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001966 assert(!argT.isNull() && "Can't find 'SEL' type");
1967 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001968 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001969 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001970 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001971 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001972 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001973 msgSendIdent, msgSendType,
1974 FunctionDecl::Extern, false, 0);
1975}
1976
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001977// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001978void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001979 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1980 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001981 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001982 assert(!argT.isNull() && "Can't find 'id' type");
1983 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001985 assert(!argT.isNull() && "Can't find 'SEL' type");
1986 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001988 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001989 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001990 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001991 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001992 msgSendIdent, msgSendType,
1993 FunctionDecl::Extern, false, 0);
1994}
1995
1996// SynthMsgSendSuperStretFunctionDecl -
1997// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001998void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001999 IdentifierInfo *msgSendIdent =
2000 &Context->Idents.get("objc_msgSendSuper_stret");
2001 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002002 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002003 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002004 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002005 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2006 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2007 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002009 assert(!argT.isNull() && "Can't find 'SEL' type");
2010 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002011 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002012 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002013 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002014 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002015 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002016 msgSendIdent, msgSendType,
2017 FunctionDecl::Extern, false, 0);
2018}
2019
Steve Naroff1284db82008-05-08 22:02:18 +00002020// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002021void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002022 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2023 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002025 assert(!argT.isNull() && "Can't find 'id' type");
2026 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002028 assert(!argT.isNull() && "Can't find 'SEL' type");
2029 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002030 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002031 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002032 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002033 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002034 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002035 msgSendIdent, msgSendType,
2036 FunctionDecl::Extern, false, 0);
2037}
2038
Steve Naroff09b266e2007-10-30 23:14:51 +00002039// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002040void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002041 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2042 llvm::SmallVector<QualType, 16> ArgTys;
2043 ArgTys.push_back(Context->getPointerType(
2044 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002046 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002047 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002048 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002049 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002050 getClassIdent, getClassType,
2051 FunctionDecl::Extern, false, 0);
2052}
2053
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002054// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002055void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002056 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2057 llvm::SmallVector<QualType, 16> ArgTys;
2058 ArgTys.push_back(Context->getPointerType(
2059 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002061 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002062 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002063 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002064 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002065 getClassIdent, getClassType,
2066 FunctionDecl::Extern, false, 0);
2067}
2068
Steve Naroffb29b4272008-04-14 22:03:09 +00002069Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002070 QualType strType = getConstantStringStructType();
2071
2072 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002073
2074 std::string tmpName = InFileName;
2075 unsigned i;
2076 for (i=0; i < tmpName.length(); i++) {
2077 char c = tmpName.at(i);
2078 // replace any non alphanumeric characters with '_'.
2079 if (!isalpha(c) && (c < '0' || c > '9'))
2080 tmpName[i] = '_';
2081 }
2082 S += tmpName;
2083 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002084 S += utostr(NumObjCStringLiterals++);
2085
Steve Naroffba92b2e2008-03-27 22:29:16 +00002086 Preamble += "static __NSConstantStringImpl " + S;
2087 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2088 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002089 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002090 std::string prettyBufS;
2091 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002092 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002093 Preamble += prettyBuf.str();
2094 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002095 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002096 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002097
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002098 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002099 &Context->Idents.get(S.c_str()), strType,
2100 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002101 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2102 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2103 Context->getPointerType(DRE->getType()),
2104 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002105 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002106 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002107 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002108 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002109 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002110 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002111}
2112
Steve Naroffb29b4272008-04-14 22:03:09 +00002113ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002114 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002115 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002116
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002117 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2118 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002119 assert(PT);
2120 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2121 return IT->getDecl();
2122 }
2123 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002124}
2125
2126// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002127QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002128 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002129 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002130 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002131 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002132 QualType FieldTypes[2];
2133
2134 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002135 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002136 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002137 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002138 // Create fields
2139 FieldDecl *FieldDecls[2];
2140
2141 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002142 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002143 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002144
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002145 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002146 }
2147 return Context->getTagDeclType(SuperStructDecl);
2148}
2149
Steve Naroffb29b4272008-04-14 22:03:09 +00002150QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002151 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002152 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002153 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002154 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002155 QualType FieldTypes[4];
2156
2157 // struct objc_object *receiver;
2158 FieldTypes[0] = Context->getObjCIdType();
2159 // int flags;
2160 FieldTypes[1] = Context->IntTy;
2161 // char *str;
2162 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2163 // long length;
2164 FieldTypes[3] = Context->LongTy;
2165 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002166 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002167
2168 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002169 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002170 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002171
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002172 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002173 }
2174 return Context->getTagDeclType(ConstantStringDecl);
2175}
2176
Steve Naroffb29b4272008-04-14 22:03:09 +00002177Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002178 if (!SelGetUidFunctionDecl)
2179 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002180 if (!MsgSendFunctionDecl)
2181 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002182 if (!MsgSendSuperFunctionDecl)
2183 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002184 if (!MsgSendStretFunctionDecl)
2185 SynthMsgSendStretFunctionDecl();
2186 if (!MsgSendSuperStretFunctionDecl)
2187 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002188 if (!MsgSendFpretFunctionDecl)
2189 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002190 if (!GetClassFunctionDecl)
2191 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002192 if (!GetMetaClassFunctionDecl)
2193 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002194
Steve Naroff874e2322007-11-15 10:28:18 +00002195 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002196 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2197 // May need to use objc_msgSend_stret() as well.
2198 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002199 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002200 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002201 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002202 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002203 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002204 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002205 }
Steve Naroff874e2322007-11-15 10:28:18 +00002206
Steve Naroff934f2762007-10-24 22:48:43 +00002207 // Synthesize a call to objc_msgSend().
2208 llvm::SmallVector<Expr*, 8> MsgExprs;
2209 IdentifierInfo *clsName = Exp->getClassName();
2210
2211 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2212 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002213 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2214 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002215 if (!strcmp(clsName->getName(), "super")) {
2216 MsgSendFlavor = MsgSendSuperFunctionDecl;
2217 if (MsgSendStretFlavor)
2218 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2219 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2220
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002221 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002222 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002223
2224 llvm::SmallVector<Expr*, 4> InitExprs;
2225
2226 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002227 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002228 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002229 Context->getObjCIdType(),
2230 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002231 llvm::SmallVector<Expr*, 8> ClsExprs;
2232 QualType argType = Context->getPointerType(Context->CharTy);
2233 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2234 SuperDecl->getIdentifier()->getLength(),
2235 false, argType, SourceLocation(),
2236 SourceLocation()));
2237 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2238 &ClsExprs[0],
2239 ClsExprs.size());
2240 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002241 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002242 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002243 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002244 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002245 // struct objc_super
2246 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002247 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002248
Steve Naroff23f41272008-03-11 18:14:26 +00002249 if (LangOpts.Microsoft) {
2250 SynthSuperContructorFunctionDecl();
2251 // Simulate a contructor call...
2252 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2253 superType, SourceLocation());
2254 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2255 superType, SourceLocation());
2256 } else {
2257 // (struct objc_super) { <exprs from above> }
2258 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2259 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002260 SourceLocation(), false);
2261 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2262 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002263 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002264 // struct objc_super *
2265 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2266 Context->getPointerType(SuperRep->getType()),
2267 SourceLocation());
2268 MsgExprs.push_back(Unop);
2269 } else {
2270 llvm::SmallVector<Expr*, 8> ClsExprs;
2271 QualType argType = Context->getPointerType(Context->CharTy);
2272 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2273 clsName->getLength(),
2274 false, argType, SourceLocation(),
2275 SourceLocation()));
2276 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2277 &ClsExprs[0],
2278 ClsExprs.size());
2279 MsgExprs.push_back(Cls);
2280 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002281 } else { // instance message.
2282 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002283
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002284 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002285 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002286 if (MsgSendStretFlavor)
2287 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002288 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2289
2290 llvm::SmallVector<Expr*, 4> InitExprs;
2291
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002292 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002293 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002294 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002295 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002296 SourceLocation()),
2297 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002298 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002299
2300 llvm::SmallVector<Expr*, 8> ClsExprs;
2301 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002302 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2303 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002304 false, argType, SourceLocation(),
2305 SourceLocation()));
2306 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002307 &ClsExprs[0],
2308 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002309 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002310 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002311 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002312 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002313 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002314 // struct objc_super
2315 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002316 Expr *SuperRep;
2317
2318 if (LangOpts.Microsoft) {
2319 SynthSuperContructorFunctionDecl();
2320 // Simulate a contructor call...
2321 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2322 superType, SourceLocation());
2323 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2324 superType, SourceLocation());
2325 } else {
2326 // (struct objc_super) { <exprs from above> }
2327 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2328 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002329 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002330 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2331 }
Steve Naroff874e2322007-11-15 10:28:18 +00002332 // struct objc_super *
2333 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2334 Context->getPointerType(SuperRep->getType()),
2335 SourceLocation());
2336 MsgExprs.push_back(Unop);
2337 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002338 // Remove all type-casts because it may contain objc-style types; e.g.
2339 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002340 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002341 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002342 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002343 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002344 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002345 MsgExprs.push_back(recExpr);
2346 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002347 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002348 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002349 llvm::SmallVector<Expr*, 8> SelExprs;
2350 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002351 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2352 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002353 false, argType, SourceLocation(),
2354 SourceLocation()));
2355 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2356 &SelExprs[0], SelExprs.size());
2357 MsgExprs.push_back(SelExp);
2358
2359 // Now push any user supplied arguments.
2360 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002361 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002362 // Make all implicit casts explicit...ICE comes in handy:-)
2363 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2364 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002365 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002366 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002367 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002368 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002369 }
2370 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002371 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002372 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002373 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002374 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002375 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002376 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002377 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002378 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002379 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002380 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002381 // We've transferred the ownership to MsgExprs. Null out the argument in
2382 // the original expression, since we will delete it below.
2383 Exp->setArg(i, 0);
2384 }
Steve Naroffab972d32007-11-04 22:37:50 +00002385 // Generate the funky cast.
2386 CastExpr *cast;
2387 llvm::SmallVector<QualType, 8> ArgTypes;
2388 QualType returnType;
2389
2390 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002391 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2392 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2393 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002394 ArgTypes.push_back(Context->getObjCIdType());
2395 ArgTypes.push_back(Context->getObjCSelType());
2396 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002397 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002398 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002399 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2400 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002401 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002402 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2403 if (isBlockPointerType(t)) {
2404 const BlockPointerType *BPT = t->getAsBlockPointerType();
2405 t = Context->getPointerType(BPT->getPointeeType());
2406 }
Steve Naroff352336b2007-11-05 14:36:37 +00002407 ArgTypes.push_back(t);
2408 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2410 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002411 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002413 }
2414 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002415 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002416
2417 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2419 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002420
2421 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2422 // If we don't do this cast, we get the following bizarre warning/note:
2423 // xx.m:13: warning: function called through a non-compatible type
2424 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002425 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002426 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002427 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002428
Steve Naroffab972d32007-11-04 22:37:50 +00002429 // Now do the "normal" pointer to function cast.
2430 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002431 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002432 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002433 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002434 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002435 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002436
2437 // Don't forget the parens to enforce the proper binding.
2438 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2439
2440 const FunctionType *FT = msgSendType->getAsFunctionType();
2441 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2442 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002443 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 if (MsgSendStretFlavor) {
2445 // We have the method which returns a struct/union. Must also generate
2446 // call to objc_msgSend_stret and hang both varieties on a conditional
2447 // expression which dictate which one to envoke depending on size of
2448 // method's return type.
2449
2450 // Create a reference to the objc_msgSend_stret() declaration.
2451 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2452 SourceLocation());
2453 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002454 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002455 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002456 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457 // Now do the "normal" pointer to function cast.
2458 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002459 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002460 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002461 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002462 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002463
2464 // Don't forget the parens to enforce the proper binding.
2465 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2466
2467 FT = msgSendType->getAsFunctionType();
2468 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2469 FT->getResultType(), SourceLocation());
2470
2471 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002472 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2473 returnType.getAsOpaquePtr(),
2474 Context->getSizeType(),
2475 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002476 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2477 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2478 // For X86 it is more complicated and some kind of target specific routine
2479 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002480 unsigned IntSize =
2481 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002482 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2483 Context->IntTy,
2484 SourceLocation());
2485 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2486 BinaryOperator::LE,
2487 Context->IntTy,
2488 SourceLocation());
2489 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2490 ConditionalOperator *CondExpr =
2491 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002492 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002493 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002494 return ReplacingStmt;
2495}
2496
Steve Naroffb29b4272008-04-14 22:03:09 +00002497Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002498 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002499
Steve Naroffc77a6362008-12-04 16:24:46 +00002500 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002501 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002502 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002503
Steve Naroff4c3580e2008-12-04 23:50:32 +00002504 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002505 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002506}
2507
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002508/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2509/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002510Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002511 if (!GetProtocolFunctionDecl)
2512 SynthGetProtocolFunctionDecl();
2513 // Create a call to objc_getProtocol("ProtocolName").
2514 llvm::SmallVector<Expr*, 8> ProtoExprs;
2515 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002516 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2517 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002518 false, argType, SourceLocation(),
2519 SourceLocation()));
2520 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2521 &ProtoExprs[0],
2522 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002523 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002524 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002525 return ProtoExp;
2526
2527}
2528
Steve Naroffbaf58c32008-05-31 14:15:04 +00002529bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2530 const char *endBuf) {
2531 while (startBuf < endBuf) {
2532 if (*startBuf == '#') {
2533 // Skip whitespace.
2534 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2535 ;
2536 if (!strncmp(startBuf, "if", strlen("if")) ||
2537 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2538 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2539 !strncmp(startBuf, "define", strlen("define")) ||
2540 !strncmp(startBuf, "undef", strlen("undef")) ||
2541 !strncmp(startBuf, "else", strlen("else")) ||
2542 !strncmp(startBuf, "elif", strlen("elif")) ||
2543 !strncmp(startBuf, "endif", strlen("endif")) ||
2544 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2545 !strncmp(startBuf, "include", strlen("include")) ||
2546 !strncmp(startBuf, "import", strlen("import")) ||
2547 !strncmp(startBuf, "include_next", strlen("include_next")))
2548 return true;
2549 }
2550 startBuf++;
2551 }
2552 return false;
2553}
2554
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002556/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002557void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002558 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002559 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002560 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002561 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002562 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002564 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002566 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002567 SourceLocation LocStart = CDecl->getLocStart();
2568 SourceLocation LocEnd = CDecl->getLocEnd();
2569
2570 const char *startBuf = SM->getCharacterData(LocStart);
2571 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002572
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002573 // If no ivars and no root or if its root, directly or indirectly,
2574 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002575 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2576 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002577 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002578 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002579 return;
2580 }
2581
2582 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002583 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002584 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002585 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002586 if (LangOpts.Microsoft)
2587 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002588
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002589 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002590 const char *cursor = strchr(startBuf, '{');
2591 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002593 // If the buffer contains preprocessor directives, we do more fine-grained
2594 // rewrites. This is intended to fix code that looks like (which occurs in
2595 // NSURL.h, for example):
2596 //
2597 // #ifdef XYZ
2598 // @interface Foo : NSObject
2599 // #else
2600 // @interface FooBar : NSObject
2601 // #endif
2602 // {
2603 // int i;
2604 // }
2605 // @end
2606 //
2607 // This clause is segregated to avoid breaking the common case.
2608 if (BufferContainsPPDirectives(startBuf, cursor)) {
2609 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2610 CDecl->getClassLoc();
2611 const char *endHeader = SM->getCharacterData(L);
2612 endHeader += Lexer::MeasureTokenLength(L, *SM);
2613
Chris Lattner3db6cae2008-07-21 18:19:38 +00002614 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002615 // advance to the end of the referenced protocols.
2616 while (endHeader < cursor && *endHeader != '>') endHeader++;
2617 endHeader++;
2618 }
2619 // rewrite the original header
2620 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2621 } else {
2622 // rewrite the original header *without* disturbing the '{'
2623 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2624 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002625 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002626 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002627 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002628 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002629 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002630 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002631
2632 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002633 SourceLocation OnePastCurly =
2634 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2635 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002636 }
2637 cursor++; // past '{'
2638
2639 // Now comment out any visibility specifiers.
2640 while (cursor < endBuf) {
2641 if (*cursor == '@') {
2642 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002643 // Skip whitespace.
2644 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2645 /*scan*/;
2646
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002647 // FIXME: presence of @public, etc. inside comment results in
2648 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002649 if (!strncmp(cursor, "public", strlen("public")) ||
2650 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002651 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002652 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002653 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002654 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002655 // FIXME: If there are cases where '<' is used in ivar declaration part
2656 // of user code, then scan the ivar list and use needToScanForQualifiers
2657 // for type checking.
2658 else if (*cursor == '<') {
2659 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002660 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002661 cursor = strchr(cursor, '>');
2662 cursor++;
2663 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002664 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002665 } else if (*cursor == '^') { // rewrite block specifier.
2666 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2667 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002668 }
Steve Narofffea763e82007-11-14 19:25:57 +00002669 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002670 }
Steve Narofffea763e82007-11-14 19:25:57 +00002671 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002672 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002673 } else { // we don't have any instance variables - insert super struct.
2674 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2675 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002676 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002677 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002678 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002679 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002680 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002681 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002682 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002683 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002684 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002685}
2686
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002687// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002688/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002689void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002690 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002691 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002692 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002693 const char *ClassName,
2694 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002695 if (MethodBegin == MethodEnd) return;
2696
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002697 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002698 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002699 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002700 SEL _cmd;
2701 char *method_types;
2702 void *_imp;
2703 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002704 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002705 Result += "\nstruct _objc_method {\n";
2706 Result += "\tSEL _cmd;\n";
2707 Result += "\tchar *method_types;\n";
2708 Result += "\tvoid *_imp;\n";
2709 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002710
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002711 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002712 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002713
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002714 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002715
2716 /* struct {
2717 struct _objc_method_list *next_method;
2718 int method_count;
2719 struct _objc_method method_list[];
2720 }
2721 */
2722 Result += "\nstatic struct {\n";
2723 Result += "\tstruct _objc_method_list *next_method;\n";
2724 Result += "\tint method_count;\n";
2725 Result += "\tstruct _objc_method method_list[";
2726 Result += utostr(MethodEnd-MethodBegin);
2727 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002728 Result += prefix;
2729 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2730 Result += "_METHODS_";
2731 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002732 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002733 Result += IsInstanceMethod ? "inst" : "cls";
2734 Result += "_meth\")))= ";
2735 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002736
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002737 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002738 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002739 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002740 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002741 Result += "\", \"";
2742 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002743 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002744 Result += MethodInternalNames[*MethodBegin];
2745 Result += "}\n";
2746 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2747 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002748 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002749 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002750 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002751 Result += "\", \"";
2752 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002753 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002754 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002755 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002756 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002757 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002758}
2759
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002760/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002761void RewriteObjC::
2762RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2763 const char *prefix,
2764 const char *ClassName,
2765 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002766 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002767 if (Protocols.empty()) return;
2768
2769 for (unsigned i = 0; i != Protocols.size(); i++) {
2770 ObjCProtocolDecl *PDecl = Protocols[i];
2771 // Output struct protocol_methods holder of method selector and type.
2772 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2773 /* struct protocol_methods {
2774 SEL _cmd;
2775 char *method_types;
2776 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002777 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002778 Result += "\nstruct protocol_methods {\n";
2779 Result += "\tSEL _cmd;\n";
2780 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002781 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002782
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002783 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002784 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002785 // Do not synthesize the protocol more than once.
2786 if (ObjCSynthesizedProtocols.count(PDecl))
2787 continue;
2788
2789 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2790 unsigned NumMethods = PDecl->getNumInstanceMethods();
2791 /* struct _objc_protocol_method_list {
2792 int protocol_method_count;
2793 struct protocol_methods protocols[];
2794 }
2795 */
2796 Result += "\nstatic struct {\n";
2797 Result += "\tint protocol_method_count;\n";
2798 Result += "\tstruct protocol_methods protocols[";
2799 Result += utostr(NumMethods);
2800 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002801 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002802 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2803 "{\n\t" + utostr(NumMethods) + "\n";
2804
2805 // Output instance methods declared in this protocol.
2806 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2807 E = PDecl->instmeth_end(); I != E; ++I) {
2808 if (I == PDecl->instmeth_begin())
2809 Result += "\t ,{{(SEL)\"";
2810 else
2811 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002812 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002813 std::string MethodTypeString;
2814 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2815 Result += "\", \"";
2816 Result += MethodTypeString;
2817 Result += "\"}\n";
2818 }
2819 Result += "\t }\n};\n";
2820 }
2821
2822 // Output class methods declared in this protocol.
2823 int NumMethods = PDecl->getNumClassMethods();
2824 if (NumMethods > 0) {
2825 /* struct _objc_protocol_method_list {
2826 int protocol_method_count;
2827 struct protocol_methods protocols[];
2828 }
2829 */
2830 Result += "\nstatic struct {\n";
2831 Result += "\tint protocol_method_count;\n";
2832 Result += "\tstruct protocol_methods protocols[";
2833 Result += utostr(NumMethods);
2834 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002835 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002836 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2837 "{\n\t";
2838 Result += utostr(NumMethods);
2839 Result += "\n";
2840
2841 // Output instance methods declared in this protocol.
2842 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2843 E = PDecl->classmeth_end(); I != E; ++I) {
2844 if (I == PDecl->classmeth_begin())
2845 Result += "\t ,{{(SEL)\"";
2846 else
2847 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002848 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002849 std::string MethodTypeString;
2850 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2851 Result += "\", \"";
2852 Result += MethodTypeString;
2853 Result += "\"}\n";
2854 }
2855 Result += "\t }\n};\n";
2856 }
2857
2858 // Output:
2859 /* struct _objc_protocol {
2860 // Objective-C 1.0 extensions
2861 struct _objc_protocol_extension *isa;
2862 char *protocol_name;
2863 struct _objc_protocol **protocol_list;
2864 struct _objc_protocol_method_list *instance_methods;
2865 struct _objc_protocol_method_list *class_methods;
2866 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002867 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002868 static bool objc_protocol = false;
2869 if (!objc_protocol) {
2870 Result += "\nstruct _objc_protocol {\n";
2871 Result += "\tstruct _objc_protocol_extension *isa;\n";
2872 Result += "\tchar *protocol_name;\n";
2873 Result += "\tstruct _objc_protocol **protocol_list;\n";
2874 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2875 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2876 Result += "};\n";
2877
2878 objc_protocol = true;
2879 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002881 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002882 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002883 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2884 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002885 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002886 Result += "\", 0, ";
2887 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2888 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002889 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002890 Result += ", ";
2891 }
2892 else
2893 Result += "0, ";
2894 if (PDecl->getNumClassMethods() > 0) {
2895 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002896 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002898 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002899 else
2900 Result += "0\n";
2901 Result += "};\n";
2902
2903 // Mark this protocol as having been generated.
2904 if (!ObjCSynthesizedProtocols.insert(PDecl))
2905 assert(false && "protocol already synthesized");
2906 }
2907 // Output the top lovel protocol meta-data for the class.
2908 /* struct _objc_protocol_list {
2909 struct _objc_protocol_list *next;
2910 int protocol_count;
2911 struct _objc_protocol *class_protocols[];
2912 }
2913 */
2914 Result += "\nstatic struct {\n";
2915 Result += "\tstruct _objc_protocol_list *next;\n";
2916 Result += "\tint protocol_count;\n";
2917 Result += "\tstruct _objc_protocol *class_protocols[";
2918 Result += utostr(Protocols.size());
2919 Result += "];\n} _OBJC_";
2920 Result += prefix;
2921 Result += "_PROTOCOLS_";
2922 Result += ClassName;
2923 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2924 "{\n\t0, ";
2925 Result += utostr(Protocols.size());
2926 Result += "\n";
2927
2928 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002929 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002930 Result += " \n";
2931
2932 for (unsigned i = 1; i != Protocols.size(); i++) {
2933 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002934 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002935 Result += "\n";
2936 }
2937 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002938}
2939
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002940/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002941/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002942void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002944 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002945 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002946 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002947 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2948 CDecl = CDecl->getNextClassCategory())
2949 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2950 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002951
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002952 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002953 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002954 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002955
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002956 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002957 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002958 true, "CATEGORY_", FullCategoryName.c_str(),
2959 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002960
2961 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002962 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002963 false, "CATEGORY_", FullCategoryName.c_str(),
2964 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002965
2966 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002967 // Null CDecl is case of a category implementation with no category interface
2968 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002969 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002970 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002971
2972 /* struct _objc_category {
2973 char *category_name;
2974 char *class_name;
2975 struct _objc_method_list *instance_methods;
2976 struct _objc_method_list *class_methods;
2977 struct _objc_protocol_list *protocols;
2978 // Objective-C 1.0 extensions
2979 uint32_t size; // sizeof (struct _objc_category)
2980 struct _objc_property_list *instance_properties; // category's own
2981 // @property decl.
2982 };
2983 */
2984
2985 static bool objc_category = false;
2986 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002987 Result += "\nstruct _objc_category {\n";
2988 Result += "\tchar *category_name;\n";
2989 Result += "\tchar *class_name;\n";
2990 Result += "\tstruct _objc_method_list *instance_methods;\n";
2991 Result += "\tstruct _objc_method_list *class_methods;\n";
2992 Result += "\tstruct _objc_protocol_list *protocols;\n";
2993 Result += "\tunsigned int size;\n";
2994 Result += "\tstruct _objc_property_list *instance_properties;\n";
2995 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002996 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002997 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002998 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2999 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003000 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003003 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003004 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003005
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003006 if (IDecl->getNumInstanceMethods() > 0) {
3007 Result += "\t, (struct _objc_method_list *)"
3008 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3009 Result += FullCategoryName;
3010 Result += "\n";
3011 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003012 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003013 Result += "\t, 0\n";
3014 if (IDecl->getNumClassMethods() > 0) {
3015 Result += "\t, (struct _objc_method_list *)"
3016 "&_OBJC_CATEGORY_CLASS_METHODS_";
3017 Result += FullCategoryName;
3018 Result += "\n";
3019 }
3020 else
3021 Result += "\t, 0\n";
3022
Chris Lattner780f3292008-07-21 21:32:27 +00003023 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003024 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3025 Result += FullCategoryName;
3026 Result += "\n";
3027 }
3028 else
3029 Result += "\t, 0\n";
3030 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003031}
3032
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003033/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3034/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003035void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003036 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003037 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003038 if (ivar->isBitField()) {
3039 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3040 // place all bitfields at offset 0.
3041 Result += "0";
3042 } else {
3043 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003044 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003045 if (LangOpts.Microsoft)
3046 Result += "_IMPL";
3047 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003048 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003049 Result += ")";
3050 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003051}
3052
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003053//===----------------------------------------------------------------------===//
3054// Meta Data Emission
3055//===----------------------------------------------------------------------===//
3056
Steve Naroffb29b4272008-04-14 22:03:09 +00003057void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003058 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003059 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003060
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003061 // Explictly declared @interface's are already synthesized.
3062 if (CDecl->ImplicitInterfaceDecl()) {
3063 // FIXME: Implementation of a class with no @interface (legacy) doese not
3064 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003065 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003066 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003067
Chris Lattnerbe6df082007-12-12 07:56:42 +00003068 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003069 unsigned NumIvars = !IDecl->ivar_empty()
3070 ? IDecl->ivar_size()
3071 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003072 if (NumIvars > 0) {
3073 static bool objc_ivar = false;
3074 if (!objc_ivar) {
3075 /* struct _objc_ivar {
3076 char *ivar_name;
3077 char *ivar_type;
3078 int ivar_offset;
3079 };
3080 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003081 Result += "\nstruct _objc_ivar {\n";
3082 Result += "\tchar *ivar_name;\n";
3083 Result += "\tchar *ivar_type;\n";
3084 Result += "\tint ivar_offset;\n";
3085 Result += "};\n";
3086
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003087 objc_ivar = true;
3088 }
3089
Steve Naroff946a6932008-03-11 00:12:29 +00003090 /* struct {
3091 int ivar_count;
3092 struct _objc_ivar ivar_list[nIvars];
3093 };
3094 */
3095 Result += "\nstatic struct {\n";
3096 Result += "\tint ivar_count;\n";
3097 Result += "\tstruct _objc_ivar ivar_list[";
3098 Result += utostr(NumIvars);
3099 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003100 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003101 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003102 "{\n\t";
3103 Result += utostr(NumIvars);
3104 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003105
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003106 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003107 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003108 IVI = IDecl->ivar_begin();
3109 IVE = IDecl->ivar_end();
3110 } else {
3111 IVI = CDecl->ivar_begin();
3112 IVE = CDecl->ivar_end();
3113 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003114 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003115 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003116 Result += "\", \"";
3117 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003118 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003119 Result += StrEncoding;
3120 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003121 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003122 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003123 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003124 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003125 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003126 Result += "\", \"";
3127 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003128 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003129 Result += StrEncoding;
3130 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003131 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003132 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003133 }
3134
3135 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003136 }
3137
3138 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003139 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003140 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003141
3142 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003143 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003144 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003145
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003146 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003147 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003148 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003149
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003150
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003151 // Declaration of class/meta-class metadata
3152 /* struct _objc_class {
3153 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003154 const char *super_class_name;
3155 char *name;
3156 long version;
3157 long info;
3158 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003159 struct _objc_ivar_list *ivars;
3160 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003161 struct objc_cache *cache;
3162 struct objc_protocol_list *protocols;
3163 const char *ivar_layout;
3164 struct _objc_class_ext *ext;
3165 };
3166 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003167 static bool objc_class = false;
3168 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003169 Result += "\nstruct _objc_class {\n";
3170 Result += "\tstruct _objc_class *isa;\n";
3171 Result += "\tconst char *super_class_name;\n";
3172 Result += "\tchar *name;\n";
3173 Result += "\tlong version;\n";
3174 Result += "\tlong info;\n";
3175 Result += "\tlong instance_size;\n";
3176 Result += "\tstruct _objc_ivar_list *ivars;\n";
3177 Result += "\tstruct _objc_method_list *methods;\n";
3178 Result += "\tstruct objc_cache *cache;\n";
3179 Result += "\tstruct _objc_protocol_list *protocols;\n";
3180 Result += "\tconst char *ivar_layout;\n";
3181 Result += "\tstruct _objc_class_ext *ext;\n";
3182 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003183 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003184 }
3185
3186 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003187 ObjCInterfaceDecl *RootClass = 0;
3188 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003189 while (SuperClass) {
3190 RootClass = SuperClass;
3191 SuperClass = SuperClass->getSuperClass();
3192 }
3193 SuperClass = CDecl->getSuperClass();
3194
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003195 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003196 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003197 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003200 Result += "\"";
3201
3202 if (SuperClass) {
3203 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003206 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 Result += "\"";
3208 }
3209 else {
3210 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003211 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003212 Result += "\"";
3213 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003215 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003216 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003217 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003218 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003219 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003220 Result += "\n";
3221 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003222 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003223 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003224 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003225 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003226 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003227 Result += ",0,0\n";
3228 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003229 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003230 Result += "\t,0,0,0,0\n";
3231 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003232
3233 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003234 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003235 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003236 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003237 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003239 if (SuperClass) {
3240 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003242 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003243 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003244 Result += "\"";
3245 }
3246 else {
3247 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003248 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003249 Result += "\"";
3250 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003251 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003252 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003253 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003254 Result += ",0";
3255 else {
3256 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003257 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003258 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003259 if (LangOpts.Microsoft)
3260 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003261 Result += ")";
3262 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003264 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003265 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003266 Result += "\n\t";
3267 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003268 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003269 Result += ",0";
3270 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003271 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003272 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 Result += ", 0\n\t";
3274 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003275 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003277 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003278 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 Result += ", 0,0\n";
3281 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003282 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += ",0,0,0\n";
3284 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003285}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003286
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003287/// RewriteImplementations - This routine rewrites all method implementations
3288/// and emits meta-data.
3289
Steve Narofface66252008-11-13 20:07:04 +00003290void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003291 int ClsDefCount = ClassImplementation.size();
3292 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003293
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003294 // Rewrite implemented methods
3295 for (int i = 0; i < ClsDefCount; i++)
3296 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003297
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003298 for (int i = 0; i < CatDefCount; i++)
3299 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003300}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003301
Steve Narofface66252008-11-13 20:07:04 +00003302void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3303 int ClsDefCount = ClassImplementation.size();
3304 int CatDefCount = CategoryImplementation.size();
3305
Steve Naroff5df5b762008-05-07 21:23:49 +00003306 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003307 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003308 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003309 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003310 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003311
3312 // For each implemented category, write out all its meta data.
3313 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003314 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003315
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003316 // Write objc_symtab metadata
3317 /*
3318 struct _objc_symtab
3319 {
3320 long sel_ref_cnt;
3321 SEL *refs;
3322 short cls_def_cnt;
3323 short cat_def_cnt;
3324 void *defs[cls_def_cnt + cat_def_cnt];
3325 };
3326 */
3327
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += "\nstruct _objc_symtab {\n";
3329 Result += "\tlong sel_ref_cnt;\n";
3330 Result += "\tSEL *refs;\n";
3331 Result += "\tshort cls_def_cnt;\n";
3332 Result += "\tshort cat_def_cnt;\n";
3333 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3334 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003335
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003336 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003337 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003338 Result += "\t0, 0, " + utostr(ClsDefCount)
3339 + ", " + utostr(CatDefCount) + "\n";
3340 for (int i = 0; i < ClsDefCount; i++) {
3341 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003342 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003343 Result += "\n";
3344 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003345
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003346 for (int i = 0; i < CatDefCount; i++) {
3347 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003348 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003349 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003350 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003351 Result += "\n";
3352 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003353
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003354 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003355
3356 // Write objc_module metadata
3357
3358 /*
3359 struct _objc_module {
3360 long version;
3361 long size;
3362 const char *name;
3363 struct _objc_symtab *symtab;
3364 }
3365 */
3366
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003367 Result += "\nstruct _objc_module {\n";
3368 Result += "\tlong version;\n";
3369 Result += "\tlong size;\n";
3370 Result += "\tconst char *name;\n";
3371 Result += "\tstruct _objc_symtab *symtab;\n";
3372 Result += "};\n\n";
3373 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003374 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003375 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3376 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003377 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003378
3379 if (LangOpts.Microsoft) {
3380 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003381 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003382 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3383 Result += "&_OBJC_MODULES;\n";
3384 Result += "#pragma data_seg(pop)\n\n";
3385 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003386}
Chris Lattner311ff022007-10-16 22:36:42 +00003387
Steve Naroff54055232008-10-27 17:20:55 +00003388std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3389 const char *funcName,
3390 std::string Tag) {
3391 const FunctionType *AFT = CE->getFunctionType();
3392 QualType RT = AFT->getResultType();
3393 std::string StructRef = "struct " + Tag;
3394 std::string S = "static " + RT.getAsString() + " __" +
3395 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003396
Steve Naroff54055232008-10-27 17:20:55 +00003397 BlockDecl *BD = CE->getBlockDecl();
3398
3399 if (isa<FunctionTypeNoProto>(AFT)) {
3400 S += "()";
3401 } else if (BD->param_empty()) {
3402 S += "(" + StructRef + " *__cself)";
3403 } else {
3404 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3405 assert(FT && "SynthesizeBlockFunc: No function proto");
3406 S += '(';
3407 // first add the implicit argument.
3408 S += StructRef + " *__cself, ";
3409 std::string ParamStr;
3410 for (BlockDecl::param_iterator AI = BD->param_begin(),
3411 E = BD->param_end(); AI != E; ++AI) {
3412 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003413 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003414 (*AI)->getType().getAsStringInternal(ParamStr);
3415 S += ParamStr;
3416 }
3417 if (FT->isVariadic()) {
3418 if (!BD->param_empty()) S += ", ";
3419 S += "...";
3420 }
3421 S += ')';
3422 }
3423 S += " {\n";
3424
3425 // Create local declarations to avoid rewriting all closure decl ref exprs.
3426 // First, emit a declaration for all "by ref" decls.
3427 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3428 E = BlockByRefDecls.end(); I != E; ++I) {
3429 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003430 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003431 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003433 }
3434 // Next, emit a declaration for all "by copy" declarations.
3435 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3436 E = BlockByCopyDecls.end(); I != E; ++I) {
3437 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003438 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003439 // Handle nested closure invocation. For example:
3440 //
3441 // void (^myImportedClosure)(void);
3442 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3443 //
3444 // void (^anotherClosure)(void);
3445 // anotherClosure = ^(void) {
3446 // myImportedClosure(); // import and invoke the closure
3447 // };
3448 //
3449 if (isBlockPointerType((*I)->getType()))
3450 S += "struct __block_impl *";
3451 else
3452 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003453 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003454 }
3455 std::string RewrittenStr = RewrittenBlockExprs[CE];
3456 const char *cstr = RewrittenStr.c_str();
3457 while (*cstr++ != '{') ;
3458 S += cstr;
3459 S += "\n";
3460 return S;
3461}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003462
Steve Naroff54055232008-10-27 17:20:55 +00003463std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3464 const char *funcName,
3465 std::string Tag) {
3466 std::string StructRef = "struct " + Tag;
3467 std::string S = "static void __";
3468
3469 S += funcName;
3470 S += "_block_copy_" + utostr(i);
3471 S += "(" + StructRef;
3472 S += "*dst, " + StructRef;
3473 S += "*src) {";
3474 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3475 E = ImportedBlockDecls.end(); I != E; ++I) {
3476 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003477 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003478 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003479 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003480 S += ");}";
3481 }
3482 S += "\nstatic void __";
3483 S += funcName;
3484 S += "_block_dispose_" + utostr(i);
3485 S += "(" + StructRef;
3486 S += "*src) {";
3487 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3488 E = ImportedBlockDecls.end(); I != E; ++I) {
3489 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003490 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003491 S += ");";
3492 }
3493 S += "}\n";
3494 return S;
3495}
3496
3497std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3498 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003499 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003500 std::string Constructor = " " + Tag;
3501
3502 S += " {\n struct __block_impl impl;\n";
3503
3504 if (hasCopyDisposeHelpers)
3505 S += " void *copy;\n void *dispose;\n";
3506
3507 Constructor += "(void *fp";
3508
3509 if (hasCopyDisposeHelpers)
3510 Constructor += ", void *copyHelp, void *disposeHelp";
3511
3512 if (BlockDeclRefs.size()) {
3513 // Output all "by copy" declarations.
3514 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3515 E = BlockByCopyDecls.end(); I != E; ++I) {
3516 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003517 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003518 std::string ArgName = "_" + FieldName;
3519 // Handle nested closure invocation. For example:
3520 //
3521 // void (^myImportedBlock)(void);
3522 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3523 //
3524 // void (^anotherBlock)(void);
3525 // anotherBlock = ^(void) {
3526 // myImportedBlock(); // import and invoke the closure
3527 // };
3528 //
3529 if (isBlockPointerType((*I)->getType())) {
3530 S += "struct __block_impl *";
3531 Constructor += ", void *" + ArgName;
3532 } else {
3533 (*I)->getType().getAsStringInternal(FieldName);
3534 (*I)->getType().getAsStringInternal(ArgName);
3535 Constructor += ", " + ArgName;
3536 }
3537 S += FieldName + ";\n";
3538 }
3539 // Output all "by ref" declarations.
3540 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3541 E = BlockByRefDecls.end(); I != E; ++I) {
3542 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003543 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003544 std::string ArgName = "_" + FieldName;
3545 // Handle nested closure invocation. For example:
3546 //
3547 // void (^myImportedBlock)(void);
3548 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3549 //
3550 // void (^anotherBlock)(void);
3551 // anotherBlock = ^(void) {
3552 // myImportedBlock(); // import and invoke the closure
3553 // };
3554 //
3555 if (isBlockPointerType((*I)->getType())) {
3556 S += "struct __block_impl *";
3557 Constructor += ", void *" + ArgName;
3558 } else {
3559 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3560 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3561 Constructor += ", " + ArgName;
3562 }
3563 S += FieldName + "; // by ref\n";
3564 }
3565 // Finish writing the constructor.
3566 // FIXME: handle NSConcreteGlobalBlock.
3567 Constructor += ", int flags=0) {\n";
3568 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3569 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3570
3571 if (hasCopyDisposeHelpers)
3572 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3573
3574 // Initialize all "by copy" arguments.
3575 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3576 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003578 Constructor += " ";
3579 if (isBlockPointerType((*I)->getType()))
3580 Constructor += Name + " = (struct __block_impl *)_";
3581 else
3582 Constructor += Name + " = _";
3583 Constructor += Name + ";\n";
3584 }
3585 // Initialize all "by ref" arguments.
3586 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3587 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003588 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003589 Constructor += " ";
3590 if (isBlockPointerType((*I)->getType()))
3591 Constructor += Name + " = (struct __block_impl *)_";
3592 else
3593 Constructor += Name + " = _";
3594 Constructor += Name + ";\n";
3595 }
3596 } else {
3597 // Finish writing the constructor.
3598 // FIXME: handle NSConcreteGlobalBlock.
3599 Constructor += ", int flags=0) {\n";
3600 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3601 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3602 if (hasCopyDisposeHelpers)
3603 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3604 }
3605 Constructor += " ";
3606 Constructor += "}\n";
3607 S += Constructor;
3608 S += "};\n";
3609 return S;
3610}
3611
3612void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3613 const char *FunName) {
3614 // Insert closures that were part of the function.
3615 for (unsigned i = 0; i < Blocks.size(); i++) {
3616
3617 CollectBlockDeclRefInfo(Blocks[i]);
3618
3619 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3620
3621 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3622 ImportedBlockDecls.size() > 0);
3623
3624 InsertText(FunLocStart, CI.c_str(), CI.size());
3625
3626 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3627
3628 InsertText(FunLocStart, CF.c_str(), CF.size());
3629
3630 if (ImportedBlockDecls.size()) {
3631 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3632 InsertText(FunLocStart, HF.c_str(), HF.size());
3633 }
3634
3635 BlockDeclRefs.clear();
3636 BlockByRefDecls.clear();
3637 BlockByCopyDecls.clear();
3638 BlockCallExprs.clear();
3639 ImportedBlockDecls.clear();
3640 }
3641 Blocks.clear();
3642 RewrittenBlockExprs.clear();
3643}
3644
3645void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3646 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003647 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003648
3649 SynthesizeBlockLiterals(FunLocStart, FuncName);
3650}
3651
3652void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003653 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3654 //SourceLocation FunLocStart = MD->getLocStart();
3655 // FIXME: This hack works around a bug in Rewrite.InsertText().
3656 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003657 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003658 // Convert colons to underscores.
3659 std::string::size_type loc = 0;
3660 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3661 FuncName.replace(loc, 1, "_");
3662
3663 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3664}
3665
3666void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3667 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3668 CI != E; ++CI)
3669 if (*CI) {
3670 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3671 GetBlockDeclRefExprs(CBE->getBody());
3672 else
3673 GetBlockDeclRefExprs(*CI);
3674 }
3675 // Handle specific things.
3676 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3677 // FIXME: Handle enums.
3678 if (!isa<FunctionDecl>(CDRE->getDecl()))
3679 BlockDeclRefs.push_back(CDRE);
3680 return;
3681}
3682
3683void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3684 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3685 CI != E; ++CI)
3686 if (*CI) {
3687 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3688 GetBlockCallExprs(CBE->getBody());
3689 else
3690 GetBlockCallExprs(*CI);
3691 }
3692
3693 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3694 if (CE->getCallee()->getType()->isBlockPointerType()) {
3695 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3696 }
3697 }
3698 return;
3699}
3700
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003701Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003702 // Navigate to relevant type information.
3703 const char *closureName = 0;
3704 const BlockPointerType *CPT = 0;
3705
3706 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003707 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003708 CPT = DRE->getType()->getAsBlockPointerType();
3709 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003710 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003711 CPT = CDRE->getType()->getAsBlockPointerType();
3712 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003713 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003714 CPT = MExpr->getType()->getAsBlockPointerType();
3715 } else {
3716 assert(1 && "RewriteBlockClass: Bad type");
3717 }
3718 assert(CPT && "RewriteBlockClass: Bad type");
3719 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3720 assert(FT && "RewriteBlockClass: Bad type");
3721 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3722 // FTP will be null for closures that don't take arguments.
3723
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003724 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3725 SourceLocation(),
3726 &Context->Idents.get("__block_impl"));
3727 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003728
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003729 // Generate a funky cast.
3730 llvm::SmallVector<QualType, 8> ArgTypes;
3731
3732 // Push the block argument type.
3733 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003734 if (FTP) {
3735 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003736 E = FTP->arg_type_end(); I && (I != E); ++I) {
3737 QualType t = *I;
3738 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3739 if (isBlockPointerType(t)) {
3740 const BlockPointerType *BPT = t->getAsBlockPointerType();
3741 t = Context->getPointerType(BPT->getPointeeType());
3742 }
3743 ArgTypes.push_back(t);
3744 }
Steve Naroff54055232008-10-27 17:20:55 +00003745 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003746 // Now do the pointer to function cast.
3747 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3748 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3749
3750 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003751
Steve Naroffb2f9e512008-11-03 23:29:32 +00003752 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003753 // Don't forget the parens to enforce the proper binding.
3754 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3755 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003756
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003757 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3758 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3759 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3760
Steve Naroffb2f9e512008-11-03 23:29:32 +00003761 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003762 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3763
3764 llvm::SmallVector<Expr*, 8> BlkExprs;
3765 // Add the implicit argument.
3766 BlkExprs.push_back(BlkCast);
3767 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003768 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3769 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003770 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003771 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003772 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3773 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003774}
3775
3776void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003777 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3778 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003779}
3780
3781void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3782 // FIXME: Add more elaborate code generation required by the ABI.
3783 InsertText(BDRE->getLocStart(), "*", 1);
3784}
3785
Steve Naroffb2f9e512008-11-03 23:29:32 +00003786void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3787 SourceLocation LocStart = CE->getLParenLoc();
3788 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003789
3790 // Need to avoid trying to rewrite synthesized casts.
3791 if (LocStart.isInvalid())
3792 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003793 // Need to avoid trying to rewrite casts contained in macros.
3794 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3795 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003796
Steve Naroff54055232008-10-27 17:20:55 +00003797 const char *startBuf = SM->getCharacterData(LocStart);
3798 const char *endBuf = SM->getCharacterData(LocEnd);
3799
3800 // advance the location to startArgList.
3801 const char *argPtr = startBuf;
3802
3803 while (*argPtr++ && (argPtr < endBuf)) {
3804 switch (*argPtr) {
3805 case '^':
3806 // Replace the '^' with '*'.
3807 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3808 ReplaceText(LocStart, 1, "*", 1);
3809 break;
3810 }
3811 }
3812 return;
3813}
3814
3815void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3816 SourceLocation DeclLoc = FD->getLocation();
3817 unsigned parenCount = 0;
3818
3819 // We have 1 or more arguments that have closure pointers.
3820 const char *startBuf = SM->getCharacterData(DeclLoc);
3821 const char *startArgList = strchr(startBuf, '(');
3822
3823 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3824
3825 parenCount++;
3826 // advance the location to startArgList.
3827 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3828 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3829
3830 const char *argPtr = startArgList;
3831
3832 while (*argPtr++ && parenCount) {
3833 switch (*argPtr) {
3834 case '^':
3835 // Replace the '^' with '*'.
3836 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3837 ReplaceText(DeclLoc, 1, "*", 1);
3838 break;
3839 case '(':
3840 parenCount++;
3841 break;
3842 case ')':
3843 parenCount--;
3844 break;
3845 }
3846 }
3847 return;
3848}
3849
3850bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3851 const FunctionTypeProto *FTP;
3852 const PointerType *PT = QT->getAsPointerType();
3853 if (PT) {
3854 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3855 } else {
3856 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3857 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3858 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3859 }
3860 if (FTP) {
3861 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3862 E = FTP->arg_type_end(); I != E; ++I)
3863 if (isBlockPointerType(*I))
3864 return true;
3865 }
3866 return false;
3867}
3868
3869void RewriteObjC::GetExtentOfArgList(const char *Name,
3870 const char *&LParen, const char *&RParen) {
3871 const char *argPtr = strchr(Name, '(');
3872 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3873
3874 LParen = argPtr; // output the start.
3875 argPtr++; // skip past the left paren.
3876 unsigned parenCount = 1;
3877
3878 while (*argPtr && parenCount) {
3879 switch (*argPtr) {
3880 case '(': parenCount++; break;
3881 case ')': parenCount--; break;
3882 default: break;
3883 }
3884 if (parenCount) argPtr++;
3885 }
3886 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3887 RParen = argPtr; // output the end
3888}
3889
3890void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3891 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3892 RewriteBlockPointerFunctionArgs(FD);
3893 return;
3894 }
3895 // Handle Variables and Typedefs.
3896 SourceLocation DeclLoc = ND->getLocation();
3897 QualType DeclT;
3898 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3899 DeclT = VD->getType();
3900 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3901 DeclT = TDD->getUnderlyingType();
3902 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3903 DeclT = FD->getType();
3904 else
3905 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3906
3907 const char *startBuf = SM->getCharacterData(DeclLoc);
3908 const char *endBuf = startBuf;
3909 // scan backward (from the decl location) for the end of the previous decl.
3910 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3911 startBuf--;
3912
3913 // *startBuf != '^' if we are dealing with a pointer to function that
3914 // may take block argument types (which will be handled below).
3915 if (*startBuf == '^') {
3916 // Replace the '^' with '*', computing a negative offset.
3917 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3918 ReplaceText(DeclLoc, 1, "*", 1);
3919 }
3920 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3921 // Replace the '^' with '*' for arguments.
3922 DeclLoc = ND->getLocation();
3923 startBuf = SM->getCharacterData(DeclLoc);
3924 const char *argListBegin, *argListEnd;
3925 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3926 while (argListBegin < argListEnd) {
3927 if (*argListBegin == '^') {
3928 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3929 ReplaceText(CaretLoc, 1, "*", 1);
3930 }
3931 argListBegin++;
3932 }
3933 }
3934 return;
3935}
3936
3937void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3938 // Add initializers for any closure decl refs.
3939 GetBlockDeclRefExprs(Exp->getBody());
3940 if (BlockDeclRefs.size()) {
3941 // Unique all "by copy" declarations.
3942 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3943 if (!BlockDeclRefs[i]->isByRef())
3944 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3945 // Unique all "by ref" declarations.
3946 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3947 if (BlockDeclRefs[i]->isByRef()) {
3948 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3949 }
3950 // Find any imported blocks...they will need special attention.
3951 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3952 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003953 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003954 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3955 }
3956 }
3957}
3958
Steve Narofffa15fd92008-10-28 20:29:00 +00003959FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3960 IdentifierInfo *ID = &Context->Idents.get(name);
3961 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3962 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3963 ID, FType, FunctionDecl::Extern, false, 0);
3964}
3965
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003966Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003967 Blocks.push_back(Exp);
3968
3969 CollectBlockDeclRefInfo(Exp);
3970 std::string FuncName;
3971
3972 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003973 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003974 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003975 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003976 // Convert colons to underscores.
3977 std::string::size_type loc = 0;
3978 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3979 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003980 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003981 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003982
3983 std::string BlockNumber = utostr(Blocks.size()-1);
3984
3985 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3986 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3987
3988 // Get a pointer to the function type so we can cast appropriately.
3989 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3990
3991 FunctionDecl *FD;
3992 Expr *NewRep;
3993
3994 // Simulate a contructor call...
3995 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3996 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3997
3998 llvm::SmallVector<Expr*, 4> InitExprs;
3999
Steve Narofffdc03722008-10-29 21:23:59 +00004000 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004001 FD = SynthBlockInitFunctionDecl(Func.c_str());
4002 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4003 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004004 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004005 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004006
4007 if (ImportedBlockDecls.size()) {
4008 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004009 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4010 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4011 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004012 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004013 InitExprs.push_back(castExpr);
4014
Steve Narofffa15fd92008-10-28 20:29:00 +00004015 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004016 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4017 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4018 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004019 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004020 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004021 }
4022 // Add initializers for any closure decl refs.
4023 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004024 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004025 // Output all "by copy" declarations.
4026 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4027 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004028 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004029 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004030 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004031 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004032 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004033 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004034 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4035 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004036 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004037 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004038 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004039 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004040 }
Steve Narofffdc03722008-10-29 21:23:59 +00004041 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004042 }
4043 // Output all "by ref" declarations.
4044 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4045 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004046 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004047 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4048 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4049 Context->getPointerType(Exp->getType()),
4050 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004051 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004052 }
4053 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004054 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4055 FType, SourceLocation());
4056 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4057 Context->getPointerType(NewRep->getType()),
4058 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004059 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004060 BlockDeclRefs.clear();
4061 BlockByRefDecls.clear();
4062 BlockByCopyDecls.clear();
4063 ImportedBlockDecls.clear();
4064 return NewRep;
4065}
4066
4067//===----------------------------------------------------------------------===//
4068// Function Body / Expression rewriting
4069//===----------------------------------------------------------------------===//
4070
Steve Naroffc77a6362008-12-04 16:24:46 +00004071// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4072// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4073// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4074// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4075// Since the rewriter isn't capable of rewriting rewritten code, it's important
4076// we get this right.
4077void RewriteObjC::CollectPropertySetters(Stmt *S) {
4078 // Perform a bottom up traversal of all children.
4079 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4080 CI != E; ++CI)
4081 if (*CI)
4082 CollectPropertySetters(*CI);
4083
4084 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4085 if (BinOp->isAssignmentOp()) {
4086 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4087 PropSetters[PRE] = BinOp;
4088 }
4089 }
4090}
4091
Steve Narofffa15fd92008-10-28 20:29:00 +00004092Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4093 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4094 isa<DoStmt>(S) || isa<ForStmt>(S))
4095 Stmts.push_back(S);
4096 else if (isa<ObjCForCollectionStmt>(S)) {
4097 Stmts.push_back(S);
4098 ObjCBcLabelNo.push_back(++BcLabelCount);
4099 }
4100
4101 SourceRange OrigStmtRange = S->getSourceRange();
4102
4103 // Perform a bottom up rewrite of all children.
4104 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4105 CI != E; ++CI)
4106 if (*CI) {
4107 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4108 if (newStmt)
4109 *CI = newStmt;
4110 }
4111
4112 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4113 // Rewrite the block body in place.
4114 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4115
4116 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004117 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4118 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004119
4120 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4121 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004122 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004123 return blockTranscribed;
4124 }
4125 // Handle specific things.
4126 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4127 return RewriteAtEncode(AtEncode);
4128
4129 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4130 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4131
Steve Naroffc77a6362008-12-04 16:24:46 +00004132 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4133 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4134 if (BinOp) {
4135 // Because the rewriter doesn't allow us to rewrite rewritten code,
4136 // we need to rewrite the right hand side prior to rewriting the setter.
4137 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff4c3580e2008-12-04 23:50:32 +00004138 //
4139 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4140 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4141 // to see the original expression). Consider this example:
4142 //
4143 // Foo *obj1, *obj2;
4144 //
4145 // obj1.i = [obj2 rrrr];
4146 //
4147 // 'BinOp' for the previous expression looks like:
4148 //
4149 // (BinaryOperator 0x231ccf0 'int' '='
4150 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4151 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4152 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4153 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4154 //
4155 // 'newStmt' represents the rewritten message expression. For example:
4156 //
4157 // (CallExpr 0x231d300 'id':'struct objc_object *'
4158 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4159 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4160 // (CStyleCastExpr 0x231d220 'void *'
4161 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4162 //
4163 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4164 // can be used as the setter argument. ReplaceStmt() will still 'see'
4165 // the original RHS (since we haven't altered BinOp).
4166 //
4167 // This implies the Rewrite* routines can no longer delete the original
4168 // node. As a result, we now leak the original AST nodes.
4169 //
Steve Naroffc77a6362008-12-04 16:24:46 +00004170 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4171 } else {
4172 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004173 }
4174 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004175 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4176 return RewriteAtSelector(AtSelector);
4177
4178 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4179 return RewriteObjCStringLiteral(AtString);
4180
4181 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004182#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004183 // Before we rewrite it, put the original message expression in a comment.
4184 SourceLocation startLoc = MessExpr->getLocStart();
4185 SourceLocation endLoc = MessExpr->getLocEnd();
4186
4187 const char *startBuf = SM->getCharacterData(startLoc);
4188 const char *endBuf = SM->getCharacterData(endLoc);
4189
4190 std::string messString;
4191 messString += "// ";
4192 messString.append(startBuf, endBuf-startBuf+1);
4193 messString += "\n";
4194
4195 // FIXME: Missing definition of
4196 // InsertText(clang::SourceLocation, char const*, unsigned int).
4197 // InsertText(startLoc, messString.c_str(), messString.size());
4198 // Tried this, but it didn't work either...
4199 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004200#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004201 return RewriteMessageExpr(MessExpr);
4202 }
4203
4204 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4205 return RewriteObjCTryStmt(StmtTry);
4206
4207 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4208 return RewriteObjCSynchronizedStmt(StmtTry);
4209
4210 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4211 return RewriteObjCThrowStmt(StmtThrow);
4212
4213 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4214 return RewriteObjCProtocolExpr(ProtocolExp);
4215
4216 if (ObjCForCollectionStmt *StmtForCollection =
4217 dyn_cast<ObjCForCollectionStmt>(S))
4218 return RewriteObjCForCollectionStmt(StmtForCollection,
4219 OrigStmtRange.getEnd());
4220 if (BreakStmt *StmtBreakStmt =
4221 dyn_cast<BreakStmt>(S))
4222 return RewriteBreakStmt(StmtBreakStmt);
4223 if (ContinueStmt *StmtContinueStmt =
4224 dyn_cast<ContinueStmt>(S))
4225 return RewriteContinueStmt(StmtContinueStmt);
4226
4227 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4228 // and cast exprs.
4229 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4230 // FIXME: What we're doing here is modifying the type-specifier that
4231 // precedes the first Decl. In the future the DeclGroup should have
4232 // a separate type-specifier that we can rewrite.
4233 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4234
4235 // Blocks rewrite rules.
4236 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4237 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004238 ScopedDecl *SD = *DI;
4239 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4240 if (isBlockPointerType(ND->getType()))
4241 RewriteBlockPointerDecl(ND);
4242 else if (ND->getType()->isFunctionPointerType())
4243 CheckFunctionPointerDecl(ND->getType(), ND);
4244 }
4245 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4246 if (isBlockPointerType(TD->getUnderlyingType()))
4247 RewriteBlockPointerDecl(TD);
4248 else if (TD->getUnderlyingType()->isFunctionPointerType())
4249 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4250 }
4251 }
4252 }
4253
4254 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4255 RewriteObjCQualifiedInterfaceTypes(CE);
4256
4257 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4258 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4259 assert(!Stmts.empty() && "Statement stack is empty");
4260 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4261 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4262 && "Statement stack mismatch");
4263 Stmts.pop_back();
4264 }
4265 // Handle blocks rewriting.
4266 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4267 if (BDRE->isByRef())
4268 RewriteBlockDeclRefExpr(BDRE);
4269 }
4270 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004271 if (CE->getCallee()->getType()->isBlockPointerType()) {
4272 Stmt *BlockCall = SynthesizeBlockCall(CE);
4273 ReplaceStmt(S, BlockCall);
4274 return BlockCall;
4275 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004276 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004277 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004278 RewriteCastExpr(CE);
4279 }
4280#if 0
4281 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4282 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4283 // Get the new text.
4284 std::string SStr;
4285 llvm::raw_string_ostream Buf(SStr);
4286 Replacement->printPretty(Buf);
4287 const std::string &Str = Buf.str();
4288
4289 printf("CAST = %s\n", &Str[0]);
4290 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4291 delete S;
4292 return Replacement;
4293 }
4294#endif
4295 // Return this stmt unmodified.
4296 return S;
4297}
4298
4299/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4300/// main file of the input.
4301void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4303 // Since function prototypes don't have ParmDecl's, we check the function
4304 // prototype. This enables us to rewrite function declarations and
4305 // definitions using the same code.
4306 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4307
4308 if (Stmt *Body = FD->getBody()) {
4309 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004310 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004311 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004312 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004313 CurrentBody = 0;
4314 if (PropParentMap) {
4315 delete PropParentMap;
4316 PropParentMap = 0;
4317 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004318 // This synthesizes and inserts the block "impl" struct, invoke function,
4319 // and any copy/dispose helper functions.
4320 InsertBlockLiteralsWithinFunction(FD);
4321 CurFunctionDef = 0;
4322 }
4323 return;
4324 }
4325 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4326 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004327 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004328 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004329 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004330 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004331 CurrentBody = 0;
4332 if (PropParentMap) {
4333 delete PropParentMap;
4334 PropParentMap = 0;
4335 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004336 InsertBlockLiteralsWithinMethod(MD);
4337 CurMethodDef = 0;
4338 }
4339 }
4340 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4341 ClassImplementation.push_back(CI);
4342 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4343 CategoryImplementation.push_back(CI);
4344 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4345 RewriteForwardClassDecl(CD);
4346 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4347 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004348 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004349 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004350 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004351 CheckFunctionPointerDecl(VD->getType(), VD);
4352 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004353 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004354 RewriteCastExpr(CE);
4355 }
4356 }
4357 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004358 if (VD->getInit()) {
4359 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004360 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004361 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004362 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004363 CurrentBody = 0;
4364 if (PropParentMap) {
4365 delete PropParentMap;
4366 PropParentMap = 0;
4367 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004368 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004369 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004370 GlobalVarDecl = 0;
4371
4372 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004373 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004374 RewriteCastExpr(CE);
4375 }
4376 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004377 return;
4378 }
4379 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4380 if (isBlockPointerType(TD->getUnderlyingType()))
4381 RewriteBlockPointerDecl(TD);
4382 else if (TD->getUnderlyingType()->isFunctionPointerType())
4383 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4384 return;
4385 }
4386 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4387 if (RD->isDefinition()) {
4388 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4389 e = RD->field_end(); i != e; ++i) {
4390 FieldDecl *FD = *i;
4391 if (isBlockPointerType(FD->getType()))
4392 RewriteBlockPointerDecl(FD);
4393 }
4394 }
4395 return;
4396 }
4397 // Nothing yet.
4398}
4399
4400void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4401 // Get the top-level buffer that this corresponds to.
4402
4403 // Rewrite tabs if we care.
4404 //RewriteTabs();
4405
4406 if (Diags.hasErrorOccurred())
4407 return;
4408
4409 // Create the output file.
4410
4411 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4412 llvm::raw_ostream *OutFile;
4413 if (OutFileName == "-") {
4414 OutFile = &llvm::outs();
4415 } else if (!OutFileName.empty()) {
4416 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004417 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004418 OwnedStream.reset(OutFile);
4419 } else if (InFileName == "-") {
4420 OutFile = &llvm::outs();
4421 } else {
4422 llvm::sys::Path Path(InFileName);
4423 Path.eraseSuffix();
4424 Path.appendSuffix("cpp");
4425 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004426 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004427 OwnedStream.reset(OutFile);
4428 }
4429
4430 RewriteInclude();
4431
4432 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4433 Preamble.c_str(), Preamble.size(), false);
4434
Steve Naroff0aab7962008-11-14 14:10:01 +00004435 if (ClassImplementation.size() || CategoryImplementation.size())
4436 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004437
4438 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4439 // we are done.
4440 if (const RewriteBuffer *RewriteBuf =
4441 Rewrite.getRewriteBufferFor(MainFileID)) {
4442 //printf("Changed:\n");
4443 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4444 } else {
4445 fprintf(stderr, "No changes\n");
4446 }
Steve Narofface66252008-11-13 20:07:04 +00004447
Steve Naroff0aab7962008-11-14 14:10:01 +00004448 if (ClassImplementation.size() || CategoryImplementation.size()) {
4449 // Rewrite Objective-c meta data*
4450 std::string ResultStr;
4451 SynthesizeMetaDataIntoBuffer(ResultStr);
4452 // Emit metadata.
4453 *OutFile << ResultStr;
4454 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004455 OutFile->flush();
4456}
4457