blob: 614c30996ebce638450be78a877c64b99650f85c [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
Steve Naroffb619d952008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
129 virtual void InitializeTU(TranslationUnit &TU) {
130 TU.SetOwnsDecls(false);
131 Initialize(TU.getContext());
132 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000133
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000138 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000139 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
143 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000227 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000233 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000342 bool isTopLevelBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
Steve Naroff54055232008-10-27 17:20:55 +0000343
344 // FIXME: This predicate seems like it would be useful to add to ASTContext.
345 bool isObjCType(QualType T) {
346 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
347 return false;
348
349 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
350
351 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
352 OCT == Context->getCanonicalType(Context->getObjCClassType()))
353 return true;
354
355 if (const PointerType *PT = OCT->getAsPointerType()) {
356 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
357 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
358 return true;
359 }
360 return false;
361 }
362 bool PointerTypeTakesAnyBlockArguments(QualType QT);
363 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000368 };
369}
370
Steve Naroff54055232008-10-27 17:20:55 +0000371void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
372 NamedDecl *D) {
373 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
374 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
387 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
388}
389
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroffb29b4272008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
413 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000414}
415
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000416ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000417 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000418 Diagnostic &Diags,
419 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000420 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000421}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422
Steve Naroffb29b4272008-04-14 22:03:09 +0000423void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 Context = &context;
425 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000426 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000427 MsgSendFunctionDecl = 0;
428 MsgSendSuperFunctionDecl = 0;
429 MsgSendStretFunctionDecl = 0;
430 MsgSendSuperStretFunctionDecl = 0;
431 MsgSendFpretFunctionDecl = 0;
432 GetClassFunctionDecl = 0;
433 GetMetaClassFunctionDecl = 0;
434 SelGetUidFunctionDecl = 0;
435 CFStringFunctionDecl = 0;
436 GetProtocolFunctionDecl = 0;
437 ConstantStringClassReference = 0;
438 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000439 CurMethodDef = 0;
440 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000441 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000442 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000443 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000444 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000445 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000446 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000447 PropParentMap = 0;
448 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000449 DisableReplaceStmt = false;
450
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000451 // Get the ID and start/end of the main file.
452 MainFileID = SM->getMainFileID();
453 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
454 MainFileStart = MainBuf->getBufferStart();
455 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000457 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000458
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000459 // declaring objc_selector outside the parameter list removes a silly
460 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 if (IsHeader)
462 Preamble = "#pragma once\n";
463 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000464 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000465 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000466 if (LangOpts.Microsoft) {
467 // Add a constructor for creating temporary objects.
Steve Naroff46a98a72008-12-23 20:11:22 +0000468 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) : ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000470 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
473 Preamble += "typedef struct objc_object Protocol;\n";
474 Preamble += "#define _REWRITER_typedef_Protocol\n";
475 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000476 if (LangOpts.Microsoft) {
477 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
478 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
479 } else
480 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
481 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000482 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000492 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
496 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000500 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000501 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
504 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
506 Preamble += "struct __objcFastEnumerationState {\n\t";
507 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000508 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "unsigned long *mutationsPtr;\n\t";
510 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000512 Preamble += "#define __FASTENUMERATIONSTATE\n";
513 Preamble += "#endif\n";
514 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
515 Preamble += "struct __NSConstantStringImpl {\n";
516 Preamble += " int *isa;\n";
517 Preamble += " int flags;\n";
518 Preamble += " char *str;\n";
519 Preamble += " long length;\n";
520 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000521 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
522 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
523 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000524 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000525 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000526 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
527 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000528 // Blocks preamble.
529 Preamble += "#ifndef BLOCK_IMPL\n";
530 Preamble += "#define BLOCK_IMPL\n";
531 Preamble += "struct __block_impl {\n";
532 Preamble += " void *isa;\n";
533 Preamble += " int Flags;\n";
534 Preamble += " int Size;\n";
535 Preamble += " void *FuncPtr;\n";
536 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000537 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
538 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
539 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000542 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000543 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
545 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000546 Preamble += "#define __attribute__(X)\n";
547 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548}
549
550
Chris Lattnerf04da132007-10-24 17:06:59 +0000551//===----------------------------------------------------------------------===//
552// Top Level Driver Code
553//===----------------------------------------------------------------------===//
554
Steve Naroffb29b4272008-04-14 22:03:09 +0000555void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000556 // Two cases: either the decl could be in the main file, or it could be in a
557 // #included file. If the former, rewrite it now. If the later, check to see
558 // if we rewrote the #include/#import.
559 SourceLocation Loc = D->getLocation();
560 Loc = SM->getLogicalLoc(Loc);
561
562 // If this is for a builtin, ignore it.
563 if (Loc.isInvalid()) return;
564
Steve Naroffebf2b562007-10-23 23:50:29 +0000565 // Look for built-in declarations that we need to refer during the rewrite.
566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000567 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000568 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000569 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000570 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000571 ConstantStringClassReference = FVD;
572 return;
573 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000575 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000577 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000578 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000579 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 } else if (ObjCForwardProtocolDecl *FP =
581 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000582 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000583 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000584 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000585 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000586 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000587}
588
Chris Lattnerf04da132007-10-24 17:06:59 +0000589//===----------------------------------------------------------------------===//
590// Syntactic (non-AST) Rewriting Code
591//===----------------------------------------------------------------------===//
592
Steve Naroffb29b4272008-04-14 22:03:09 +0000593void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000594 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
595 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
596 const char *MainBufStart = MainBuf.first;
597 const char *MainBufEnd = MainBuf.second;
598 size_t ImportLen = strlen("import");
599 size_t IncludeLen = strlen("include");
600
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000601 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000602 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
603 if (*BufPtr == '#') {
604 if (++BufPtr == MainBufEnd)
605 return;
606 while (*BufPtr == ' ' || *BufPtr == '\t')
607 if (++BufPtr == MainBufEnd)
608 return;
609 if (!strncmp(BufPtr, "import", ImportLen)) {
610 // replace import with include
611 SourceLocation ImportLoc =
612 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000613 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000614 BufPtr += ImportLen;
615 }
616 }
617 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000618}
619
Steve Naroffb29b4272008-04-14 22:03:09 +0000620void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000621 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
622 const char *MainBufStart = MainBuf.first;
623 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000624
Chris Lattnerf04da132007-10-24 17:06:59 +0000625 // Loop over the whole file, looking for tabs.
626 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
627 if (*BufPtr != '\t')
628 continue;
629
630 // Okay, we found a tab. This tab will turn into at least one character,
631 // but it depends on which 'virtual column' it is in. Compute that now.
632 unsigned VCol = 0;
633 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
634 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
635 ++VCol;
636
637 // Okay, now that we know the virtual column, we know how many spaces to
638 // insert. We assume 8-character tab-stops.
639 unsigned Spaces = 8-(VCol & 7);
640
641 // Get the location of the tab.
642 SourceLocation TabLoc =
643 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
644
645 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000646 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000647 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000648}
649
Steve Naroffeb0646c2008-12-02 15:48:25 +0000650static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
651 ObjCIvarDecl *OID) {
652 std::string S;
653 S = "((struct ";
654 S += ClassDecl->getIdentifier()->getName();
655 S += "_IMPL *)self)->";
656 S += OID->getNameAsCString();
657 return S;
658}
659
Steve Naroffa0876e82008-12-02 17:36:43 +0000660void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
661 ObjCImplementationDecl *IMD,
662 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000663 SourceLocation startLoc = PID->getLocStart();
664 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000665 const char *startBuf = SM->getCharacterData(startLoc);
666 assert((*startBuf == '@') && "bogus @synthesize location");
667 const char *semiBuf = strchr(startBuf, ';');
668 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
669 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
670
671 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
672 return; // FIXME: is this correct?
673
674 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000675 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000676 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000677 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000678
679 if (!OID)
680 return;
681
682 std::string Getr;
683 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
684 Getr += "{ ";
685 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000686 // FIXME: deal with code generation implications for various property
687 // attributes (copy, retain, nonatomic).
688 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000689 Getr += "return " + getIvarAccessString(ClassDecl, OID);
690 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000691 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000692
693 // Add the rewritten getter to trigger meta data generation. An alternate, and
694 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
695 // with properties explicitly. The following addInstanceMethod() required far
696 // less code change (and actually models what the rewriter is doing).
697 if (IMD)
698 IMD->addInstanceMethod(PD->getGetterMethodDecl());
699 else
700 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000701
702 if (PD->isReadOnly())
703 return;
704
705 // Generate the 'setter' function.
706 std::string Setr;
707 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000708 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000709 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000710 // FIXME: deal with code generation implications for various property
711 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000712 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000713 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000714 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000715 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000716 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000717
718 // Add the rewritten setter to trigger meta data generation.
719 if (IMD)
720 IMD->addInstanceMethod(PD->getSetterMethodDecl());
721 else
722 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000723}
Chris Lattner8a12c272007-10-11 18:38:32 +0000724
Steve Naroffb29b4272008-04-14 22:03:09 +0000725void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000728
729 // Get the start location and compute the semi location.
730 SourceLocation startLoc = ClassDecl->getLocation();
731 const char *startBuf = SM->getCharacterData(startLoc);
732 const char *semiPtr = strchr(startBuf, ';');
733
734 // Translate to typedef's that forward reference structs with the same name
735 // as the class. As a convenience, we include the original declaration
736 // as a comment.
737 std::string typedefString;
738 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000739 typedefString.append(startBuf, semiPtr-startBuf+1);
740 typedefString += "\n";
741 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000743 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000744 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000745 typedefString += "\n";
746 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000747 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000749 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000751 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000752 }
753
754 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000755 ReplaceText(startLoc, semiPtr-startBuf+1,
756 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000757}
758
Steve Naroffb29b4272008-04-14 22:03:09 +0000759void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000760 SourceLocation LocStart = Method->getLocStart();
761 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000762
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000763 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000764 InsertText(LocStart, "#if 0\n", 6);
765 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000766 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000767 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000768 }
769}
770
Steve Naroffb29b4272008-04-14 22:03:09 +0000771void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000772{
Chris Lattner55d13b42008-03-16 21:23:50 +0000773 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000774 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000775 SourceLocation Loc = Property->getLocation();
776
Chris Lattneraadaf782008-01-31 19:51:04 +0000777 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000778
779 // FIXME: handle properties that are declared across multiple lines.
780 }
781}
782
Steve Naroffb29b4272008-04-14 22:03:09 +0000783void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000784 SourceLocation LocStart = CatDecl->getLocStart();
785
786 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000787 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000788
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000789 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000790 E = CatDecl->instmeth_end(); I != E; ++I)
791 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000792 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000793 E = CatDecl->classmeth_end(); I != E; ++I)
794 RewriteMethodDeclaration(*I);
795
Steve Naroff423cb562007-10-30 13:30:57 +0000796 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000797 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000798}
799
Steve Naroffb29b4272008-04-14 22:03:09 +0000800void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000801 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000802
Steve Naroff752d6ef2007-10-30 16:42:30 +0000803 SourceLocation LocStart = PDecl->getLocStart();
804
805 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000806 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000807
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000809 E = PDecl->instmeth_end(); I != E; ++I)
810 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000811 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000812 E = PDecl->classmeth_end(); I != E; ++I)
813 RewriteMethodDeclaration(*I);
814
Steve Naroff752d6ef2007-10-30 16:42:30 +0000815 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000816 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000817 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000818
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000819 // Must comment out @optional/@required
820 const char *startBuf = SM->getCharacterData(LocStart);
821 const char *endBuf = SM->getCharacterData(LocEnd);
822 for (const char *p = startBuf; p < endBuf; p++) {
823 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
824 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000825 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000826 ReplaceText(OptionalLoc, strlen("@optional"),
827 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000828
829 }
830 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
831 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000832 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000833 ReplaceText(OptionalLoc, strlen("@required"),
834 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000835
836 }
837 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000838}
839
Steve Naroffb29b4272008-04-14 22:03:09 +0000840void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000841 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000842 if (LocStart.isInvalid())
843 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000844 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000845 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000846}
847
Steve Naroffb29b4272008-04-14 22:03:09 +0000848void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000849 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000850 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000851 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000854 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000855 else if (OMD->getResultType()->isFunctionPointerType() ||
856 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000857 // needs special handling, since pointer-to-functions have special
858 // syntax (where a decaration models use).
859 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000860 QualType PointeeTy;
861 if (const PointerType* PT = retType->getAsPointerType())
862 PointeeTy = PT->getPointeeType();
863 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
864 PointeeTy = BPT->getPointeeType();
865 if ((FPRetType = PointeeTy->getAsFunctionType())) {
866 ResultStr += FPRetType->getResultType().getAsString();
867 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000868 }
869 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000870 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000871 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000872
873 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000874 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000875
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000876 if (OMD->isInstance())
877 NameStr += "_I_";
878 else
879 NameStr += "_C_";
880
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000881 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000882 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000883
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000884 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000885 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000886 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000887 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888 }
Steve Naroff563b8282008-04-04 22:23:44 +0000889 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000890 {
891 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000892 int len = selString.size();
893 for (int i = 0; i < len; i++)
894 if (selString[i] == ':')
895 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000896 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000897 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000898 // Remember this name for metadata emission
899 MethodInternalNames[OMD] = NameStr;
900 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901
902 // Rewrite arguments
903 ResultStr += "(";
904
905 // invisible arguments
906 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000907 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000908 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000909 if (!LangOpts.Microsoft) {
910 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
911 ResultStr += "struct ";
912 }
913 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000914 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000915 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000916 }
917 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000918 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000919
920 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000921 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922 ResultStr += " _cmd";
923
924 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000925 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ParmVarDecl *PDecl = OMD->getParamDecl(i);
927 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000928 if (PDecl->getType()->isObjCQualifiedIdType()) {
929 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000930 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000931 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000932 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000933 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000934 // Make sure we convert "t (^)(...)" to "t (*)(...)".
935 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
936 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
937 } else
938 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000939 ResultStr += Name;
940 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000941 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000942 if (OMD->isVariadic())
943 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000944 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000945
Steve Naroff76e429d2008-07-16 14:40:40 +0000946 if (FPRetType) {
947 ResultStr += ")"; // close the precedence "scope" for "*".
948
949 // Now, emit the argument types (if any).
950 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
951 ResultStr += "(";
952 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
953 if (i) ResultStr += ", ";
954 std::string ParamStr = FT->getArgType(i).getAsString();
955 ResultStr += ParamStr;
956 }
957 if (FT->isVariadic()) {
958 if (FT->getNumArgs()) ResultStr += ", ";
959 ResultStr += "...";
960 }
961 ResultStr += ")";
962 } else {
963 ResultStr += "()";
964 }
965 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000966}
Steve Naroffb29b4272008-04-14 22:03:09 +0000967void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000968 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
969 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000971 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000972 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000973 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000974 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000975
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000976 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000977 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
978 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000980 ObjCMethodDecl *OMD = *I;
981 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 SourceLocation LocStart = OMD->getLocStart();
983 SourceLocation LocEnd = OMD->getBody()->getLocStart();
984
985 const char *startBuf = SM->getCharacterData(LocStart);
986 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000987 ReplaceText(LocStart, endBuf-startBuf,
988 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989 }
990
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000991 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000992 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
993 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000994 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000995 ObjCMethodDecl *OMD = *I;
996 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 SourceLocation LocStart = OMD->getLocStart();
998 SourceLocation LocEnd = OMD->getBody()->getLocStart();
999
1000 const char *startBuf = SM->getCharacterData(LocStart);
1001 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001002 ReplaceText(LocStart, endBuf-startBuf,
1003 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001005 for (ObjCCategoryImplDecl::propimpl_iterator
1006 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1007 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001008 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001009 }
1010
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001011 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001012 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001013 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001014 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001015}
1016
Steve Naroffb29b4272008-04-14 22:03:09 +00001017void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001018 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001019 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001020 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001021 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001022 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001023 ResultStr += "\n";
1024 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001025 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001026 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001027 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001028 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001029 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001030 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001031 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001032 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001034
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001035 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1036 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001037 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001038 E = ClassDecl->instmeth_end(); I != E; ++I)
1039 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001040 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001041 E = ClassDecl->classmeth_end(); I != E; ++I)
1042 RewriteMethodDeclaration(*I);
1043
Steve Naroff2feac5e2007-10-30 03:43:13 +00001044 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001045 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001046}
1047
Steve Naroffb619d952008-12-09 12:56:34 +00001048Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1049 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001050 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1051 // This allows us to reuse all the fun and games in SynthMessageExpr().
1052 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1053 ObjCMessageExpr *MsgExpr;
1054 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1055 llvm::SmallVector<Expr *, 1> ExprVec;
1056 ExprVec.push_back(newStmt);
1057
Steve Naroff8599e7a2008-12-08 16:43:47 +00001058 Stmt *Receiver = PropRefExpr->getBase();
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 Naroffc77a6362008-12-04 16:24:46 +00001065 PDecl->getSetterName(), PDecl->getType(),
1066 PDecl->getSetterMethodDecl(),
1067 SourceLocation(), SourceLocation(),
1068 &ExprVec[0], 1);
1069 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1070
1071 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001072 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001073 //delete BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00001074 delete MsgExpr;
1075 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001076}
1077
Steve Naroffc77a6362008-12-04 16:24:46 +00001078Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001079 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1080 // This allows us to reuse all the fun and games in SynthMessageExpr().
1081 ObjCMessageExpr *MsgExpr;
1082 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1083
Steve Naroff8599e7a2008-12-08 16:43:47 +00001084 Stmt *Receiver = PropRefExpr->getBase();
1085
1086 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1087 if (PRE && PropGetters[PRE]) {
1088 // This allows us to handle chain/nested property getters.
1089 Receiver = PropGetters[PRE];
1090 }
1091 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001092 PDecl->getGetterName(), PDecl->getType(),
1093 PDecl->getGetterMethodDecl(),
1094 SourceLocation(), SourceLocation(),
1095 0, 0);
1096
Steve Naroff4c3580e2008-12-04 23:50:32 +00001097 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001098
1099 if (!PropParentMap)
1100 PropParentMap = new ParentMap(CurrentBody);
1101
1102 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1103 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1104 // We stash away the ReplacingStmt since actually doing the
1105 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1106 PropGetters[PropRefExpr] = ReplacingStmt;
1107 delete MsgExpr;
1108 return PropRefExpr; // return the original...
1109 } else {
1110 ReplaceStmt(PropRefExpr, ReplacingStmt);
1111 // delete PropRefExpr; elsewhere...
1112 delete MsgExpr;
1113 return ReplacingStmt;
1114 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001115}
1116
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001117Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1118 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001119 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001120 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001121 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001122 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1123 // lookup which class implements the instance variable.
1124 ObjCInterfaceDecl *clsDeclared = 0;
1125 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1126 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1127
1128 // Synthesize an explicit cast to gain access to the ivar.
1129 std::string RecName = clsDeclared->getIdentifier()->getName();
1130 RecName += "_IMPL";
1131 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001132 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001133 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001134 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1135 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001136 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001137 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001138 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001139 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1140 IV->getBase()->getLocEnd(),
1141 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001142 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001143 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001144 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1145 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001146 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001147 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001148 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001149 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001150
1151 ReplaceStmt(IV->getBase(), PE);
1152 // Cannot delete IV->getBase(), since PE points to it.
1153 // Replace the old base with the cast. This is important when doing
1154 // embedded rewrites. For example, [newInv->_container addObject:0].
1155 IV->setBase(PE);
1156 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001157 }
Steve Naroff84472a82008-04-18 21:55:08 +00001158 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001159 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1160
1161 // Explicit ivar refs need to have a cast inserted.
1162 // FIXME: consider sharing some of this code with the code above.
1163 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001164 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001165 // lookup which class implements the instance variable.
1166 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001167 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001168 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1169
1170 // Synthesize an explicit cast to gain access to the ivar.
1171 std::string RecName = clsDeclared->getIdentifier()->getName();
1172 RecName += "_IMPL";
1173 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001174 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001175 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001176 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1177 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001178 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001179 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001180 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001181 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1182 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001183 ReplaceStmt(IV->getBase(), PE);
1184 // Cannot delete IV->getBase(), since PE points to it.
1185 // Replace the old base with the cast. This is important when doing
1186 // embedded rewrites. For example, [newInv->_container addObject:0].
1187 IV->setBase(PE);
1188 return IV;
1189 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001190 }
Steve Naroff84472a82008-04-18 21:55:08 +00001191 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001192}
1193
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001194/// SynthCountByEnumWithState - To print:
1195/// ((unsigned int (*)
1196/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1197/// (void *)objc_msgSend)((id)l_collection,
1198/// sel_registerName(
1199/// "countByEnumeratingWithState:objects:count:"),
1200/// &enumState,
1201/// (id *)items, (unsigned int)16)
1202///
Steve Naroffb29b4272008-04-14 22:03:09 +00001203void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1205 "id *, unsigned int))(void *)objc_msgSend)";
1206 buf += "\n\t\t";
1207 buf += "((id)l_collection,\n\t\t";
1208 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1209 buf += "\n\t\t";
1210 buf += "&enumState, "
1211 "(id *)items, (unsigned int)16)";
1212}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001213
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001214/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1215/// statement to exit to its outer synthesized loop.
1216///
Steve Naroffb29b4272008-04-14 22:03:09 +00001217Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001218 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1219 return S;
1220 // replace break with goto __break_label
1221 std::string buf;
1222
1223 SourceLocation startLoc = S->getLocStart();
1224 buf = "goto __break_label_";
1225 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001226 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001227
1228 return 0;
1229}
1230
1231/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1232/// statement to continue with its inner synthesized loop.
1233///
Steve Naroffb29b4272008-04-14 22:03:09 +00001234Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001235 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1236 return S;
1237 // replace continue with goto __continue_label
1238 std::string buf;
1239
1240 SourceLocation startLoc = S->getLocStart();
1241 buf = "goto __continue_label_";
1242 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001243 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244
1245 return 0;
1246}
1247
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001248/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001249/// It rewrites:
1250/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001251
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001252/// Into:
1253/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001254/// type elem;
1255/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001256/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001257/// id l_collection = (id)collection;
1258/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1259/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001260/// if (limit) {
1261/// unsigned long startMutations = *enumState.mutationsPtr;
1262/// do {
1263/// unsigned long counter = 0;
1264/// do {
1265/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001266/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001267/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001268/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001269/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001270/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1272/// objects:items count:16]);
1273/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001274/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001275/// }
1276/// else
1277/// elem = nil;
1278/// }
1279///
Steve Naroffb29b4272008-04-14 22:03:09 +00001280Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001281 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001282 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1283 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1284 "ObjCForCollectionStmt Statement stack mismatch");
1285 assert(!ObjCBcLabelNo.empty() &&
1286 "ObjCForCollectionStmt - Label No stack empty");
1287
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001288 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001289 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001290 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001291 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292 std::string buf;
1293 buf = "\n{\n\t";
1294 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1295 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001296 ScopedDecl* D = DS->getSolitaryDecl();
1297 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001298 elementTypeAsString = ElementType.getAsString();
1299 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001300 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001301 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001302 buf += elementName;
1303 buf += ";\n\t";
1304 }
Chris Lattner06767512008-04-08 05:52:18 +00001305 else {
1306 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001307 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001308 elementTypeAsString
1309 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001310 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001311
1312 // struct __objcFastEnumerationState enumState = { 0 };
1313 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1314 // id items[16];
1315 buf += "id items[16];\n\t";
1316 // id l_collection = (id)
1317 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001318 // Find start location of 'collection' the hard way!
1319 const char *startCollectionBuf = startBuf;
1320 startCollectionBuf += 3; // skip 'for'
1321 startCollectionBuf = strchr(startCollectionBuf, '(');
1322 startCollectionBuf++; // skip '('
1323 // find 'in' and skip it.
1324 while (*startCollectionBuf != ' ' ||
1325 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1326 (*(startCollectionBuf+3) != ' ' &&
1327 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1328 startCollectionBuf++;
1329 startCollectionBuf += 3;
1330
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001332 ReplaceText(startLoc, startCollectionBuf - startBuf,
1333 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001334 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001335 SourceLocation rightParenLoc = S->getRParenLoc();
1336 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1337 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001338 buf = ";\n\t";
1339
1340 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1341 // objects:items count:16];
1342 // which is synthesized into:
1343 // unsigned int limit =
1344 // ((unsigned int (*)
1345 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1346 // (void *)objc_msgSend)((id)l_collection,
1347 // sel_registerName(
1348 // "countByEnumeratingWithState:objects:count:"),
1349 // (struct __objcFastEnumerationState *)&state,
1350 // (id *)items, (unsigned int)16);
1351 buf += "unsigned long limit =\n\t\t";
1352 SynthCountByEnumWithState(buf);
1353 buf += ";\n\t";
1354 /// if (limit) {
1355 /// unsigned long startMutations = *enumState.mutationsPtr;
1356 /// do {
1357 /// unsigned long counter = 0;
1358 /// do {
1359 /// if (startMutations != *enumState.mutationsPtr)
1360 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001361 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001362 buf += "if (limit) {\n\t";
1363 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1364 buf += "do {\n\t\t";
1365 buf += "unsigned long counter = 0;\n\t\t";
1366 buf += "do {\n\t\t\t";
1367 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1368 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1369 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001370 buf += " = (";
1371 buf += elementTypeAsString;
1372 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001373 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001374 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001375
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001376 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 /// } while (counter < limit);
1378 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1379 /// objects:items count:16]);
1380 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001381 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382 /// }
1383 /// else
1384 /// elem = nil;
1385 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001386 ///
1387 buf = ";\n\t";
1388 buf += "__continue_label_";
1389 buf += utostr(ObjCBcLabelNo.back());
1390 buf += ": ;";
1391 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 buf += "} while (counter < limit);\n\t";
1393 buf += "} while (limit = ";
1394 SynthCountByEnumWithState(buf);
1395 buf += ");\n\t";
1396 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001397 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001398 buf += "__break_label_";
1399 buf += utostr(ObjCBcLabelNo.back());
1400 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401 buf += "}\n\t";
1402 buf += "else\n\t\t";
1403 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001404 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001405 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001406
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001408 if (isa<CompoundStmt>(S->getBody())) {
1409 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1410 InsertText(endBodyLoc, buf.c_str(), buf.size());
1411 } else {
1412 /* Need to treat single statements specially. For example:
1413 *
1414 * for (A *a in b) if (stuff()) break;
1415 * for (A *a in b) xxxyy;
1416 *
1417 * The following code simply scans ahead to the semi to find the actual end.
1418 */
1419 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1420 const char *semiBuf = strchr(stmtBuf, ';');
1421 assert(semiBuf && "Can't find ';'");
1422 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1423 InsertText(endBodyLoc, buf.c_str(), buf.size());
1424 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001425 Stmts.pop_back();
1426 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001428}
1429
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001430/// RewriteObjCSynchronizedStmt -
1431/// This routine rewrites @synchronized(expr) stmt;
1432/// into:
1433/// objc_sync_enter(expr);
1434/// @try stmt @finally { objc_sync_exit(expr); }
1435///
Steve Naroffb29b4272008-04-14 22:03:09 +00001436Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001437 // Get the start location and compute the semi location.
1438 SourceLocation startLoc = S->getLocStart();
1439 const char *startBuf = SM->getCharacterData(startLoc);
1440
1441 assert((*startBuf == '@') && "bogus @synchronized location");
1442
1443 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001444 buf = "objc_sync_enter((id)";
1445 const char *lparenBuf = startBuf;
1446 while (*lparenBuf != '(') lparenBuf++;
1447 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001448 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1449 // the sync expression is typically a message expression that's already
1450 // been rewritten! (which implies the SourceLocation's are invalid).
1451 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001452 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001453 while (*endBuf != ')') endBuf--;
1454 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001455 buf = ");\n";
1456 // declare a new scope with two variables, _stack and _rethrow.
1457 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1458 buf += "int buf[18/*32-bit i386*/];\n";
1459 buf += "char *pointers[4];} _stack;\n";
1460 buf += "id volatile _rethrow = 0;\n";
1461 buf += "objc_exception_try_enter(&_stack);\n";
1462 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001463 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001464 startLoc = S->getSynchBody()->getLocEnd();
1465 startBuf = SM->getCharacterData(startLoc);
1466
Steve Naroffc7089f12008-08-19 13:04:19 +00001467 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001468 SourceLocation lastCurlyLoc = startLoc;
1469 buf = "}\nelse {\n";
1470 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1471 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001472 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001473 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001474 S->getSynchExpr(),
1475 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001476 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001477 std::string syncExprBufS;
1478 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001479 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001480 buf += syncExprBuf.str();
1481 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001482 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1483 buf += "}\n";
1484 buf += "}";
1485
Chris Lattneraadaf782008-01-31 19:51:04 +00001486 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001487 return 0;
1488}
1489
Steve Naroff8c565152008-12-05 17:03:39 +00001490void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1491 // Perform a bottom up traversal of all children.
1492 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1493 CI != E; ++CI)
1494 if (*CI)
1495 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1496
1497 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1498 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1499 Diags.Report(Context->getFullLoc(S->getLocStart()),
1500 TryFinallyContainsReturnDiag);
1501 }
1502 return;
1503}
1504
Steve Naroffb29b4272008-04-14 22:03:09 +00001505Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001506 // Get the start location and compute the semi location.
1507 SourceLocation startLoc = S->getLocStart();
1508 const char *startBuf = SM->getCharacterData(startLoc);
1509
1510 assert((*startBuf == '@') && "bogus @try location");
1511
1512 std::string buf;
1513 // declare a new scope with two variables, _stack and _rethrow.
1514 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1515 buf += "int buf[18/*32-bit i386*/];\n";
1516 buf += "char *pointers[4];} _stack;\n";
1517 buf += "id volatile _rethrow = 0;\n";
1518 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001519 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001520
Chris Lattneraadaf782008-01-31 19:51:04 +00001521 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001522
1523 startLoc = S->getTryBody()->getLocEnd();
1524 startBuf = SM->getCharacterData(startLoc);
1525
1526 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001527
Steve Naroff75730982007-11-07 04:08:17 +00001528 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001529 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1530 if (catchList) {
1531 startLoc = startLoc.getFileLocWithOffset(1);
1532 buf = " /* @catch begin */ else {\n";
1533 buf += " id _caught = objc_exception_extract(&_stack);\n";
1534 buf += " objc_exception_try_enter (&_stack);\n";
1535 buf += " if (_setjmp(_stack.buf))\n";
1536 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1537 buf += " else { /* @catch continue */";
1538
1539 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001540 } else { /* no catch list */
1541 buf = "}\nelse {\n";
1542 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1543 buf += "}";
1544 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001545 }
Steve Naroff75730982007-11-07 04:08:17 +00001546 bool sawIdTypedCatch = false;
1547 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001548 while (catchList) {
1549 Stmt *catchStmt = catchList->getCatchParamStmt();
1550
1551 if (catchList == S->getCatchStmts())
1552 buf = "if ("; // we are generating code for the first catch clause
1553 else
1554 buf = "else if (";
1555 startLoc = catchList->getLocStart();
1556 startBuf = SM->getCharacterData(startLoc);
1557
1558 assert((*startBuf == '@') && "bogus @catch location");
1559
1560 const char *lParenLoc = strchr(startBuf, '(');
1561
Steve Naroffbe4b3332008-02-01 22:08:12 +00001562 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001563 // Now rewrite the body...
1564 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001565 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1566 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001567 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1568 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001569 assert((*bodyBuf == '{') && "bogus @catch body location");
1570
1571 buf += "1) { id _tmp = _caught;";
1572 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1573 buf.c_str(), buf.size());
1574 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001575 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001576 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001577 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001578 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001579 sawIdTypedCatch = true;
1580 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001581 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001582
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001584 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001585 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001586 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001587 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001588 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001589 }
1590 }
1591 // Now rewrite the body...
1592 lastCatchBody = catchList->getCatchBody();
1593 SourceLocation rParenLoc = catchList->getRParenLoc();
1594 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1595 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1596 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1597 assert((*rParenBuf == ')') && "bogus @catch paren location");
1598 assert((*bodyBuf == '{') && "bogus @catch body location");
1599
1600 buf = " = _caught;";
1601 // Here we replace ") {" with "= _caught;" (which initializes and
1602 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001603 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001604 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001605 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001606 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001607 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001608 catchList = catchList->getNextCatchStmt();
1609 }
1610 // Complete the catch list...
1611 if (lastCatchBody) {
1612 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001613 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1614 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001615
Steve Naroff378f47a2008-09-11 15:29:03 +00001616 // Insert the last (implicit) else clause *before* the right curly brace.
1617 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1618 buf = "} /* last catch end */\n";
1619 buf += "else {\n";
1620 buf += " _rethrow = _caught;\n";
1621 buf += " objc_exception_try_exit(&_stack);\n";
1622 buf += "} } /* @catch end */\n";
1623 if (!S->getFinallyStmt())
1624 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001625 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001626
1627 // Set lastCurlyLoc
1628 lastCurlyLoc = lastCatchBody->getLocEnd();
1629 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001630 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001631 startLoc = finalStmt->getLocStart();
1632 startBuf = SM->getCharacterData(startLoc);
1633 assert((*startBuf == '@') && "bogus @finally start");
1634
1635 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001636 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001637
1638 Stmt *body = finalStmt->getFinallyBody();
1639 SourceLocation startLoc = body->getLocStart();
1640 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001641 assert(*SM->getCharacterData(startLoc) == '{' &&
1642 "bogus @finally body location");
1643 assert(*SM->getCharacterData(endLoc) == '}' &&
1644 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001645
1646 startLoc = startLoc.getFileLocWithOffset(1);
1647 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001648 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001649 endLoc = endLoc.getFileLocWithOffset(-1);
1650 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001651 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001652
1653 // Set lastCurlyLoc
1654 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001655
1656 // Now check for any return/continue/go statements within the @try.
1657 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001658 } else { /* no finally clause - make sure we synthesize an implicit one */
1659 buf = "{ /* implicit finally clause */\n";
1660 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1661 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1662 buf += "}";
1663 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001664 }
1665 // Now emit the final closing curly brace...
1666 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1667 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001668 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001669 return 0;
1670}
1671
Steve Naroffb29b4272008-04-14 22:03:09 +00001672Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001673 return 0;
1674}
1675
Steve Naroffb29b4272008-04-14 22:03:09 +00001676Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001677 return 0;
1678}
1679
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001680// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001681// the throw expression is typically a message expression that's already
1682// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001683Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001684 // Get the start location and compute the semi location.
1685 SourceLocation startLoc = S->getLocStart();
1686 const char *startBuf = SM->getCharacterData(startLoc);
1687
1688 assert((*startBuf == '@') && "bogus @throw location");
1689
1690 std::string buf;
1691 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001692 if (S->getThrowExpr())
1693 buf = "objc_exception_throw(";
1694 else // add an implicit argument
1695 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001696
1697 // handle "@ throw" correctly.
1698 const char *wBuf = strchr(startBuf, 'w');
1699 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1700 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1701
Steve Naroff2bd03922007-11-07 15:32:26 +00001702 const char *semiBuf = strchr(startBuf, ';');
1703 assert((*semiBuf == ';') && "@throw: can't find ';'");
1704 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1705 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001706 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001707 return 0;
1708}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001709
Steve Naroffb29b4272008-04-14 22:03:09 +00001710Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001711 // Create a new string expression.
1712 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001713 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001714 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001715 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1716 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001717 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001718 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001719
Chris Lattner07506182007-11-30 22:53:43 +00001720 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001721 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001722 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001723}
1724
Steve Naroffb29b4272008-04-14 22:03:09 +00001725Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001726 if (!SelGetUidFunctionDecl)
1727 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001728 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1729 // Create a call to sel_registerName("selName").
1730 llvm::SmallVector<Expr*, 8> SelExprs;
1731 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001732 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1733 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001734 false, argType, SourceLocation(),
1735 SourceLocation()));
1736 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1737 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001738 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001739 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001740 return SelExp;
1741}
1742
Steve Naroffb29b4272008-04-14 22:03:09 +00001743CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001744 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001745 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001746 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001747
1748 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001749 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001750
1751 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001752 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001753 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1754 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001755
1756 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001757
Steve Naroff934f2762007-10-24 22:48:43 +00001758 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1759}
1760
Steve Naroffd5255f52007-11-01 13:24:47 +00001761static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1762 const char *&startRef, const char *&endRef) {
1763 while (startBuf < endBuf) {
1764 if (*startBuf == '<')
1765 startRef = startBuf; // mark the start.
1766 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001767 if (startRef && *startRef == '<') {
1768 endRef = startBuf; // mark the end.
1769 return true;
1770 }
1771 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001772 }
1773 startBuf++;
1774 }
1775 return false;
1776}
1777
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001778static void scanToNextArgument(const char *&argRef) {
1779 int angle = 0;
1780 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1781 if (*argRef == '<')
1782 angle++;
1783 else if (*argRef == '>')
1784 angle--;
1785 argRef++;
1786 }
1787 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1788}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001789
Steve Naroffb29b4272008-04-14 22:03:09 +00001790bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001791
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001792 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001793 return true;
1794
Steve Naroffd5255f52007-11-01 13:24:47 +00001795 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001796 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001797 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001798 return true; // we have "Class <Protocol> *".
1799 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001800 return false;
1801}
1802
Steve Naroff4f95b752008-07-29 18:15:38 +00001803void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1804 QualType Type = E->getType();
1805 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001806 SourceLocation Loc, EndLoc;
1807
1808 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1809 Loc = ECE->getLParenLoc();
1810 EndLoc = ECE->getRParenLoc();
1811 } else {
1812 Loc = E->getLocStart();
1813 EndLoc = E->getLocEnd();
1814 }
1815 // This will defend against trying to rewrite synthesized expressions.
1816 if (Loc.isInvalid() || EndLoc.isInvalid())
1817 return;
1818
Steve Naroff4f95b752008-07-29 18:15:38 +00001819 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001820 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001821 const char *startRef = 0, *endRef = 0;
1822 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1823 // Get the locations of the startRef, endRef.
1824 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1825 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1826 // Comment out the protocol references.
1827 InsertText(LessLoc, "/*", 2);
1828 InsertText(GreaterLoc, "*/", 2);
1829 }
1830 }
1831}
1832
Steve Naroffb29b4272008-04-14 22:03:09 +00001833void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001834 SourceLocation Loc;
1835 QualType Type;
1836 const FunctionTypeProto *proto = 0;
1837 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1838 Loc = VD->getLocation();
1839 Type = VD->getType();
1840 }
1841 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1842 Loc = FD->getLocation();
1843 // Check for ObjC 'id' and class types that have been adorned with protocol
1844 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1845 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1846 assert(funcType && "missing function type");
1847 proto = dyn_cast<FunctionTypeProto>(funcType);
1848 if (!proto)
1849 return;
1850 Type = proto->getResultType();
1851 }
1852 else
1853 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001854
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001855 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001856 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001857
1858 const char *endBuf = SM->getCharacterData(Loc);
1859 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001860 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001861 startBuf--; // scan backward (from the decl location) for return type.
1862 const char *startRef = 0, *endRef = 0;
1863 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1864 // Get the locations of the startRef, endRef.
1865 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1866 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1867 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001868 InsertText(LessLoc, "/*", 2);
1869 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001870 }
1871 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001872 if (!proto)
1873 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001874 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001875 const char *startBuf = SM->getCharacterData(Loc);
1876 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001877 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1878 if (needToScanForQualifiers(proto->getArgType(i))) {
1879 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001880
Steve Naroffd5255f52007-11-01 13:24:47 +00001881 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001882 // scan forward (from the decl location) for argument types.
1883 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001884 const char *startRef = 0, *endRef = 0;
1885 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1886 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001887 SourceLocation LessLoc =
1888 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1889 SourceLocation GreaterLoc =
1890 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001891 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001892 InsertText(LessLoc, "/*", 2);
1893 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001894 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001895 startBuf = ++endBuf;
1896 }
1897 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001898 // If the function name is derived from a macro expansion, then the
1899 // argument buffer will not follow the name. Need to speak with Chris.
1900 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001901 startBuf++; // scan forward (from the decl location) for argument types.
1902 startBuf++;
1903 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001904 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001905}
1906
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001907// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001908void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001909 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1910 llvm::SmallVector<QualType, 16> ArgTys;
1911 ArgTys.push_back(Context->getPointerType(
1912 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001913 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001914 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001915 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001916 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001917 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001918 SelGetUidIdent, getFuncType,
1919 FunctionDecl::Extern, false, 0);
1920}
1921
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001922// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001923void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001924 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1925 llvm::SmallVector<QualType, 16> ArgTys;
1926 ArgTys.push_back(Context->getPointerType(
1927 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001928 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001929 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001930 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001931 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001932 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001933 SelGetProtoIdent, getFuncType,
1934 FunctionDecl::Extern, false, 0);
1935}
1936
Steve Naroffb29b4272008-04-14 22:03:09 +00001937void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001938 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001939 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001940 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001941 return;
1942 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001943 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001944}
1945
Steve Naroffc0a123c2008-03-11 17:37:02 +00001946// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001947void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001948 if (SuperContructorFunctionDecl)
1949 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001950 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001951 llvm::SmallVector<QualType, 16> ArgTys;
1952 QualType argT = Context->getObjCIdType();
1953 assert(!argT.isNull() && "Can't find 'id' type");
1954 ArgTys.push_back(argT);
1955 ArgTys.push_back(argT);
1956 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1957 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001958 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001959 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001960 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001961 msgSendIdent, msgSendType,
1962 FunctionDecl::Extern, false, 0);
1963}
1964
Steve Naroff09b266e2007-10-30 23:14:51 +00001965// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001966void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001967 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1968 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001970 assert(!argT.isNull() && "Can't find 'id' type");
1971 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001972 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001973 assert(!argT.isNull() && "Can't find 'SEL' type");
1974 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001975 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001976 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001977 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001978 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001979 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001980 msgSendIdent, msgSendType,
1981 FunctionDecl::Extern, false, 0);
1982}
1983
Steve Naroff874e2322007-11-15 10:28:18 +00001984// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001985void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001986 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1987 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001988 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001989 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001990 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001991 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1992 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1993 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001994 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001995 assert(!argT.isNull() && "Can't find 'SEL' type");
1996 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001998 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001999 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002000 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002001 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002002 msgSendIdent, msgSendType,
2003 FunctionDecl::Extern, false, 0);
2004}
2005
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002006// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002007void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002008 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2009 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002011 assert(!argT.isNull() && "Can't find 'id' type");
2012 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002014 assert(!argT.isNull() && "Can't find 'SEL' type");
2015 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002016 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002017 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002018 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002019 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002020 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002021 msgSendIdent, msgSendType,
2022 FunctionDecl::Extern, false, 0);
2023}
2024
2025// SynthMsgSendSuperStretFunctionDecl -
2026// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002027void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002028 IdentifierInfo *msgSendIdent =
2029 &Context->Idents.get("objc_msgSendSuper_stret");
2030 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002031 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002032 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002033 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002034 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2035 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2036 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002037 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002038 assert(!argT.isNull() && "Can't find 'SEL' type");
2039 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002040 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002042 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002043 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002044 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002045 msgSendIdent, msgSendType,
2046 FunctionDecl::Extern, false, 0);
2047}
2048
Steve Naroff1284db82008-05-08 22:02:18 +00002049// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002050void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002051 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2052 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002053 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002054 assert(!argT.isNull() && "Can't find 'id' type");
2055 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002056 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002057 assert(!argT.isNull() && "Can't find 'SEL' type");
2058 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002059 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002060 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002061 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002062 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002063 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002064 msgSendIdent, msgSendType,
2065 FunctionDecl::Extern, false, 0);
2066}
2067
Steve Naroff09b266e2007-10-30 23:14:51 +00002068// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002069void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002070 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2071 llvm::SmallVector<QualType, 16> ArgTys;
2072 ArgTys.push_back(Context->getPointerType(
2073 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002074 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002075 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002076 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002077 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002078 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002079 getClassIdent, getClassType,
2080 FunctionDecl::Extern, false, 0);
2081}
2082
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002083// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002084void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002085 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2086 llvm::SmallVector<QualType, 16> ArgTys;
2087 ArgTys.push_back(Context->getPointerType(
2088 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002090 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002091 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002092 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002093 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002094 getClassIdent, getClassType,
2095 FunctionDecl::Extern, false, 0);
2096}
2097
Steve Naroffb29b4272008-04-14 22:03:09 +00002098Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002099 QualType strType = getConstantStringStructType();
2100
2101 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002102
2103 std::string tmpName = InFileName;
2104 unsigned i;
2105 for (i=0; i < tmpName.length(); i++) {
2106 char c = tmpName.at(i);
2107 // replace any non alphanumeric characters with '_'.
2108 if (!isalpha(c) && (c < '0' || c > '9'))
2109 tmpName[i] = '_';
2110 }
2111 S += tmpName;
2112 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002113 S += utostr(NumObjCStringLiterals++);
2114
Steve Naroffba92b2e2008-03-27 22:29:16 +00002115 Preamble += "static __NSConstantStringImpl " + S;
2116 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2117 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002118 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002119 std::string prettyBufS;
2120 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002121 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002122 Preamble += prettyBuf.str();
2123 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002124 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002125 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002126
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002127 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002128 &Context->Idents.get(S.c_str()), strType,
2129 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002130 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2131 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2132 Context->getPointerType(DRE->getType()),
2133 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002134 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002135 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002136 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002137 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002138 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002139 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002140}
2141
Steve Naroffb29b4272008-04-14 22:03:09 +00002142ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002143 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002144 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002145
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002146 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2147 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002148 assert(PT);
2149 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2150 return IT->getDecl();
2151 }
2152 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002153}
2154
2155// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002156QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002157 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002158 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002159 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002160 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002161 QualType FieldTypes[2];
2162
2163 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002164 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002165 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002166 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002167
Steve Naroff874e2322007-11-15 10:28:18 +00002168 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002169 for (unsigned i = 0; i < 2; ++i) {
2170 SuperStructDecl->addDecl(*Context,
2171 FieldDecl::Create(*Context, SuperStructDecl,
2172 SourceLocation(), 0,
2173 FieldTypes[i], /*BitWidth=*/0,
2174 /*Mutable=*/false, 0),
2175 true);
2176 }
Steve Naroff874e2322007-11-15 10:28:18 +00002177
Douglas Gregor44b43212008-12-11 16:49:14 +00002178 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002179 }
2180 return Context->getTagDeclType(SuperStructDecl);
2181}
2182
Steve Naroffb29b4272008-04-14 22:03:09 +00002183QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002184 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002185 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002186 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002187 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002188 QualType FieldTypes[4];
2189
2190 // struct objc_object *receiver;
2191 FieldTypes[0] = Context->getObjCIdType();
2192 // int flags;
2193 FieldTypes[1] = Context->IntTy;
2194 // char *str;
2195 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2196 // long length;
2197 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002198
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002199 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002200 for (unsigned i = 0; i < 4; ++i) {
2201 ConstantStringDecl->addDecl(*Context,
2202 FieldDecl::Create(*Context,
2203 ConstantStringDecl,
2204 SourceLocation(), 0,
2205 FieldTypes[i],
2206 /*BitWidth=*/0,
2207 /*Mutable=*/true, 0),
2208 true);
2209 }
2210
2211 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002212 }
2213 return Context->getTagDeclType(ConstantStringDecl);
2214}
2215
Steve Naroffb29b4272008-04-14 22:03:09 +00002216Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002217 if (!SelGetUidFunctionDecl)
2218 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002219 if (!MsgSendFunctionDecl)
2220 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002221 if (!MsgSendSuperFunctionDecl)
2222 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002223 if (!MsgSendStretFunctionDecl)
2224 SynthMsgSendStretFunctionDecl();
2225 if (!MsgSendSuperStretFunctionDecl)
2226 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002227 if (!MsgSendFpretFunctionDecl)
2228 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002229 if (!GetClassFunctionDecl)
2230 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002231 if (!GetMetaClassFunctionDecl)
2232 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002233
Steve Naroff874e2322007-11-15 10:28:18 +00002234 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002235 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2236 // May need to use objc_msgSend_stret() as well.
2237 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002238 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002239 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002240 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002241 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002242 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002243 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002244 }
Steve Naroff874e2322007-11-15 10:28:18 +00002245
Steve Naroff934f2762007-10-24 22:48:43 +00002246 // Synthesize a call to objc_msgSend().
2247 llvm::SmallVector<Expr*, 8> MsgExprs;
2248 IdentifierInfo *clsName = Exp->getClassName();
2249
2250 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2251 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002252 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2253 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002254 if (!strcmp(clsName->getName(), "super")) {
2255 MsgSendFlavor = MsgSendSuperFunctionDecl;
2256 if (MsgSendStretFlavor)
2257 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2258 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2259
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002260 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002261 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002262
2263 llvm::SmallVector<Expr*, 4> InitExprs;
2264
2265 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002266 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002267 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002268 Context->getObjCIdType(),
2269 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002270 llvm::SmallVector<Expr*, 8> ClsExprs;
2271 QualType argType = Context->getPointerType(Context->CharTy);
2272 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2273 SuperDecl->getIdentifier()->getLength(),
2274 false, argType, SourceLocation(),
2275 SourceLocation()));
2276 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2277 &ClsExprs[0],
2278 ClsExprs.size());
2279 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002280 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002281 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002282 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002283 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002284 // struct objc_super
2285 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002286 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002287
Steve Naroff23f41272008-03-11 18:14:26 +00002288 if (LangOpts.Microsoft) {
2289 SynthSuperContructorFunctionDecl();
2290 // Simulate a contructor call...
2291 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2292 superType, SourceLocation());
2293 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2294 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002295 // The code for super is a little tricky to prevent collision with
2296 // the structure definition in the header. The rewriter has it's own
2297 // internal definition (__rw_objc_super) that is uses. This is why
2298 // we need the cast below. For example:
2299 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2300 //
2301 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2302 Context->getPointerType(SuperRep->getType()),
2303 SourceLocation());
2304 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2305 SuperRep, Context->getPointerType(superType),
2306 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002307 } else {
2308 // (struct objc_super) { <exprs from above> }
2309 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2310 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002311 SourceLocation(), false);
2312 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2313 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002314 // struct objc_super *
2315 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2316 Context->getPointerType(SuperRep->getType()),
2317 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002318 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002319 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002320 } else {
2321 llvm::SmallVector<Expr*, 8> ClsExprs;
2322 QualType argType = Context->getPointerType(Context->CharTy);
2323 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2324 clsName->getLength(),
2325 false, argType, SourceLocation(),
2326 SourceLocation()));
2327 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2328 &ClsExprs[0],
2329 ClsExprs.size());
2330 MsgExprs.push_back(Cls);
2331 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002332 } else { // instance message.
2333 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002334
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002335 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002336 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002337 if (MsgSendStretFlavor)
2338 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002339 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2340
2341 llvm::SmallVector<Expr*, 4> InitExprs;
2342
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002343 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002344 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002345 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002346 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002347 SourceLocation()),
2348 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002349 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002350
2351 llvm::SmallVector<Expr*, 8> ClsExprs;
2352 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002353 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2354 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002355 false, argType, SourceLocation(),
2356 SourceLocation()));
2357 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002358 &ClsExprs[0],
2359 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002360 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002361 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002362 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002363 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002364 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002365 // struct objc_super
2366 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002367 Expr *SuperRep;
2368
2369 if (LangOpts.Microsoft) {
2370 SynthSuperContructorFunctionDecl();
2371 // Simulate a contructor call...
2372 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2373 superType, SourceLocation());
2374 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2375 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002376 // The code for super is a little tricky to prevent collision with
2377 // the structure definition in the header. The rewriter has it's own
2378 // internal definition (__rw_objc_super) that is uses. This is why
2379 // we need the cast below. For example:
2380 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2381 //
2382 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2383 Context->getPointerType(SuperRep->getType()),
2384 SourceLocation());
2385 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2386 SuperRep, Context->getPointerType(superType),
2387 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002388 } else {
2389 // (struct objc_super) { <exprs from above> }
2390 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2391 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002392 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002393 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2394 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002395 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002396 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002397 // Remove all type-casts because it may contain objc-style types; e.g.
2398 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002399 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002400 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002401 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002402 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002403 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002404 MsgExprs.push_back(recExpr);
2405 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002406 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002407 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002408 llvm::SmallVector<Expr*, 8> SelExprs;
2409 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002410 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2411 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002412 false, argType, SourceLocation(),
2413 SourceLocation()));
2414 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2415 &SelExprs[0], SelExprs.size());
2416 MsgExprs.push_back(SelExp);
2417
2418 // Now push any user supplied arguments.
2419 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002420 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002421 // Make all implicit casts explicit...ICE comes in handy:-)
2422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2423 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002424 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002425 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002426 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002427 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002428 }
2429 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002430 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002432 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002433 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002434 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002435 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002436 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002437 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002438 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002439 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002440 // We've transferred the ownership to MsgExprs. Null out the argument in
2441 // the original expression, since we will delete it below.
2442 Exp->setArg(i, 0);
2443 }
Steve Naroffab972d32007-11-04 22:37:50 +00002444 // Generate the funky cast.
2445 CastExpr *cast;
2446 llvm::SmallVector<QualType, 8> ArgTypes;
2447 QualType returnType;
2448
2449 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002450 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2451 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2452 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002453 ArgTypes.push_back(Context->getObjCIdType());
2454 ArgTypes.push_back(Context->getObjCSelType());
2455 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002456 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002457 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2459 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002460 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002461 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002462 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002463 const BlockPointerType *BPT = t->getAsBlockPointerType();
2464 t = Context->getPointerType(BPT->getPointeeType());
2465 }
Steve Naroff352336b2007-11-05 14:36:37 +00002466 ArgTypes.push_back(t);
2467 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2469 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002470 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002472 }
2473 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002474 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002475
2476 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002477 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2478 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002479
2480 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2481 // If we don't do this cast, we get the following bizarre warning/note:
2482 // xx.m:13: warning: function called through a non-compatible type
2483 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002484 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002485 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002486 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002487
Steve Naroffab972d32007-11-04 22:37:50 +00002488 // Now do the "normal" pointer to function cast.
2489 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002490 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002491 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002492 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002493 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002494 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002495
2496 // Don't forget the parens to enforce the proper binding.
2497 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2498
2499 const FunctionType *FT = msgSendType->getAsFunctionType();
2500 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2501 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002502 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002503 if (MsgSendStretFlavor) {
2504 // We have the method which returns a struct/union. Must also generate
2505 // call to objc_msgSend_stret and hang both varieties on a conditional
2506 // expression which dictate which one to envoke depending on size of
2507 // method's return type.
2508
2509 // Create a reference to the objc_msgSend_stret() declaration.
2510 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2511 SourceLocation());
2512 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002513 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002514 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002515 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 // Now do the "normal" pointer to function cast.
2517 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002518 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002519 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002520 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002521 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002522
2523 // Don't forget the parens to enforce the proper binding.
2524 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2525
2526 FT = msgSendType->getAsFunctionType();
2527 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2528 FT->getResultType(), SourceLocation());
2529
2530 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002531 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2532 returnType.getAsOpaquePtr(),
2533 Context->getSizeType(),
2534 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2536 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2537 // For X86 it is more complicated and some kind of target specific routine
2538 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002539 unsigned IntSize =
2540 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002541 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2542 Context->IntTy,
2543 SourceLocation());
2544 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2545 BinaryOperator::LE,
2546 Context->IntTy,
2547 SourceLocation());
2548 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2549 ConditionalOperator *CondExpr =
2550 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002551 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002552 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002553 return ReplacingStmt;
2554}
2555
Steve Naroffb29b4272008-04-14 22:03:09 +00002556Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002557 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002558
Steve Naroffc77a6362008-12-04 16:24:46 +00002559 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002560 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002561 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002562
Steve Naroff4c3580e2008-12-04 23:50:32 +00002563 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002564 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002565}
2566
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002567/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2568/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002569Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002570 if (!GetProtocolFunctionDecl)
2571 SynthGetProtocolFunctionDecl();
2572 // Create a call to objc_getProtocol("ProtocolName").
2573 llvm::SmallVector<Expr*, 8> ProtoExprs;
2574 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002575 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2576 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002577 false, argType, SourceLocation(),
2578 SourceLocation()));
2579 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2580 &ProtoExprs[0],
2581 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002582 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002583 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002584 return ProtoExp;
2585
2586}
2587
Steve Naroffbaf58c32008-05-31 14:15:04 +00002588bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2589 const char *endBuf) {
2590 while (startBuf < endBuf) {
2591 if (*startBuf == '#') {
2592 // Skip whitespace.
2593 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2594 ;
2595 if (!strncmp(startBuf, "if", strlen("if")) ||
2596 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2597 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2598 !strncmp(startBuf, "define", strlen("define")) ||
2599 !strncmp(startBuf, "undef", strlen("undef")) ||
2600 !strncmp(startBuf, "else", strlen("else")) ||
2601 !strncmp(startBuf, "elif", strlen("elif")) ||
2602 !strncmp(startBuf, "endif", strlen("endif")) ||
2603 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2604 !strncmp(startBuf, "include", strlen("include")) ||
2605 !strncmp(startBuf, "import", strlen("import")) ||
2606 !strncmp(startBuf, "include_next", strlen("include_next")))
2607 return true;
2608 }
2609 startBuf++;
2610 }
2611 return false;
2612}
2613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002614/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002615/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002616void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002617 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002618 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002619 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002620 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002621 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002623 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002624 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002625 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002626 SourceLocation LocStart = CDecl->getLocStart();
2627 SourceLocation LocEnd = CDecl->getLocEnd();
2628
2629 const char *startBuf = SM->getCharacterData(LocStart);
2630 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002631
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002632 // If no ivars and no root or if its root, directly or indirectly,
2633 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002634 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2635 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002636 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002637 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002638 return;
2639 }
2640
2641 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002642 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002643 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002644 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002645 if (LangOpts.Microsoft)
2646 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002647
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002648 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002649 const char *cursor = strchr(startBuf, '{');
2650 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002652 // If the buffer contains preprocessor directives, we do more fine-grained
2653 // rewrites. This is intended to fix code that looks like (which occurs in
2654 // NSURL.h, for example):
2655 //
2656 // #ifdef XYZ
2657 // @interface Foo : NSObject
2658 // #else
2659 // @interface FooBar : NSObject
2660 // #endif
2661 // {
2662 // int i;
2663 // }
2664 // @end
2665 //
2666 // This clause is segregated to avoid breaking the common case.
2667 if (BufferContainsPPDirectives(startBuf, cursor)) {
2668 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2669 CDecl->getClassLoc();
2670 const char *endHeader = SM->getCharacterData(L);
2671 endHeader += Lexer::MeasureTokenLength(L, *SM);
2672
Chris Lattner3db6cae2008-07-21 18:19:38 +00002673 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002674 // advance to the end of the referenced protocols.
2675 while (endHeader < cursor && *endHeader != '>') endHeader++;
2676 endHeader++;
2677 }
2678 // rewrite the original header
2679 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2680 } else {
2681 // rewrite the original header *without* disturbing the '{'
2682 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2683 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002684 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002685 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002686 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002687 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002688 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002689 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002690
2691 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002692 SourceLocation OnePastCurly =
2693 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2694 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002695 }
2696 cursor++; // past '{'
2697
2698 // Now comment out any visibility specifiers.
2699 while (cursor < endBuf) {
2700 if (*cursor == '@') {
2701 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002702 // Skip whitespace.
2703 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2704 /*scan*/;
2705
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002706 // FIXME: presence of @public, etc. inside comment results in
2707 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002708 if (!strncmp(cursor, "public", strlen("public")) ||
2709 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002710 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002711 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002712 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002713 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002714 // FIXME: If there are cases where '<' is used in ivar declaration part
2715 // of user code, then scan the ivar list and use needToScanForQualifiers
2716 // for type checking.
2717 else if (*cursor == '<') {
2718 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002719 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002720 cursor = strchr(cursor, '>');
2721 cursor++;
2722 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002723 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002724 } else if (*cursor == '^') { // rewrite block specifier.
2725 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2726 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002727 }
Steve Narofffea763e82007-11-14 19:25:57 +00002728 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002729 }
Steve Narofffea763e82007-11-14 19:25:57 +00002730 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002731 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002732 } else { // we don't have any instance variables - insert super struct.
2733 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2734 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002735 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002736 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002737 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002738 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002739 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002740 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002741 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002742 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002743 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002744}
2745
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002746// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002747/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002748void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002749 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002750 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002752 const char *ClassName,
2753 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002754 if (MethodBegin == MethodEnd) return;
2755
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002756 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002757 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002758 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002759 SEL _cmd;
2760 char *method_types;
2761 void *_imp;
2762 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002763 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002764 Result += "\nstruct _objc_method {\n";
2765 Result += "\tSEL _cmd;\n";
2766 Result += "\tchar *method_types;\n";
2767 Result += "\tvoid *_imp;\n";
2768 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002769
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002770 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002771 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002772
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002773 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002774
2775 /* struct {
2776 struct _objc_method_list *next_method;
2777 int method_count;
2778 struct _objc_method method_list[];
2779 }
2780 */
2781 Result += "\nstatic struct {\n";
2782 Result += "\tstruct _objc_method_list *next_method;\n";
2783 Result += "\tint method_count;\n";
2784 Result += "\tstruct _objc_method method_list[";
2785 Result += utostr(MethodEnd-MethodBegin);
2786 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002787 Result += prefix;
2788 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2789 Result += "_METHODS_";
2790 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002791 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002792 Result += IsInstanceMethod ? "inst" : "cls";
2793 Result += "_meth\")))= ";
2794 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002795
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002796 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002797 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002798 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002799 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002800 Result += "\", \"";
2801 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002802 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002803 Result += MethodInternalNames[*MethodBegin];
2804 Result += "}\n";
2805 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2806 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002807 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002808 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002809 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002810 Result += "\", \"";
2811 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002812 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002813 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002814 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002815 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002816 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002817}
2818
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002819/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002820void RewriteObjC::
2821RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2822 const char *prefix,
2823 const char *ClassName,
2824 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002825 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002826 if (Protocols.empty()) return;
2827
2828 for (unsigned i = 0; i != Protocols.size(); i++) {
2829 ObjCProtocolDecl *PDecl = Protocols[i];
2830 // Output struct protocol_methods holder of method selector and type.
2831 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2832 /* struct protocol_methods {
2833 SEL _cmd;
2834 char *method_types;
2835 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002836 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002837 Result += "\nstruct protocol_methods {\n";
2838 Result += "\tSEL _cmd;\n";
2839 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002840 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002841
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002842 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002843 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002844 // Do not synthesize the protocol more than once.
2845 if (ObjCSynthesizedProtocols.count(PDecl))
2846 continue;
2847
2848 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2849 unsigned NumMethods = PDecl->getNumInstanceMethods();
2850 /* struct _objc_protocol_method_list {
2851 int protocol_method_count;
2852 struct protocol_methods protocols[];
2853 }
2854 */
2855 Result += "\nstatic struct {\n";
2856 Result += "\tint protocol_method_count;\n";
2857 Result += "\tstruct protocol_methods protocols[";
2858 Result += utostr(NumMethods);
2859 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002860 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002861 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2862 "{\n\t" + utostr(NumMethods) + "\n";
2863
2864 // Output instance methods declared in this protocol.
2865 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2866 E = PDecl->instmeth_end(); I != E; ++I) {
2867 if (I == PDecl->instmeth_begin())
2868 Result += "\t ,{{(SEL)\"";
2869 else
2870 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002871 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002872 std::string MethodTypeString;
2873 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2874 Result += "\", \"";
2875 Result += MethodTypeString;
2876 Result += "\"}\n";
2877 }
2878 Result += "\t }\n};\n";
2879 }
2880
2881 // Output class methods declared in this protocol.
2882 int NumMethods = PDecl->getNumClassMethods();
2883 if (NumMethods > 0) {
2884 /* struct _objc_protocol_method_list {
2885 int protocol_method_count;
2886 struct protocol_methods protocols[];
2887 }
2888 */
2889 Result += "\nstatic struct {\n";
2890 Result += "\tint protocol_method_count;\n";
2891 Result += "\tstruct protocol_methods protocols[";
2892 Result += utostr(NumMethods);
2893 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002894 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002895 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2896 "{\n\t";
2897 Result += utostr(NumMethods);
2898 Result += "\n";
2899
2900 // Output instance methods declared in this protocol.
2901 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2902 E = PDecl->classmeth_end(); I != E; ++I) {
2903 if (I == PDecl->classmeth_begin())
2904 Result += "\t ,{{(SEL)\"";
2905 else
2906 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002907 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002908 std::string MethodTypeString;
2909 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2910 Result += "\", \"";
2911 Result += MethodTypeString;
2912 Result += "\"}\n";
2913 }
2914 Result += "\t }\n};\n";
2915 }
2916
2917 // Output:
2918 /* struct _objc_protocol {
2919 // Objective-C 1.0 extensions
2920 struct _objc_protocol_extension *isa;
2921 char *protocol_name;
2922 struct _objc_protocol **protocol_list;
2923 struct _objc_protocol_method_list *instance_methods;
2924 struct _objc_protocol_method_list *class_methods;
2925 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002926 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002927 static bool objc_protocol = false;
2928 if (!objc_protocol) {
2929 Result += "\nstruct _objc_protocol {\n";
2930 Result += "\tstruct _objc_protocol_extension *isa;\n";
2931 Result += "\tchar *protocol_name;\n";
2932 Result += "\tstruct _objc_protocol **protocol_list;\n";
2933 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2934 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2935 Result += "};\n";
2936
2937 objc_protocol = true;
2938 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002939
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002940 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002941 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002942 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2943 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002944 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002945 Result += "\", 0, ";
2946 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2947 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002948 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002949 Result += ", ";
2950 }
2951 else
2952 Result += "0, ";
2953 if (PDecl->getNumClassMethods() > 0) {
2954 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002955 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002956 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002957 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002958 else
2959 Result += "0\n";
2960 Result += "};\n";
2961
2962 // Mark this protocol as having been generated.
2963 if (!ObjCSynthesizedProtocols.insert(PDecl))
2964 assert(false && "protocol already synthesized");
2965 }
2966 // Output the top lovel protocol meta-data for the class.
2967 /* struct _objc_protocol_list {
2968 struct _objc_protocol_list *next;
2969 int protocol_count;
2970 struct _objc_protocol *class_protocols[];
2971 }
2972 */
2973 Result += "\nstatic struct {\n";
2974 Result += "\tstruct _objc_protocol_list *next;\n";
2975 Result += "\tint protocol_count;\n";
2976 Result += "\tstruct _objc_protocol *class_protocols[";
2977 Result += utostr(Protocols.size());
2978 Result += "];\n} _OBJC_";
2979 Result += prefix;
2980 Result += "_PROTOCOLS_";
2981 Result += ClassName;
2982 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2983 "{\n\t0, ";
2984 Result += utostr(Protocols.size());
2985 Result += "\n";
2986
2987 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002988 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002989 Result += " \n";
2990
2991 for (unsigned i = 1; i != Protocols.size(); i++) {
2992 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002993 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002994 Result += "\n";
2995 }
2996 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002997}
2998
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003000/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003001void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003003 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003004 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003005 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003006 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3007 CDecl = CDecl->getNextClassCategory())
3008 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3009 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003010
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003011 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003012 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003013 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003014
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003015 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003017 true, "CATEGORY_", FullCategoryName.c_str(),
3018 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019
3020 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003021 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003022 false, "CATEGORY_", FullCategoryName.c_str(),
3023 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024
3025 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003026 // Null CDecl is case of a category implementation with no category interface
3027 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003028 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003029 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003030
3031 /* struct _objc_category {
3032 char *category_name;
3033 char *class_name;
3034 struct _objc_method_list *instance_methods;
3035 struct _objc_method_list *class_methods;
3036 struct _objc_protocol_list *protocols;
3037 // Objective-C 1.0 extensions
3038 uint32_t size; // sizeof (struct _objc_category)
3039 struct _objc_property_list *instance_properties; // category's own
3040 // @property decl.
3041 };
3042 */
3043
3044 static bool objc_category = false;
3045 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003046 Result += "\nstruct _objc_category {\n";
3047 Result += "\tchar *category_name;\n";
3048 Result += "\tchar *class_name;\n";
3049 Result += "\tstruct _objc_method_list *instance_methods;\n";
3050 Result += "\tstruct _objc_method_list *class_methods;\n";
3051 Result += "\tstruct _objc_protocol_list *protocols;\n";
3052 Result += "\tunsigned int size;\n";
3053 Result += "\tstruct _objc_property_list *instance_properties;\n";
3054 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003055 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003056 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003057 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3058 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003059 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003060 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003062 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003064
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003065 if (IDecl->getNumInstanceMethods() > 0) {
3066 Result += "\t, (struct _objc_method_list *)"
3067 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3068 Result += FullCategoryName;
3069 Result += "\n";
3070 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003071 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += "\t, 0\n";
3073 if (IDecl->getNumClassMethods() > 0) {
3074 Result += "\t, (struct _objc_method_list *)"
3075 "&_OBJC_CATEGORY_CLASS_METHODS_";
3076 Result += FullCategoryName;
3077 Result += "\n";
3078 }
3079 else
3080 Result += "\t, 0\n";
3081
Chris Lattner780f3292008-07-21 21:32:27 +00003082 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003083 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3084 Result += FullCategoryName;
3085 Result += "\n";
3086 }
3087 else
3088 Result += "\t, 0\n";
3089 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003090}
3091
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003092/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3093/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003094void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003095 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003096 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003097 if (ivar->isBitField()) {
3098 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3099 // place all bitfields at offset 0.
3100 Result += "0";
3101 } else {
3102 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003103 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003104 if (LangOpts.Microsoft)
3105 Result += "_IMPL";
3106 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003107 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003108 Result += ")";
3109 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003110}
3111
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003112//===----------------------------------------------------------------------===//
3113// Meta Data Emission
3114//===----------------------------------------------------------------------===//
3115
Steve Naroffb29b4272008-04-14 22:03:09 +00003116void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003119
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003120 // Explictly declared @interface's are already synthesized.
3121 if (CDecl->ImplicitInterfaceDecl()) {
3122 // FIXME: Implementation of a class with no @interface (legacy) doese not
3123 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003124 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003125 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003126
Chris Lattnerbe6df082007-12-12 07:56:42 +00003127 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003128 unsigned NumIvars = !IDecl->ivar_empty()
3129 ? IDecl->ivar_size()
3130 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003131 if (NumIvars > 0) {
3132 static bool objc_ivar = false;
3133 if (!objc_ivar) {
3134 /* struct _objc_ivar {
3135 char *ivar_name;
3136 char *ivar_type;
3137 int ivar_offset;
3138 };
3139 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003140 Result += "\nstruct _objc_ivar {\n";
3141 Result += "\tchar *ivar_name;\n";
3142 Result += "\tchar *ivar_type;\n";
3143 Result += "\tint ivar_offset;\n";
3144 Result += "};\n";
3145
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003146 objc_ivar = true;
3147 }
3148
Steve Naroff946a6932008-03-11 00:12:29 +00003149 /* struct {
3150 int ivar_count;
3151 struct _objc_ivar ivar_list[nIvars];
3152 };
3153 */
3154 Result += "\nstatic struct {\n";
3155 Result += "\tint ivar_count;\n";
3156 Result += "\tstruct _objc_ivar ivar_list[";
3157 Result += utostr(NumIvars);
3158 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003159 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003160 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003161 "{\n\t";
3162 Result += utostr(NumIvars);
3163 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003164
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003166 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003167 IVI = IDecl->ivar_begin();
3168 IVE = IDecl->ivar_end();
3169 } else {
3170 IVI = CDecl->ivar_begin();
3171 IVE = CDecl->ivar_end();
3172 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003173 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003174 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003175 Result += "\", \"";
3176 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003177 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003178 Result += StrEncoding;
3179 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003180 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003181 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003182 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003183 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003184 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003185 Result += "\", \"";
3186 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003187 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003188 Result += StrEncoding;
3189 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003190 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003191 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003192 }
3193
3194 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003195 }
3196
3197 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003199 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003200
3201 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003202 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003203 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003204
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003206 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003207 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003208
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003209
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003210 // Declaration of class/meta-class metadata
3211 /* struct _objc_class {
3212 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003213 const char *super_class_name;
3214 char *name;
3215 long version;
3216 long info;
3217 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003218 struct _objc_ivar_list *ivars;
3219 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003220 struct objc_cache *cache;
3221 struct objc_protocol_list *protocols;
3222 const char *ivar_layout;
3223 struct _objc_class_ext *ext;
3224 };
3225 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003226 static bool objc_class = false;
3227 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003228 Result += "\nstruct _objc_class {\n";
3229 Result += "\tstruct _objc_class *isa;\n";
3230 Result += "\tconst char *super_class_name;\n";
3231 Result += "\tchar *name;\n";
3232 Result += "\tlong version;\n";
3233 Result += "\tlong info;\n";
3234 Result += "\tlong instance_size;\n";
3235 Result += "\tstruct _objc_ivar_list *ivars;\n";
3236 Result += "\tstruct _objc_method_list *methods;\n";
3237 Result += "\tstruct objc_cache *cache;\n";
3238 Result += "\tstruct _objc_protocol_list *protocols;\n";
3239 Result += "\tconst char *ivar_layout;\n";
3240 Result += "\tstruct _objc_class_ext *ext;\n";
3241 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003242 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003243 }
3244
3245 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003246 ObjCInterfaceDecl *RootClass = 0;
3247 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003248 while (SuperClass) {
3249 RootClass = SuperClass;
3250 SuperClass = SuperClass->getSuperClass();
3251 }
3252 SuperClass = CDecl->getSuperClass();
3253
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003254 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003255 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003256 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003257 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003258 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003259 Result += "\"";
3260
3261 if (SuperClass) {
3262 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003263 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003264 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003265 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003266 Result += "\"";
3267 }
3268 else {
3269 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003270 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003271 Result += "\"";
3272 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003273 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003274 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003275 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003276 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003277 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += "\n";
3280 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003281 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003282 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003283 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003284 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 Result += ",0,0\n";
3287 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003288 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "\t,0,0,0,0\n";
3290 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003291
3292 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003294 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003295 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003297 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003298 if (SuperClass) {
3299 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003300 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003301 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003302 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003303 Result += "\"";
3304 }
3305 else {
3306 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003307 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003308 Result += "\"";
3309 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003310 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003311 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003313 Result += ",0";
3314 else {
3315 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003316 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003317 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003318 if (LangOpts.Microsoft)
3319 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003320 Result += ")";
3321 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003322 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003323 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003324 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003325 Result += "\n\t";
3326 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003327 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += ",0";
3329 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003330 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003332 Result += ", 0\n\t";
3333 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003334 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003335 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003336 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003337 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003338 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += ", 0,0\n";
3340 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003341 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003342 Result += ",0,0,0\n";
3343 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003344}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003345
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003346/// RewriteImplementations - This routine rewrites all method implementations
3347/// and emits meta-data.
3348
Steve Narofface66252008-11-13 20:07:04 +00003349void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003350 int ClsDefCount = ClassImplementation.size();
3351 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003352
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003353 // Rewrite implemented methods
3354 for (int i = 0; i < ClsDefCount; i++)
3355 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003356
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003357 for (int i = 0; i < CatDefCount; i++)
3358 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003359}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003360
Steve Narofface66252008-11-13 20:07:04 +00003361void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3362 int ClsDefCount = ClassImplementation.size();
3363 int CatDefCount = CategoryImplementation.size();
3364
Steve Naroff5df5b762008-05-07 21:23:49 +00003365 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003366 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003367 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003368 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003369 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003370
3371 // For each implemented category, write out all its meta data.
3372 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003373 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003374
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003375 // Write objc_symtab metadata
3376 /*
3377 struct _objc_symtab
3378 {
3379 long sel_ref_cnt;
3380 SEL *refs;
3381 short cls_def_cnt;
3382 short cat_def_cnt;
3383 void *defs[cls_def_cnt + cat_def_cnt];
3384 };
3385 */
3386
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003387 Result += "\nstruct _objc_symtab {\n";
3388 Result += "\tlong sel_ref_cnt;\n";
3389 Result += "\tSEL *refs;\n";
3390 Result += "\tshort cls_def_cnt;\n";
3391 Result += "\tshort cat_def_cnt;\n";
3392 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3393 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003394
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003395 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003396 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003397 Result += "\t0, 0, " + utostr(ClsDefCount)
3398 + ", " + utostr(CatDefCount) + "\n";
3399 for (int i = 0; i < ClsDefCount; i++) {
3400 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003401 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003402 Result += "\n";
3403 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003404
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003405 for (int i = 0; i < CatDefCount; i++) {
3406 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003407 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003408 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003409 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\n";
3411 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003412
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003413 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003414
3415 // Write objc_module metadata
3416
3417 /*
3418 struct _objc_module {
3419 long version;
3420 long size;
3421 const char *name;
3422 struct _objc_symtab *symtab;
3423 }
3424 */
3425
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003426 Result += "\nstruct _objc_module {\n";
3427 Result += "\tlong version;\n";
3428 Result += "\tlong size;\n";
3429 Result += "\tconst char *name;\n";
3430 Result += "\tstruct _objc_symtab *symtab;\n";
3431 Result += "};\n\n";
3432 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003433 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003434 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3435 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003436 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003437
3438 if (LangOpts.Microsoft) {
3439 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003440 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003441 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3442 Result += "&_OBJC_MODULES;\n";
3443 Result += "#pragma data_seg(pop)\n\n";
3444 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003445}
Chris Lattner311ff022007-10-16 22:36:42 +00003446
Steve Naroff54055232008-10-27 17:20:55 +00003447std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3448 const char *funcName,
3449 std::string Tag) {
3450 const FunctionType *AFT = CE->getFunctionType();
3451 QualType RT = AFT->getResultType();
3452 std::string StructRef = "struct " + Tag;
3453 std::string S = "static " + RT.getAsString() + " __" +
3454 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003455
Steve Naroff54055232008-10-27 17:20:55 +00003456 BlockDecl *BD = CE->getBlockDecl();
3457
3458 if (isa<FunctionTypeNoProto>(AFT)) {
3459 S += "()";
3460 } else if (BD->param_empty()) {
3461 S += "(" + StructRef + " *__cself)";
3462 } else {
3463 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3464 assert(FT && "SynthesizeBlockFunc: No function proto");
3465 S += '(';
3466 // first add the implicit argument.
3467 S += StructRef + " *__cself, ";
3468 std::string ParamStr;
3469 for (BlockDecl::param_iterator AI = BD->param_begin(),
3470 E = BD->param_end(); AI != E; ++AI) {
3471 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003472 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003473 (*AI)->getType().getAsStringInternal(ParamStr);
3474 S += ParamStr;
3475 }
3476 if (FT->isVariadic()) {
3477 if (!BD->param_empty()) S += ", ";
3478 S += "...";
3479 }
3480 S += ')';
3481 }
3482 S += " {\n";
3483
3484 // Create local declarations to avoid rewriting all closure decl ref exprs.
3485 // First, emit a declaration for all "by ref" decls.
3486 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3487 E = BlockByRefDecls.end(); I != E; ++I) {
3488 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003489 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003490 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003491 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003492 }
3493 // Next, emit a declaration for all "by copy" declarations.
3494 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3495 E = BlockByCopyDecls.end(); I != E; ++I) {
3496 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003497 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003498 // Handle nested closure invocation. For example:
3499 //
3500 // void (^myImportedClosure)(void);
3501 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3502 //
3503 // void (^anotherClosure)(void);
3504 // anotherClosure = ^(void) {
3505 // myImportedClosure(); // import and invoke the closure
3506 // };
3507 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003508 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003509 S += "struct __block_impl *";
3510 else
3511 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003512 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003513 }
3514 std::string RewrittenStr = RewrittenBlockExprs[CE];
3515 const char *cstr = RewrittenStr.c_str();
3516 while (*cstr++ != '{') ;
3517 S += cstr;
3518 S += "\n";
3519 return S;
3520}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003521
Steve Naroff54055232008-10-27 17:20:55 +00003522std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3523 const char *funcName,
3524 std::string Tag) {
3525 std::string StructRef = "struct " + Tag;
3526 std::string S = "static void __";
3527
3528 S += funcName;
3529 S += "_block_copy_" + utostr(i);
3530 S += "(" + StructRef;
3531 S += "*dst, " + StructRef;
3532 S += "*src) {";
3533 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3534 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003535 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003536 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003537 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003538 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003539 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003540 }
3541 S += "\nstatic void __";
3542 S += funcName;
3543 S += "_block_dispose_" + utostr(i);
3544 S += "(" + StructRef;
3545 S += "*src) {";
3546 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3547 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003548 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003549 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003550 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003551 }
3552 S += "}\n";
3553 return S;
3554}
3555
3556std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3557 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003558 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003559 std::string Constructor = " " + Tag;
3560
3561 S += " {\n struct __block_impl impl;\n";
3562
3563 if (hasCopyDisposeHelpers)
3564 S += " void *copy;\n void *dispose;\n";
3565
3566 Constructor += "(void *fp";
3567
3568 if (hasCopyDisposeHelpers)
3569 Constructor += ", void *copyHelp, void *disposeHelp";
3570
3571 if (BlockDeclRefs.size()) {
3572 // Output all "by copy" declarations.
3573 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3574 E = BlockByCopyDecls.end(); I != E; ++I) {
3575 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003576 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003577 std::string ArgName = "_" + FieldName;
3578 // Handle nested closure invocation. For example:
3579 //
3580 // void (^myImportedBlock)(void);
3581 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3582 //
3583 // void (^anotherBlock)(void);
3584 // anotherBlock = ^(void) {
3585 // myImportedBlock(); // import and invoke the closure
3586 // };
3587 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003588 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003589 S += "struct __block_impl *";
3590 Constructor += ", void *" + ArgName;
3591 } else {
3592 (*I)->getType().getAsStringInternal(FieldName);
3593 (*I)->getType().getAsStringInternal(ArgName);
3594 Constructor += ", " + ArgName;
3595 }
3596 S += FieldName + ";\n";
3597 }
3598 // Output all "by ref" declarations.
3599 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3600 E = BlockByRefDecls.end(); I != E; ++I) {
3601 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003602 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003603 std::string ArgName = "_" + FieldName;
3604 // Handle nested closure invocation. For example:
3605 //
3606 // void (^myImportedBlock)(void);
3607 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3608 //
3609 // void (^anotherBlock)(void);
3610 // anotherBlock = ^(void) {
3611 // myImportedBlock(); // import and invoke the closure
3612 // };
3613 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003614 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003615 S += "struct __block_impl *";
3616 Constructor += ", void *" + ArgName;
3617 } else {
3618 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3619 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3620 Constructor += ", " + ArgName;
3621 }
3622 S += FieldName + "; // by ref\n";
3623 }
3624 // Finish writing the constructor.
3625 // FIXME: handle NSConcreteGlobalBlock.
3626 Constructor += ", int flags=0) {\n";
3627 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3628 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3629
3630 if (hasCopyDisposeHelpers)
3631 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3632
3633 // Initialize all "by copy" arguments.
3634 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3635 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003636 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003637 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003638 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003639 Constructor += Name + " = (struct __block_impl *)_";
3640 else
3641 Constructor += Name + " = _";
3642 Constructor += Name + ";\n";
3643 }
3644 // Initialize all "by ref" arguments.
3645 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3646 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003647 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003648 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003649 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003650 Constructor += Name + " = (struct __block_impl *)_";
3651 else
3652 Constructor += Name + " = _";
3653 Constructor += Name + ";\n";
3654 }
3655 } else {
3656 // Finish writing the constructor.
3657 // FIXME: handle NSConcreteGlobalBlock.
3658 Constructor += ", int flags=0) {\n";
3659 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3660 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3661 if (hasCopyDisposeHelpers)
3662 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3663 }
3664 Constructor += " ";
3665 Constructor += "}\n";
3666 S += Constructor;
3667 S += "};\n";
3668 return S;
3669}
3670
3671void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3672 const char *FunName) {
3673 // Insert closures that were part of the function.
3674 for (unsigned i = 0; i < Blocks.size(); i++) {
3675
3676 CollectBlockDeclRefInfo(Blocks[i]);
3677
3678 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3679
3680 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3681 ImportedBlockDecls.size() > 0);
3682
3683 InsertText(FunLocStart, CI.c_str(), CI.size());
3684
3685 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3686
3687 InsertText(FunLocStart, CF.c_str(), CF.size());
3688
3689 if (ImportedBlockDecls.size()) {
3690 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3691 InsertText(FunLocStart, HF.c_str(), HF.size());
3692 }
3693
3694 BlockDeclRefs.clear();
3695 BlockByRefDecls.clear();
3696 BlockByCopyDecls.clear();
3697 BlockCallExprs.clear();
3698 ImportedBlockDecls.clear();
3699 }
3700 Blocks.clear();
3701 RewrittenBlockExprs.clear();
3702}
3703
3704void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3705 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003706 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003707
3708 SynthesizeBlockLiterals(FunLocStart, FuncName);
3709}
3710
3711void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003712 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3713 //SourceLocation FunLocStart = MD->getLocStart();
3714 // FIXME: This hack works around a bug in Rewrite.InsertText().
3715 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003716 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003717 // Convert colons to underscores.
3718 std::string::size_type loc = 0;
3719 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3720 FuncName.replace(loc, 1, "_");
3721
3722 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3723}
3724
3725void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3726 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3727 CI != E; ++CI)
3728 if (*CI) {
3729 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3730 GetBlockDeclRefExprs(CBE->getBody());
3731 else
3732 GetBlockDeclRefExprs(*CI);
3733 }
3734 // Handle specific things.
3735 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3736 // FIXME: Handle enums.
3737 if (!isa<FunctionDecl>(CDRE->getDecl()))
3738 BlockDeclRefs.push_back(CDRE);
3739 return;
3740}
3741
3742void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3743 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3744 CI != E; ++CI)
3745 if (*CI) {
3746 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3747 GetBlockCallExprs(CBE->getBody());
3748 else
3749 GetBlockCallExprs(*CI);
3750 }
3751
3752 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3753 if (CE->getCallee()->getType()->isBlockPointerType()) {
3754 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3755 }
3756 }
3757 return;
3758}
3759
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003760Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003761 // Navigate to relevant type information.
3762 const char *closureName = 0;
3763 const BlockPointerType *CPT = 0;
3764
3765 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003766 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003767 CPT = DRE->getType()->getAsBlockPointerType();
3768 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003769 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003770 CPT = CDRE->getType()->getAsBlockPointerType();
3771 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003772 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003773 CPT = MExpr->getType()->getAsBlockPointerType();
3774 } else {
3775 assert(1 && "RewriteBlockClass: Bad type");
3776 }
3777 assert(CPT && "RewriteBlockClass: Bad type");
3778 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3779 assert(FT && "RewriteBlockClass: Bad type");
3780 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3781 // FTP will be null for closures that don't take arguments.
3782
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003783 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3784 SourceLocation(),
3785 &Context->Idents.get("__block_impl"));
3786 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003787
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003788 // Generate a funky cast.
3789 llvm::SmallVector<QualType, 8> ArgTypes;
3790
3791 // Push the block argument type.
3792 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003793 if (FTP) {
3794 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003795 E = FTP->arg_type_end(); I && (I != E); ++I) {
3796 QualType t = *I;
3797 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003798 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003799 const BlockPointerType *BPT = t->getAsBlockPointerType();
3800 t = Context->getPointerType(BPT->getPointeeType());
3801 }
3802 ArgTypes.push_back(t);
3803 }
Steve Naroff54055232008-10-27 17:20:55 +00003804 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003805 // Now do the pointer to function cast.
3806 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3807 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3808
3809 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003810
Steve Naroffb2f9e512008-11-03 23:29:32 +00003811 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003812 // Don't forget the parens to enforce the proper binding.
3813 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3814 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003815
Douglas Gregor44b43212008-12-11 16:49:14 +00003816 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3817 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
3818 /*BitWidth=*/0, /*Mutable=*/true, 0);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003819 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3820
Steve Naroffb2f9e512008-11-03 23:29:32 +00003821 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003822 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3823
3824 llvm::SmallVector<Expr*, 8> BlkExprs;
3825 // Add the implicit argument.
3826 BlkExprs.push_back(BlkCast);
3827 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003828 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3829 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003831 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003832 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3833 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003834}
3835
3836void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003837 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3838 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003839}
3840
3841void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3842 // FIXME: Add more elaborate code generation required by the ABI.
3843 InsertText(BDRE->getLocStart(), "*", 1);
3844}
3845
Steve Naroffb2f9e512008-11-03 23:29:32 +00003846void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3847 SourceLocation LocStart = CE->getLParenLoc();
3848 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003849
3850 // Need to avoid trying to rewrite synthesized casts.
3851 if (LocStart.isInvalid())
3852 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003853 // Need to avoid trying to rewrite casts contained in macros.
3854 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3855 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003856
Steve Naroff54055232008-10-27 17:20:55 +00003857 const char *startBuf = SM->getCharacterData(LocStart);
3858 const char *endBuf = SM->getCharacterData(LocEnd);
3859
3860 // advance the location to startArgList.
3861 const char *argPtr = startBuf;
3862
3863 while (*argPtr++ && (argPtr < endBuf)) {
3864 switch (*argPtr) {
3865 case '^':
3866 // Replace the '^' with '*'.
3867 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3868 ReplaceText(LocStart, 1, "*", 1);
3869 break;
3870 }
3871 }
3872 return;
3873}
3874
3875void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3876 SourceLocation DeclLoc = FD->getLocation();
3877 unsigned parenCount = 0;
3878
3879 // We have 1 or more arguments that have closure pointers.
3880 const char *startBuf = SM->getCharacterData(DeclLoc);
3881 const char *startArgList = strchr(startBuf, '(');
3882
3883 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3884
3885 parenCount++;
3886 // advance the location to startArgList.
3887 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3888 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3889
3890 const char *argPtr = startArgList;
3891
3892 while (*argPtr++ && parenCount) {
3893 switch (*argPtr) {
3894 case '^':
3895 // Replace the '^' with '*'.
3896 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3897 ReplaceText(DeclLoc, 1, "*", 1);
3898 break;
3899 case '(':
3900 parenCount++;
3901 break;
3902 case ')':
3903 parenCount--;
3904 break;
3905 }
3906 }
3907 return;
3908}
3909
3910bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3911 const FunctionTypeProto *FTP;
3912 const PointerType *PT = QT->getAsPointerType();
3913 if (PT) {
3914 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3915 } else {
3916 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3917 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3918 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3919 }
3920 if (FTP) {
3921 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3922 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003923 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003924 return true;
3925 }
3926 return false;
3927}
3928
3929void RewriteObjC::GetExtentOfArgList(const char *Name,
3930 const char *&LParen, const char *&RParen) {
3931 const char *argPtr = strchr(Name, '(');
3932 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3933
3934 LParen = argPtr; // output the start.
3935 argPtr++; // skip past the left paren.
3936 unsigned parenCount = 1;
3937
3938 while (*argPtr && parenCount) {
3939 switch (*argPtr) {
3940 case '(': parenCount++; break;
3941 case ')': parenCount--; break;
3942 default: break;
3943 }
3944 if (parenCount) argPtr++;
3945 }
3946 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3947 RParen = argPtr; // output the end
3948}
3949
3950void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3951 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3952 RewriteBlockPointerFunctionArgs(FD);
3953 return;
3954 }
3955 // Handle Variables and Typedefs.
3956 SourceLocation DeclLoc = ND->getLocation();
3957 QualType DeclT;
3958 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3959 DeclT = VD->getType();
3960 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3961 DeclT = TDD->getUnderlyingType();
3962 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3963 DeclT = FD->getType();
3964 else
3965 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3966
3967 const char *startBuf = SM->getCharacterData(DeclLoc);
3968 const char *endBuf = startBuf;
3969 // scan backward (from the decl location) for the end of the previous decl.
3970 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3971 startBuf--;
3972
3973 // *startBuf != '^' if we are dealing with a pointer to function that
3974 // may take block argument types (which will be handled below).
3975 if (*startBuf == '^') {
3976 // Replace the '^' with '*', computing a negative offset.
3977 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3978 ReplaceText(DeclLoc, 1, "*", 1);
3979 }
3980 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3981 // Replace the '^' with '*' for arguments.
3982 DeclLoc = ND->getLocation();
3983 startBuf = SM->getCharacterData(DeclLoc);
3984 const char *argListBegin, *argListEnd;
3985 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3986 while (argListBegin < argListEnd) {
3987 if (*argListBegin == '^') {
3988 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3989 ReplaceText(CaretLoc, 1, "*", 1);
3990 }
3991 argListBegin++;
3992 }
3993 }
3994 return;
3995}
3996
3997void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3998 // Add initializers for any closure decl refs.
3999 GetBlockDeclRefExprs(Exp->getBody());
4000 if (BlockDeclRefs.size()) {
4001 // Unique all "by copy" declarations.
4002 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4003 if (!BlockDeclRefs[i]->isByRef())
4004 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4005 // Unique all "by ref" declarations.
4006 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4007 if (BlockDeclRefs[i]->isByRef()) {
4008 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4009 }
4010 // Find any imported blocks...they will need special attention.
4011 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004012 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004013 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004014 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4015 }
4016 }
4017}
4018
Steve Narofffa15fd92008-10-28 20:29:00 +00004019FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4020 IdentifierInfo *ID = &Context->Idents.get(name);
4021 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4022 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
4023 ID, FType, FunctionDecl::Extern, false, 0);
4024}
4025
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004026Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004027 Blocks.push_back(Exp);
4028
4029 CollectBlockDeclRefInfo(Exp);
4030 std::string FuncName;
4031
4032 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004033 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004034 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004035 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004036 // Convert colons to underscores.
4037 std::string::size_type loc = 0;
4038 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4039 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004040 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004041 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004042
4043 std::string BlockNumber = utostr(Blocks.size()-1);
4044
4045 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4046 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4047
4048 // Get a pointer to the function type so we can cast appropriately.
4049 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4050
4051 FunctionDecl *FD;
4052 Expr *NewRep;
4053
4054 // Simulate a contructor call...
4055 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4056 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4057
4058 llvm::SmallVector<Expr*, 4> InitExprs;
4059
Steve Narofffdc03722008-10-29 21:23:59 +00004060 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004061 FD = SynthBlockInitFunctionDecl(Func.c_str());
4062 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4063 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004064 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004065 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004066
4067 if (ImportedBlockDecls.size()) {
4068 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004069 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4070 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4071 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004072 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004073 InitExprs.push_back(castExpr);
4074
Steve Narofffa15fd92008-10-28 20:29:00 +00004075 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004076 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4077 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4078 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004079 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004080 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004081 }
4082 // Add initializers for any closure decl refs.
4083 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004084 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004085 // Output all "by copy" declarations.
4086 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4087 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004088 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004089 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004090 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004091 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004092 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004093 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004094 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4095 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004096 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004097 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004098 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004099 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004100 }
Steve Narofffdc03722008-10-29 21:23:59 +00004101 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004102 }
4103 // Output all "by ref" declarations.
4104 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4105 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004106 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004107 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4108 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4109 Context->getPointerType(Exp->getType()),
4110 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004111 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004112 }
4113 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004114 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4115 FType, SourceLocation());
4116 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4117 Context->getPointerType(NewRep->getType()),
4118 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004119 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004120 BlockDeclRefs.clear();
4121 BlockByRefDecls.clear();
4122 BlockByCopyDecls.clear();
4123 ImportedBlockDecls.clear();
4124 return NewRep;
4125}
4126
4127//===----------------------------------------------------------------------===//
4128// Function Body / Expression rewriting
4129//===----------------------------------------------------------------------===//
4130
Steve Naroffc77a6362008-12-04 16:24:46 +00004131// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4132// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4133// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4134// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4135// Since the rewriter isn't capable of rewriting rewritten code, it's important
4136// we get this right.
4137void RewriteObjC::CollectPropertySetters(Stmt *S) {
4138 // Perform a bottom up traversal of all children.
4139 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4140 CI != E; ++CI)
4141 if (*CI)
4142 CollectPropertySetters(*CI);
4143
4144 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4145 if (BinOp->isAssignmentOp()) {
4146 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4147 PropSetters[PRE] = BinOp;
4148 }
4149 }
4150}
4151
Steve Narofffa15fd92008-10-28 20:29:00 +00004152Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4153 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4154 isa<DoStmt>(S) || isa<ForStmt>(S))
4155 Stmts.push_back(S);
4156 else if (isa<ObjCForCollectionStmt>(S)) {
4157 Stmts.push_back(S);
4158 ObjCBcLabelNo.push_back(++BcLabelCount);
4159 }
4160
4161 SourceRange OrigStmtRange = S->getSourceRange();
4162
4163 // Perform a bottom up rewrite of all children.
4164 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4165 CI != E; ++CI)
4166 if (*CI) {
4167 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4168 if (newStmt)
4169 *CI = newStmt;
4170 }
4171
4172 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4173 // Rewrite the block body in place.
4174 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4175
4176 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004177 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4178 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004179
4180 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4181 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004182 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004183 return blockTranscribed;
4184 }
4185 // Handle specific things.
4186 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4187 return RewriteAtEncode(AtEncode);
4188
4189 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4190 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4191
Steve Naroffc77a6362008-12-04 16:24:46 +00004192 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4193 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4194 if (BinOp) {
4195 // Because the rewriter doesn't allow us to rewrite rewritten code,
4196 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004197 DisableReplaceStmt = true;
4198 // Save the source range. Even if we disable the replacement, the
4199 // rewritten node will have been inserted into the tree. If the synthesized
4200 // node is at the 'end', the rewriter will fail. Consider this:
4201 // self.errorHandler = handler ? handler :
4202 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4203 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004204 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004205 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004206 //
4207 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4208 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4209 // to see the original expression). Consider this example:
4210 //
4211 // Foo *obj1, *obj2;
4212 //
4213 // obj1.i = [obj2 rrrr];
4214 //
4215 // 'BinOp' for the previous expression looks like:
4216 //
4217 // (BinaryOperator 0x231ccf0 'int' '='
4218 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4219 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4220 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4221 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4222 //
4223 // 'newStmt' represents the rewritten message expression. For example:
4224 //
4225 // (CallExpr 0x231d300 'id':'struct objc_object *'
4226 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4227 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4228 // (CStyleCastExpr 0x231d220 'void *'
4229 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4230 //
4231 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4232 // can be used as the setter argument. ReplaceStmt() will still 'see'
4233 // the original RHS (since we haven't altered BinOp).
4234 //
4235 // This implies the Rewrite* routines can no longer delete the original
4236 // node. As a result, we now leak the original AST nodes.
4237 //
Steve Naroffb619d952008-12-09 12:56:34 +00004238 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004239 } else {
4240 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004241 }
4242 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004243 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4244 return RewriteAtSelector(AtSelector);
4245
4246 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4247 return RewriteObjCStringLiteral(AtString);
4248
4249 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004250#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004251 // Before we rewrite it, put the original message expression in a comment.
4252 SourceLocation startLoc = MessExpr->getLocStart();
4253 SourceLocation endLoc = MessExpr->getLocEnd();
4254
4255 const char *startBuf = SM->getCharacterData(startLoc);
4256 const char *endBuf = SM->getCharacterData(endLoc);
4257
4258 std::string messString;
4259 messString += "// ";
4260 messString.append(startBuf, endBuf-startBuf+1);
4261 messString += "\n";
4262
4263 // FIXME: Missing definition of
4264 // InsertText(clang::SourceLocation, char const*, unsigned int).
4265 // InsertText(startLoc, messString.c_str(), messString.size());
4266 // Tried this, but it didn't work either...
4267 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004268#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004269 return RewriteMessageExpr(MessExpr);
4270 }
4271
4272 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4273 return RewriteObjCTryStmt(StmtTry);
4274
4275 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4276 return RewriteObjCSynchronizedStmt(StmtTry);
4277
4278 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4279 return RewriteObjCThrowStmt(StmtThrow);
4280
4281 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4282 return RewriteObjCProtocolExpr(ProtocolExp);
4283
4284 if (ObjCForCollectionStmt *StmtForCollection =
4285 dyn_cast<ObjCForCollectionStmt>(S))
4286 return RewriteObjCForCollectionStmt(StmtForCollection,
4287 OrigStmtRange.getEnd());
4288 if (BreakStmt *StmtBreakStmt =
4289 dyn_cast<BreakStmt>(S))
4290 return RewriteBreakStmt(StmtBreakStmt);
4291 if (ContinueStmt *StmtContinueStmt =
4292 dyn_cast<ContinueStmt>(S))
4293 return RewriteContinueStmt(StmtContinueStmt);
4294
4295 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4296 // and cast exprs.
4297 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4298 // FIXME: What we're doing here is modifying the type-specifier that
4299 // precedes the first Decl. In the future the DeclGroup should have
4300 // a separate type-specifier that we can rewrite.
4301 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4302
4303 // Blocks rewrite rules.
4304 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4305 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004306 ScopedDecl *SD = *DI;
4307 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004308 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004309 RewriteBlockPointerDecl(ND);
4310 else if (ND->getType()->isFunctionPointerType())
4311 CheckFunctionPointerDecl(ND->getType(), ND);
4312 }
4313 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004314 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004315 RewriteBlockPointerDecl(TD);
4316 else if (TD->getUnderlyingType()->isFunctionPointerType())
4317 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4318 }
4319 }
4320 }
4321
4322 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4323 RewriteObjCQualifiedInterfaceTypes(CE);
4324
4325 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4326 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4327 assert(!Stmts.empty() && "Statement stack is empty");
4328 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4329 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4330 && "Statement stack mismatch");
4331 Stmts.pop_back();
4332 }
4333 // Handle blocks rewriting.
4334 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4335 if (BDRE->isByRef())
4336 RewriteBlockDeclRefExpr(BDRE);
4337 }
4338 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004339 if (CE->getCallee()->getType()->isBlockPointerType()) {
4340 Stmt *BlockCall = SynthesizeBlockCall(CE);
4341 ReplaceStmt(S, BlockCall);
4342 return BlockCall;
4343 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004344 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004345 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004346 RewriteCastExpr(CE);
4347 }
4348#if 0
4349 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4350 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4351 // Get the new text.
4352 std::string SStr;
4353 llvm::raw_string_ostream Buf(SStr);
4354 Replacement->printPretty(Buf);
4355 const std::string &Str = Buf.str();
4356
4357 printf("CAST = %s\n", &Str[0]);
4358 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4359 delete S;
4360 return Replacement;
4361 }
4362#endif
4363 // Return this stmt unmodified.
4364 return S;
4365}
4366
4367/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4368/// main file of the input.
4369void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Steve Naroffcb735302008-12-17 00:20:22 +00004370 // Required when rewriting in objective-c++ mode...
4371 if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
4372 for (LinkageSpecDecl::decl_iterator i = LSD->decls_begin(),
4373 e = LSD->decls_end(); i != e; ++i) {
4374 HandleDeclInMainFile(*i);
4375 }
4376 return;
4377 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004379 if (FD->isOverloadedOperator())
4380 return;
4381
Steve Narofffa15fd92008-10-28 20:29:00 +00004382 // Since function prototypes don't have ParmDecl's, we check the function
4383 // prototype. This enables us to rewrite function declarations and
4384 // definitions using the same code.
4385 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4386
4387 if (Stmt *Body = FD->getBody()) {
4388 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004389 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004390 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004391 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004392 CurrentBody = 0;
4393 if (PropParentMap) {
4394 delete PropParentMap;
4395 PropParentMap = 0;
4396 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004397 // This synthesizes and inserts the block "impl" struct, invoke function,
4398 // and any copy/dispose helper functions.
4399 InsertBlockLiteralsWithinFunction(FD);
4400 CurFunctionDef = 0;
4401 }
4402 return;
4403 }
4404 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4405 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004406 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004407 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004408 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004409 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004410 CurrentBody = 0;
4411 if (PropParentMap) {
4412 delete PropParentMap;
4413 PropParentMap = 0;
4414 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004415 InsertBlockLiteralsWithinMethod(MD);
4416 CurMethodDef = 0;
4417 }
4418 }
4419 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4420 ClassImplementation.push_back(CI);
4421 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4422 CategoryImplementation.push_back(CI);
4423 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4424 RewriteForwardClassDecl(CD);
4425 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4426 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004427 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004428 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004429 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004430 CheckFunctionPointerDecl(VD->getType(), VD);
4431 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004432 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004433 RewriteCastExpr(CE);
4434 }
4435 }
4436 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004437 if (VD->getInit()) {
4438 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004439 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004440 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004441 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004442 CurrentBody = 0;
4443 if (PropParentMap) {
4444 delete PropParentMap;
4445 PropParentMap = 0;
4446 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004447 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004448 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004449 GlobalVarDecl = 0;
4450
4451 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004452 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004453 RewriteCastExpr(CE);
4454 }
4455 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004456 return;
4457 }
4458 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004459 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004460 RewriteBlockPointerDecl(TD);
4461 else if (TD->getUnderlyingType()->isFunctionPointerType())
4462 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4463 return;
4464 }
4465 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4466 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004467 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004468 e = RD->field_end(); i != e; ++i) {
4469 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004470 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004471 RewriteBlockPointerDecl(FD);
4472 }
4473 }
4474 return;
4475 }
4476 // Nothing yet.
4477}
4478
4479void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4480 // Get the top-level buffer that this corresponds to.
4481
4482 // Rewrite tabs if we care.
4483 //RewriteTabs();
4484
4485 if (Diags.hasErrorOccurred())
4486 return;
4487
4488 // Create the output file.
4489
4490 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4491 llvm::raw_ostream *OutFile;
4492 if (OutFileName == "-") {
4493 OutFile = &llvm::outs();
4494 } else if (!OutFileName.empty()) {
4495 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004496 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 OwnedStream.reset(OutFile);
4498 } else if (InFileName == "-") {
4499 OutFile = &llvm::outs();
4500 } else {
4501 llvm::sys::Path Path(InFileName);
4502 Path.eraseSuffix();
4503 Path.appendSuffix("cpp");
4504 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004505 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004506 OwnedStream.reset(OutFile);
4507 }
4508
4509 RewriteInclude();
4510
4511 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4512 Preamble.c_str(), Preamble.size(), false);
4513
Steve Naroff0aab7962008-11-14 14:10:01 +00004514 if (ClassImplementation.size() || CategoryImplementation.size())
4515 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004516
4517 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4518 // we are done.
4519 if (const RewriteBuffer *RewriteBuf =
4520 Rewrite.getRewriteBufferFor(MainFileID)) {
4521 //printf("Changed:\n");
4522 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4523 } else {
4524 fprintf(stderr, "No changes\n");
4525 }
Steve Narofface66252008-11-13 20:07:04 +00004526
Steve Naroff0aab7962008-11-14 14:10:01 +00004527 if (ClassImplementation.size() || CategoryImplementation.size()) {
4528 // Rewrite Objective-c meta data*
4529 std::string ResultStr;
4530 SynthesizeMetaDataIntoBuffer(ResultStr);
4531 // Emit metadata.
4532 *OutFile << ResultStr;
4533 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004534 OutFile->flush();
4535}
4536