blob: dd3f200635f29a822078c94bcb756212e96ff984 [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.
342 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
343
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)
376 if (isBlockPointerType(*I)) {
377 // 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";
464 Preamble += "#ifndef OBJC_SUPER\n";
465 Preamble += "struct objc_super { struct objc_object *object; ";
466 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000467 if (LangOpts.Microsoft) {
468 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
470 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000471 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "};\n";
473 Preamble += "#define OBJC_SUPER\n";
474 Preamble += "#endif\n";
475 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
476 Preamble += "typedef struct objc_object Protocol;\n";
477 Preamble += "#define _REWRITER_typedef_Protocol\n";
478 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000479 if (LangOpts.Microsoft) {
480 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
481 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
482 } else
483 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
484 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000485 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000486 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000488 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000489 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000490 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000491 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000493 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000495 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
500 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000503 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000504 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
506 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
507 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000508 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
509 Preamble += "struct __objcFastEnumerationState {\n\t";
510 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000511 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000512 Preamble += "unsigned long *mutationsPtr;\n\t";
513 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000514 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000515 Preamble += "#define __FASTENUMERATIONSTATE\n";
516 Preamble += "#endif\n";
517 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
518 Preamble += "struct __NSConstantStringImpl {\n";
519 Preamble += " int *isa;\n";
520 Preamble += " int flags;\n";
521 Preamble += " char *str;\n";
522 Preamble += " long length;\n";
523 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000524 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
525 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
526 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000528 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
530 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000531 // Blocks preamble.
532 Preamble += "#ifndef BLOCK_IMPL\n";
533 Preamble += "#define BLOCK_IMPL\n";
534 Preamble += "struct __block_impl {\n";
535 Preamble += " void *isa;\n";
536 Preamble += " int Flags;\n";
537 Preamble += " int Size;\n";
538 Preamble += " void *FuncPtr;\n";
539 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000540 Preamble += "// Runtime copy/destroy helper functions\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000541 Preamble += "__OBJC_RW_STATICIMPORT void _Block_copy_assign(void *, void *);\n";
542 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_assign_copy(void *, void *);\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void _Block_destroy(void *);\n";
544 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_release(void *);\n";
545 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock;\n";
546 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000547 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000548 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000549 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
550 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000551 Preamble += "#define __attribute__(X)\n";
552 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000553}
554
555
Chris Lattnerf04da132007-10-24 17:06:59 +0000556//===----------------------------------------------------------------------===//
557// Top Level Driver Code
558//===----------------------------------------------------------------------===//
559
Steve Naroffb29b4272008-04-14 22:03:09 +0000560void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000561 // Two cases: either the decl could be in the main file, or it could be in a
562 // #included file. If the former, rewrite it now. If the later, check to see
563 // if we rewrote the #include/#import.
564 SourceLocation Loc = D->getLocation();
565 Loc = SM->getLogicalLoc(Loc);
566
567 // If this is for a builtin, ignore it.
568 if (Loc.isInvalid()) return;
569
Steve Naroffebf2b562007-10-23 23:50:29 +0000570 // Look for built-in declarations that we need to refer during the rewrite.
571 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000572 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000573 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000574 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000575 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000576 ConstantStringClassReference = FVD;
577 return;
578 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000579 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000580 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000581 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000582 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000584 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 } else if (ObjCForwardProtocolDecl *FP =
586 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000587 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000588 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000589 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000590 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000591 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000592}
593
Chris Lattnerf04da132007-10-24 17:06:59 +0000594//===----------------------------------------------------------------------===//
595// Syntactic (non-AST) Rewriting Code
596//===----------------------------------------------------------------------===//
597
Steve Naroffb29b4272008-04-14 22:03:09 +0000598void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000599 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
600 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
601 const char *MainBufStart = MainBuf.first;
602 const char *MainBufEnd = MainBuf.second;
603 size_t ImportLen = strlen("import");
604 size_t IncludeLen = strlen("include");
605
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000606 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000607 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
608 if (*BufPtr == '#') {
609 if (++BufPtr == MainBufEnd)
610 return;
611 while (*BufPtr == ' ' || *BufPtr == '\t')
612 if (++BufPtr == MainBufEnd)
613 return;
614 if (!strncmp(BufPtr, "import", ImportLen)) {
615 // replace import with include
616 SourceLocation ImportLoc =
617 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000619 BufPtr += ImportLen;
620 }
621 }
622 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000623}
624
Steve Naroffb29b4272008-04-14 22:03:09 +0000625void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000626 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
627 const char *MainBufStart = MainBuf.first;
628 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000629
Chris Lattnerf04da132007-10-24 17:06:59 +0000630 // Loop over the whole file, looking for tabs.
631 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
632 if (*BufPtr != '\t')
633 continue;
634
635 // Okay, we found a tab. This tab will turn into at least one character,
636 // but it depends on which 'virtual column' it is in. Compute that now.
637 unsigned VCol = 0;
638 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
639 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
640 ++VCol;
641
642 // Okay, now that we know the virtual column, we know how many spaces to
643 // insert. We assume 8-character tab-stops.
644 unsigned Spaces = 8-(VCol & 7);
645
646 // Get the location of the tab.
647 SourceLocation TabLoc =
648 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
649
650 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000652 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000653}
654
Steve Naroffeb0646c2008-12-02 15:48:25 +0000655static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
656 ObjCIvarDecl *OID) {
657 std::string S;
658 S = "((struct ";
659 S += ClassDecl->getIdentifier()->getName();
660 S += "_IMPL *)self)->";
661 S += OID->getNameAsCString();
662 return S;
663}
664
Steve Naroffa0876e82008-12-02 17:36:43 +0000665void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
666 ObjCImplementationDecl *IMD,
667 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000668 SourceLocation startLoc = PID->getLocStart();
669 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000670 const char *startBuf = SM->getCharacterData(startLoc);
671 assert((*startBuf == '@') && "bogus @synthesize location");
672 const char *semiBuf = strchr(startBuf, ';');
673 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
674 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
675
676 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
677 return; // FIXME: is this correct?
678
679 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000680 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000681 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000683
684 if (!OID)
685 return;
686
687 std::string Getr;
688 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
689 Getr += "{ ";
690 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000691 // FIXME: deal with code generation implications for various property
692 // attributes (copy, retain, nonatomic).
693 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000694 Getr += "return " + getIvarAccessString(ClassDecl, OID);
695 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000696 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000697
698 // Add the rewritten getter to trigger meta data generation. An alternate, and
699 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
700 // with properties explicitly. The following addInstanceMethod() required far
701 // less code change (and actually models what the rewriter is doing).
702 if (IMD)
703 IMD->addInstanceMethod(PD->getGetterMethodDecl());
704 else
705 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000706
707 if (PD->isReadOnly())
708 return;
709
710 // Generate the 'setter' function.
711 std::string Setr;
712 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000713 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000714 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000715 // FIXME: deal with code generation implications for various property
716 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000717 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000718 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000719 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000720 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000721 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000722
723 // Add the rewritten setter to trigger meta data generation.
724 if (IMD)
725 IMD->addInstanceMethod(PD->getSetterMethodDecl());
726 else
727 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000728}
Chris Lattner8a12c272007-10-11 18:38:32 +0000729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000733
734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
746 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000749 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000752 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000753 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000755 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000757 }
758
759 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
761 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000767
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000768 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Chris Lattner55d13b42008-03-16 21:23:50 +0000778 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000780 SourceLocation Loc = Property->getLocation();
781
Chris Lattneraadaf782008-01-31 19:51:04 +0000782 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783
784 // FIXME: handle properties that are declared across multiple lines.
785 }
786}
787
Steve Naroffb29b4272008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000793
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000795 E = CatDecl->instmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->classmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
800
Steve Naroff423cb562007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000803}
804
Steve Naroffb29b4272008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807
Steve Naroff752d6ef2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000814 E = PDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Naroff752d6ef2007-10-30 16:42:30 +0000820 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000821 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000822 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000823
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 // Must comment out @optional/@required
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
827 for (const char *p = startBuf; p < endBuf; p++) {
828 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
829 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@optional"),
832 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000833
834 }
835 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
836 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@required"),
839 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000840
841 }
842 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000843}
844
Steve Naroffb29b4272008-04-14 22:03:09 +0000845void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000846 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000847 if (LocStart.isInvalid())
848 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851}
852
Steve Naroffb29b4272008-04-14 22:03:09 +0000853void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000855 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000856 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000857 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000858 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000859 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000860 else if (OMD->getResultType()->isFunctionPointerType() ||
861 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000862 // needs special handling, since pointer-to-functions have special
863 // syntax (where a decaration models use).
864 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000865 QualType PointeeTy;
866 if (const PointerType* PT = retType->getAsPointerType())
867 PointeeTy = PT->getPointeeType();
868 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
869 PointeeTy = BPT->getPointeeType();
870 if ((FPRetType = PointeeTy->getAsFunctionType())) {
871 ResultStr += FPRetType->getResultType().getAsString();
872 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000873 }
874 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000875 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000876 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000877
878 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000879 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000881 if (OMD->isInstance())
882 NameStr += "_I_";
883 else
884 NameStr += "_C_";
885
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000886 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000887 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888
889 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000890 if (ObjCCategoryImplDecl *CID =
891 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 }
Steve Naroff563b8282008-04-04 22:23:44 +0000895 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000896 {
897 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 int len = selString.size();
899 for (int i = 0; i < len; i++)
900 if (selString[i] == ':')
901 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 // Remember this name for metadata emission
905 MethodInternalNames[OMD] = NameStr;
906 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907
908 // Rewrite arguments
909 ResultStr += "(";
910
911 // invisible arguments
912 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000913 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000915 if (!LangOpts.Microsoft) {
916 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
917 ResultStr += "struct ";
918 }
919 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000921 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922 }
923 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000925
926 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000927 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928 ResultStr += " _cmd";
929
930 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000931 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932 ParmVarDecl *PDecl = OMD->getParamDecl(i);
933 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000934 if (PDecl->getType()->isObjCQualifiedIdType()) {
935 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000936 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000937 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000938 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000939 if (isBlockPointerType(PDecl->getType())) {
940 // Make sure we convert "t (^)(...)" to "t (*)(...)".
941 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
942 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
943 } else
944 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000945 ResultStr += Name;
946 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000947 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000948 if (OMD->isVariadic())
949 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000950 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951
Steve Naroff76e429d2008-07-16 14:40:40 +0000952 if (FPRetType) {
953 ResultStr += ")"; // close the precedence "scope" for "*".
954
955 // Now, emit the argument types (if any).
956 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
957 ResultStr += "(";
958 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
959 if (i) ResultStr += ", ";
960 std::string ParamStr = FT->getArgType(i).getAsString();
961 ResultStr += ParamStr;
962 }
963 if (FT->isVariadic()) {
964 if (FT->getNumArgs()) ResultStr += ", ";
965 ResultStr += "...";
966 }
967 ResultStr += ")";
968 } else {
969 ResultStr += "()";
970 }
971 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000972}
Steve Naroffb29b4272008-04-14 22:03:09 +0000973void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000974 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
975 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000977 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000978 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000979 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000980 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000981
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000982 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000983 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
984 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000986 ObjCMethodDecl *OMD = *I;
987 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 SourceLocation LocStart = OMD->getLocStart();
989 SourceLocation LocEnd = OMD->getBody()->getLocStart();
990
991 const char *startBuf = SM->getCharacterData(LocStart);
992 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000993 ReplaceText(LocStart, endBuf-startBuf,
994 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000995 }
996
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000997 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000998 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
999 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001000 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001001 ObjCMethodDecl *OMD = *I;
1002 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 SourceLocation LocStart = OMD->getLocStart();
1004 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1005
1006 const char *startBuf = SM->getCharacterData(LocStart);
1007 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001008 ReplaceText(LocStart, endBuf-startBuf,
1009 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001010 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001011 for (ObjCCategoryImplDecl::propimpl_iterator
1012 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1013 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001014 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001015 }
1016
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001017 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001018 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001019 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001020 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001021}
1022
Steve Naroffb29b4272008-04-14 22:03:09 +00001023void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001024 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001025 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001026 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001027 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001028 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001029 ResultStr += "\n";
1030 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001031 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001032 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001033 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001034 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001035 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001036 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001037 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001038 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001039 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001040
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001041 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1042 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001044 E = ClassDecl->instmeth_end(); I != E; ++I)
1045 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001046 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001047 E = ClassDecl->classmeth_end(); I != E; ++I)
1048 RewriteMethodDeclaration(*I);
1049
Steve Naroff2feac5e2007-10-30 03:43:13 +00001050 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001051 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001052}
1053
Steve Naroffb619d952008-12-09 12:56:34 +00001054Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1055 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001056 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1057 // This allows us to reuse all the fun and games in SynthMessageExpr().
1058 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1059 ObjCMessageExpr *MsgExpr;
1060 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1061 llvm::SmallVector<Expr *, 1> ExprVec;
1062 ExprVec.push_back(newStmt);
1063
Steve Naroff8599e7a2008-12-08 16:43:47 +00001064 Stmt *Receiver = PropRefExpr->getBase();
1065 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1066 if (PRE && PropGetters[PRE]) {
1067 // This allows us to handle chain/nested property getters.
1068 Receiver = PropGetters[PRE];
1069 }
1070 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001071 PDecl->getSetterName(), PDecl->getType(),
1072 PDecl->getSetterMethodDecl(),
1073 SourceLocation(), SourceLocation(),
1074 &ExprVec[0], 1);
1075 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1076
1077 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001078 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001079 //delete BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00001080 delete MsgExpr;
1081 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001082}
1083
Steve Naroffc77a6362008-12-04 16:24:46 +00001084Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001085 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1086 // This allows us to reuse all the fun and games in SynthMessageExpr().
1087 ObjCMessageExpr *MsgExpr;
1088 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1089
Steve Naroff8599e7a2008-12-08 16:43:47 +00001090 Stmt *Receiver = PropRefExpr->getBase();
1091
1092 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1093 if (PRE && PropGetters[PRE]) {
1094 // This allows us to handle chain/nested property getters.
1095 Receiver = PropGetters[PRE];
1096 }
1097 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001098 PDecl->getGetterName(), PDecl->getType(),
1099 PDecl->getGetterMethodDecl(),
1100 SourceLocation(), SourceLocation(),
1101 0, 0);
1102
Steve Naroff4c3580e2008-12-04 23:50:32 +00001103 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001104
1105 if (!PropParentMap)
1106 PropParentMap = new ParentMap(CurrentBody);
1107
1108 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1109 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1110 // We stash away the ReplacingStmt since actually doing the
1111 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1112 PropGetters[PropRefExpr] = ReplacingStmt;
1113 delete MsgExpr;
1114 return PropRefExpr; // return the original...
1115 } else {
1116 ReplaceStmt(PropRefExpr, ReplacingStmt);
1117 // delete PropRefExpr; elsewhere...
1118 delete MsgExpr;
1119 return ReplacingStmt;
1120 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001121}
1122
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001123Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1124 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001125 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001126 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001127 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001128 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1129 // lookup which class implements the instance variable.
1130 ObjCInterfaceDecl *clsDeclared = 0;
1131 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1132 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1133
1134 // Synthesize an explicit cast to gain access to the ivar.
1135 std::string RecName = clsDeclared->getIdentifier()->getName();
1136 RecName += "_IMPL";
1137 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001138 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001139 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001140 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1141 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001142 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001143 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001144 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001145 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1146 IV->getBase()->getLocEnd(),
1147 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001148 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001149 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001150 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1151 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001152 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001153 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001154 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001155 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001156
1157 ReplaceStmt(IV->getBase(), PE);
1158 // Cannot delete IV->getBase(), since PE points to it.
1159 // Replace the old base with the cast. This is important when doing
1160 // embedded rewrites. For example, [newInv->_container addObject:0].
1161 IV->setBase(PE);
1162 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001163 }
Steve Naroff84472a82008-04-18 21:55:08 +00001164 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001165 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1166
1167 // Explicit ivar refs need to have a cast inserted.
1168 // FIXME: consider sharing some of this code with the code above.
1169 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001170 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001171 // lookup which class implements the instance variable.
1172 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001173 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001174 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1175
1176 // Synthesize an explicit cast to gain access to the ivar.
1177 std::string RecName = clsDeclared->getIdentifier()->getName();
1178 RecName += "_IMPL";
1179 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001180 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001181 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001182 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1183 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001184 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001185 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001186 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001187 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1188 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001189 ReplaceStmt(IV->getBase(), PE);
1190 // Cannot delete IV->getBase(), since PE points to it.
1191 // Replace the old base with the cast. This is important when doing
1192 // embedded rewrites. For example, [newInv->_container addObject:0].
1193 IV->setBase(PE);
1194 return IV;
1195 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001196 }
Steve Naroff84472a82008-04-18 21:55:08 +00001197 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001198}
1199
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001200/// SynthCountByEnumWithState - To print:
1201/// ((unsigned int (*)
1202/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1203/// (void *)objc_msgSend)((id)l_collection,
1204/// sel_registerName(
1205/// "countByEnumeratingWithState:objects:count:"),
1206/// &enumState,
1207/// (id *)items, (unsigned int)16)
1208///
Steve Naroffb29b4272008-04-14 22:03:09 +00001209void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001210 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1211 "id *, unsigned int))(void *)objc_msgSend)";
1212 buf += "\n\t\t";
1213 buf += "((id)l_collection,\n\t\t";
1214 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1215 buf += "\n\t\t";
1216 buf += "&enumState, "
1217 "(id *)items, (unsigned int)16)";
1218}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001219
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001220/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1221/// statement to exit to its outer synthesized loop.
1222///
Steve Naroffb29b4272008-04-14 22:03:09 +00001223Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001224 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1225 return S;
1226 // replace break with goto __break_label
1227 std::string buf;
1228
1229 SourceLocation startLoc = S->getLocStart();
1230 buf = "goto __break_label_";
1231 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001232 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001233
1234 return 0;
1235}
1236
1237/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1238/// statement to continue with its inner synthesized loop.
1239///
Steve Naroffb29b4272008-04-14 22:03:09 +00001240Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001241 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1242 return S;
1243 // replace continue with goto __continue_label
1244 std::string buf;
1245
1246 SourceLocation startLoc = S->getLocStart();
1247 buf = "goto __continue_label_";
1248 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001249 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001250
1251 return 0;
1252}
1253
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001254/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001255/// It rewrites:
1256/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001257
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001258/// Into:
1259/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001260/// type elem;
1261/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001262/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001263/// id l_collection = (id)collection;
1264/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1265/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001266/// if (limit) {
1267/// unsigned long startMutations = *enumState.mutationsPtr;
1268/// do {
1269/// unsigned long counter = 0;
1270/// do {
1271/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001272/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001273/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001274/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001275/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001276/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001277/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1278/// objects:items count:16]);
1279/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001280/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001281/// }
1282/// else
1283/// elem = nil;
1284/// }
1285///
Steve Naroffb29b4272008-04-14 22:03:09 +00001286Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001287 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001288 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1289 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1290 "ObjCForCollectionStmt Statement stack mismatch");
1291 assert(!ObjCBcLabelNo.empty() &&
1292 "ObjCForCollectionStmt - Label No stack empty");
1293
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001295 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001296 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001297 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001298 std::string buf;
1299 buf = "\n{\n\t";
1300 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1301 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001302 ScopedDecl* D = DS->getSolitaryDecl();
1303 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001304 elementTypeAsString = ElementType.getAsString();
1305 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001306 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001307 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001308 buf += elementName;
1309 buf += ";\n\t";
1310 }
Chris Lattner06767512008-04-08 05:52:18 +00001311 else {
1312 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001313 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001314 elementTypeAsString
1315 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001316 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001317
1318 // struct __objcFastEnumerationState enumState = { 0 };
1319 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1320 // id items[16];
1321 buf += "id items[16];\n\t";
1322 // id l_collection = (id)
1323 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001324 // Find start location of 'collection' the hard way!
1325 const char *startCollectionBuf = startBuf;
1326 startCollectionBuf += 3; // skip 'for'
1327 startCollectionBuf = strchr(startCollectionBuf, '(');
1328 startCollectionBuf++; // skip '('
1329 // find 'in' and skip it.
1330 while (*startCollectionBuf != ' ' ||
1331 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1332 (*(startCollectionBuf+3) != ' ' &&
1333 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1334 startCollectionBuf++;
1335 startCollectionBuf += 3;
1336
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001337 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001338 ReplaceText(startLoc, startCollectionBuf - startBuf,
1339 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001340 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001341 SourceLocation rightParenLoc = S->getRParenLoc();
1342 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1343 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344 buf = ";\n\t";
1345
1346 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1347 // objects:items count:16];
1348 // which is synthesized into:
1349 // unsigned int limit =
1350 // ((unsigned int (*)
1351 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1352 // (void *)objc_msgSend)((id)l_collection,
1353 // sel_registerName(
1354 // "countByEnumeratingWithState:objects:count:"),
1355 // (struct __objcFastEnumerationState *)&state,
1356 // (id *)items, (unsigned int)16);
1357 buf += "unsigned long limit =\n\t\t";
1358 SynthCountByEnumWithState(buf);
1359 buf += ";\n\t";
1360 /// if (limit) {
1361 /// unsigned long startMutations = *enumState.mutationsPtr;
1362 /// do {
1363 /// unsigned long counter = 0;
1364 /// do {
1365 /// if (startMutations != *enumState.mutationsPtr)
1366 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001367 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368 buf += "if (limit) {\n\t";
1369 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1370 buf += "do {\n\t\t";
1371 buf += "unsigned long counter = 0;\n\t\t";
1372 buf += "do {\n\t\t\t";
1373 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1374 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1375 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001376 buf += " = (";
1377 buf += elementTypeAsString;
1378 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001380 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001382 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001383 /// } while (counter < limit);
1384 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1385 /// objects:items count:16]);
1386 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001387 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001388 /// }
1389 /// else
1390 /// elem = nil;
1391 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001392 ///
1393 buf = ";\n\t";
1394 buf += "__continue_label_";
1395 buf += utostr(ObjCBcLabelNo.back());
1396 buf += ": ;";
1397 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001398 buf += "} while (counter < limit);\n\t";
1399 buf += "} while (limit = ";
1400 SynthCountByEnumWithState(buf);
1401 buf += ");\n\t";
1402 buf += elementName;
1403 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001404 buf += "__break_label_";
1405 buf += utostr(ObjCBcLabelNo.back());
1406 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407 buf += "}\n\t";
1408 buf += "else\n\t\t";
1409 buf += elementName;
1410 buf += " = nil;\n";
1411 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001412
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001414 if (isa<CompoundStmt>(S->getBody())) {
1415 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1416 InsertText(endBodyLoc, buf.c_str(), buf.size());
1417 } else {
1418 /* Need to treat single statements specially. For example:
1419 *
1420 * for (A *a in b) if (stuff()) break;
1421 * for (A *a in b) xxxyy;
1422 *
1423 * The following code simply scans ahead to the semi to find the actual end.
1424 */
1425 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1426 const char *semiBuf = strchr(stmtBuf, ';');
1427 assert(semiBuf && "Can't find ';'");
1428 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1429 InsertText(endBodyLoc, buf.c_str(), buf.size());
1430 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001431 Stmts.pop_back();
1432 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001433 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001434}
1435
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001436/// RewriteObjCSynchronizedStmt -
1437/// This routine rewrites @synchronized(expr) stmt;
1438/// into:
1439/// objc_sync_enter(expr);
1440/// @try stmt @finally { objc_sync_exit(expr); }
1441///
Steve Naroffb29b4272008-04-14 22:03:09 +00001442Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001443 // Get the start location and compute the semi location.
1444 SourceLocation startLoc = S->getLocStart();
1445 const char *startBuf = SM->getCharacterData(startLoc);
1446
1447 assert((*startBuf == '@') && "bogus @synchronized location");
1448
1449 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001450 buf = "objc_sync_enter((id)";
1451 const char *lparenBuf = startBuf;
1452 while (*lparenBuf != '(') lparenBuf++;
1453 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001454 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1455 // the sync expression is typically a message expression that's already
1456 // been rewritten! (which implies the SourceLocation's are invalid).
1457 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001458 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001459 while (*endBuf != ')') endBuf--;
1460 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001461 buf = ");\n";
1462 // declare a new scope with two variables, _stack and _rethrow.
1463 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1464 buf += "int buf[18/*32-bit i386*/];\n";
1465 buf += "char *pointers[4];} _stack;\n";
1466 buf += "id volatile _rethrow = 0;\n";
1467 buf += "objc_exception_try_enter(&_stack);\n";
1468 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001469 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001470 startLoc = S->getSynchBody()->getLocEnd();
1471 startBuf = SM->getCharacterData(startLoc);
1472
Steve Naroffc7089f12008-08-19 13:04:19 +00001473 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001474 SourceLocation lastCurlyLoc = startLoc;
1475 buf = "}\nelse {\n";
1476 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1477 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001478 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001479 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001480 S->getSynchExpr(),
1481 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001482 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001483 std::string syncExprBufS;
1484 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001485 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001486 buf += syncExprBuf.str();
1487 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001488 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1489 buf += "}\n";
1490 buf += "}";
1491
Chris Lattneraadaf782008-01-31 19:51:04 +00001492 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001493 return 0;
1494}
1495
Steve Naroff8c565152008-12-05 17:03:39 +00001496void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1497 // Perform a bottom up traversal of all children.
1498 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1499 CI != E; ++CI)
1500 if (*CI)
1501 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1502
1503 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1504 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1505 Diags.Report(Context->getFullLoc(S->getLocStart()),
1506 TryFinallyContainsReturnDiag);
1507 }
1508 return;
1509}
1510
Steve Naroffb29b4272008-04-14 22:03:09 +00001511Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001512 // Get the start location and compute the semi location.
1513 SourceLocation startLoc = S->getLocStart();
1514 const char *startBuf = SM->getCharacterData(startLoc);
1515
1516 assert((*startBuf == '@') && "bogus @try location");
1517
1518 std::string buf;
1519 // declare a new scope with two variables, _stack and _rethrow.
1520 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1521 buf += "int buf[18/*32-bit i386*/];\n";
1522 buf += "char *pointers[4];} _stack;\n";
1523 buf += "id volatile _rethrow = 0;\n";
1524 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001525 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001526
Chris Lattneraadaf782008-01-31 19:51:04 +00001527 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001528
1529 startLoc = S->getTryBody()->getLocEnd();
1530 startBuf = SM->getCharacterData(startLoc);
1531
1532 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001533
Steve Naroff75730982007-11-07 04:08:17 +00001534 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001535 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1536 if (catchList) {
1537 startLoc = startLoc.getFileLocWithOffset(1);
1538 buf = " /* @catch begin */ else {\n";
1539 buf += " id _caught = objc_exception_extract(&_stack);\n";
1540 buf += " objc_exception_try_enter (&_stack);\n";
1541 buf += " if (_setjmp(_stack.buf))\n";
1542 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1543 buf += " else { /* @catch continue */";
1544
1545 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001546 } else { /* no catch list */
1547 buf = "}\nelse {\n";
1548 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1549 buf += "}";
1550 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001551 }
Steve Naroff75730982007-11-07 04:08:17 +00001552 bool sawIdTypedCatch = false;
1553 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001554 while (catchList) {
1555 Stmt *catchStmt = catchList->getCatchParamStmt();
1556
1557 if (catchList == S->getCatchStmts())
1558 buf = "if ("; // we are generating code for the first catch clause
1559 else
1560 buf = "else if (";
1561 startLoc = catchList->getLocStart();
1562 startBuf = SM->getCharacterData(startLoc);
1563
1564 assert((*startBuf == '@') && "bogus @catch location");
1565
1566 const char *lParenLoc = strchr(startBuf, '(');
1567
Steve Naroffbe4b3332008-02-01 22:08:12 +00001568 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001569 // Now rewrite the body...
1570 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001571 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1572 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001573 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1574 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001575 assert((*bodyBuf == '{') && "bogus @catch body location");
1576
1577 buf += "1) { id _tmp = _caught;";
1578 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1579 buf.c_str(), buf.size());
1580 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001581 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001582 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001583 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001584 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001585 sawIdTypedCatch = true;
1586 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001587 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001588
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001589 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001590 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001591 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001592 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001593 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001594 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001595 }
1596 }
1597 // Now rewrite the body...
1598 lastCatchBody = catchList->getCatchBody();
1599 SourceLocation rParenLoc = catchList->getRParenLoc();
1600 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1601 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1602 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1603 assert((*rParenBuf == ')') && "bogus @catch paren location");
1604 assert((*bodyBuf == '{') && "bogus @catch body location");
1605
1606 buf = " = _caught;";
1607 // Here we replace ") {" with "= _caught;" (which initializes and
1608 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001609 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001610 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001611 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001612 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001613 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001614 catchList = catchList->getNextCatchStmt();
1615 }
1616 // Complete the catch list...
1617 if (lastCatchBody) {
1618 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001619 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1620 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001621
Steve Naroff378f47a2008-09-11 15:29:03 +00001622 // Insert the last (implicit) else clause *before* the right curly brace.
1623 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1624 buf = "} /* last catch end */\n";
1625 buf += "else {\n";
1626 buf += " _rethrow = _caught;\n";
1627 buf += " objc_exception_try_exit(&_stack);\n";
1628 buf += "} } /* @catch end */\n";
1629 if (!S->getFinallyStmt())
1630 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001631 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001632
1633 // Set lastCurlyLoc
1634 lastCurlyLoc = lastCatchBody->getLocEnd();
1635 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001636 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001637 startLoc = finalStmt->getLocStart();
1638 startBuf = SM->getCharacterData(startLoc);
1639 assert((*startBuf == '@') && "bogus @finally start");
1640
1641 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001642 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001643
1644 Stmt *body = finalStmt->getFinallyBody();
1645 SourceLocation startLoc = body->getLocStart();
1646 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001647 assert(*SM->getCharacterData(startLoc) == '{' &&
1648 "bogus @finally body location");
1649 assert(*SM->getCharacterData(endLoc) == '}' &&
1650 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001651
1652 startLoc = startLoc.getFileLocWithOffset(1);
1653 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001654 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001655 endLoc = endLoc.getFileLocWithOffset(-1);
1656 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001657 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001658
1659 // Set lastCurlyLoc
1660 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001661
1662 // Now check for any return/continue/go statements within the @try.
1663 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001664 } else { /* no finally clause - make sure we synthesize an implicit one */
1665 buf = "{ /* implicit finally clause */\n";
1666 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1667 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1668 buf += "}";
1669 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001670 }
1671 // Now emit the final closing curly brace...
1672 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1673 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001674 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001675 return 0;
1676}
1677
Steve Naroffb29b4272008-04-14 22:03:09 +00001678Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001679 return 0;
1680}
1681
Steve Naroffb29b4272008-04-14 22:03:09 +00001682Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001683 return 0;
1684}
1685
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001686// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001687// the throw expression is typically a message expression that's already
1688// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001689Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001690 // Get the start location and compute the semi location.
1691 SourceLocation startLoc = S->getLocStart();
1692 const char *startBuf = SM->getCharacterData(startLoc);
1693
1694 assert((*startBuf == '@') && "bogus @throw location");
1695
1696 std::string buf;
1697 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001698 if (S->getThrowExpr())
1699 buf = "objc_exception_throw(";
1700 else // add an implicit argument
1701 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001702
1703 // handle "@ throw" correctly.
1704 const char *wBuf = strchr(startBuf, 'w');
1705 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1706 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1707
Steve Naroff2bd03922007-11-07 15:32:26 +00001708 const char *semiBuf = strchr(startBuf, ';');
1709 assert((*semiBuf == ';') && "@throw: can't find ';'");
1710 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1711 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001712 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001713 return 0;
1714}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001715
Steve Naroffb29b4272008-04-14 22:03:09 +00001716Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001717 // Create a new string expression.
1718 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001719 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001720 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001721 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1722 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001723 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001724 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001725
Chris Lattner07506182007-11-30 22:53:43 +00001726 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001727 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001728 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001729}
1730
Steve Naroffb29b4272008-04-14 22:03:09 +00001731Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001732 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1733 // Create a call to sel_registerName("selName").
1734 llvm::SmallVector<Expr*, 8> SelExprs;
1735 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001736 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1737 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001738 false, argType, SourceLocation(),
1739 SourceLocation()));
1740 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1741 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001742 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001744 return SelExp;
1745}
1746
Steve Naroffb29b4272008-04-14 22:03:09 +00001747CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001748 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001749 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001750 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001751
1752 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001753 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001754
1755 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001756 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001757 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1758 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001759
1760 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001761
Steve Naroff934f2762007-10-24 22:48:43 +00001762 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1763}
1764
Steve Naroffd5255f52007-11-01 13:24:47 +00001765static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1766 const char *&startRef, const char *&endRef) {
1767 while (startBuf < endBuf) {
1768 if (*startBuf == '<')
1769 startRef = startBuf; // mark the start.
1770 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001771 if (startRef && *startRef == '<') {
1772 endRef = startBuf; // mark the end.
1773 return true;
1774 }
1775 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001776 }
1777 startBuf++;
1778 }
1779 return false;
1780}
1781
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001782static void scanToNextArgument(const char *&argRef) {
1783 int angle = 0;
1784 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1785 if (*argRef == '<')
1786 angle++;
1787 else if (*argRef == '>')
1788 angle--;
1789 argRef++;
1790 }
1791 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1792}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001793
Steve Naroffb29b4272008-04-14 22:03:09 +00001794bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001795
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001796 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001797 return true;
1798
Steve Naroffd5255f52007-11-01 13:24:47 +00001799 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001800 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001802 return true; // we have "Class <Protocol> *".
1803 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001804 return false;
1805}
1806
Steve Naroff4f95b752008-07-29 18:15:38 +00001807void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1808 QualType Type = E->getType();
1809 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001810 SourceLocation Loc, EndLoc;
1811
1812 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1813 Loc = ECE->getLParenLoc();
1814 EndLoc = ECE->getRParenLoc();
1815 } else {
1816 Loc = E->getLocStart();
1817 EndLoc = E->getLocEnd();
1818 }
1819 // This will defend against trying to rewrite synthesized expressions.
1820 if (Loc.isInvalid() || EndLoc.isInvalid())
1821 return;
1822
Steve Naroff4f95b752008-07-29 18:15:38 +00001823 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001824 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001825 const char *startRef = 0, *endRef = 0;
1826 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1827 // Get the locations of the startRef, endRef.
1828 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1829 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1830 // Comment out the protocol references.
1831 InsertText(LessLoc, "/*", 2);
1832 InsertText(GreaterLoc, "*/", 2);
1833 }
1834 }
1835}
1836
Steve Naroffb29b4272008-04-14 22:03:09 +00001837void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001838 SourceLocation Loc;
1839 QualType Type;
1840 const FunctionTypeProto *proto = 0;
1841 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1842 Loc = VD->getLocation();
1843 Type = VD->getType();
1844 }
1845 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1846 Loc = FD->getLocation();
1847 // Check for ObjC 'id' and class types that have been adorned with protocol
1848 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1849 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1850 assert(funcType && "missing function type");
1851 proto = dyn_cast<FunctionTypeProto>(funcType);
1852 if (!proto)
1853 return;
1854 Type = proto->getResultType();
1855 }
1856 else
1857 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001858
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001859 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001860 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001861
1862 const char *endBuf = SM->getCharacterData(Loc);
1863 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001864 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001865 startBuf--; // scan backward (from the decl location) for return type.
1866 const char *startRef = 0, *endRef = 0;
1867 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1868 // Get the locations of the startRef, endRef.
1869 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1870 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1871 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001872 InsertText(LessLoc, "/*", 2);
1873 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001874 }
1875 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001876 if (!proto)
1877 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001878 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001879 const char *startBuf = SM->getCharacterData(Loc);
1880 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001881 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1882 if (needToScanForQualifiers(proto->getArgType(i))) {
1883 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001884
Steve Naroffd5255f52007-11-01 13:24:47 +00001885 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001886 // scan forward (from the decl location) for argument types.
1887 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001888 const char *startRef = 0, *endRef = 0;
1889 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1890 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001891 SourceLocation LessLoc =
1892 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1893 SourceLocation GreaterLoc =
1894 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001895 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001896 InsertText(LessLoc, "/*", 2);
1897 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001898 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001899 startBuf = ++endBuf;
1900 }
1901 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001902 // If the function name is derived from a macro expansion, then the
1903 // argument buffer will not follow the name. Need to speak with Chris.
1904 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001905 startBuf++; // scan forward (from the decl location) for argument types.
1906 startBuf++;
1907 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001908 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001909}
1910
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001911// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001912void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001913 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1914 llvm::SmallVector<QualType, 16> ArgTys;
1915 ArgTys.push_back(Context->getPointerType(
1916 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001918 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001919 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001920 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001921 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001922 SelGetUidIdent, getFuncType,
1923 FunctionDecl::Extern, false, 0);
1924}
1925
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001926// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001927void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001928 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1929 llvm::SmallVector<QualType, 16> ArgTys;
1930 ArgTys.push_back(Context->getPointerType(
1931 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001933 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001934 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001935 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001936 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001937 SelGetProtoIdent, getFuncType,
1938 FunctionDecl::Extern, false, 0);
1939}
1940
Steve Naroffb29b4272008-04-14 22:03:09 +00001941void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001942 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001943 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001944 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001945 return;
1946 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001947 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001948}
1949
Steve Naroffc0a123c2008-03-11 17:37:02 +00001950// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001951void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001952 if (SuperContructorFunctionDecl)
1953 return;
1954 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1955 llvm::SmallVector<QualType, 16> ArgTys;
1956 QualType argT = Context->getObjCIdType();
1957 assert(!argT.isNull() && "Can't find 'id' type");
1958 ArgTys.push_back(argT);
1959 ArgTys.push_back(argT);
1960 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1961 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001962 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001963 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001964 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001965 msgSendIdent, msgSendType,
1966 FunctionDecl::Extern, false, 0);
1967}
1968
Steve Naroff09b266e2007-10-30 23:14:51 +00001969// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001970void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001971 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1972 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001973 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001974 assert(!argT.isNull() && "Can't find 'id' type");
1975 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001977 assert(!argT.isNull() && "Can't find 'SEL' type");
1978 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001980 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001981 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001982 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001983 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001984 msgSendIdent, msgSendType,
1985 FunctionDecl::Extern, false, 0);
1986}
1987
Steve Naroff874e2322007-11-15 10:28:18 +00001988// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001989void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001990 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1991 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001992 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001993 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001994 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001995 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1996 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1997 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001998 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001999 assert(!argT.isNull() && "Can't find 'SEL' type");
2000 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002002 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002003 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002004 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002005 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002006 msgSendIdent, msgSendType,
2007 FunctionDecl::Extern, false, 0);
2008}
2009
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002010// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002011void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002012 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2013 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002014 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002015 assert(!argT.isNull() && "Can't find 'id' type");
2016 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002017 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002018 assert(!argT.isNull() && "Can't find 'SEL' type");
2019 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002021 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002022 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002023 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002024 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002025 msgSendIdent, msgSendType,
2026 FunctionDecl::Extern, false, 0);
2027}
2028
2029// SynthMsgSendSuperStretFunctionDecl -
2030// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002031void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002032 IdentifierInfo *msgSendIdent =
2033 &Context->Idents.get("objc_msgSendSuper_stret");
2034 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002035 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002036 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002037 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002038 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2039 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2040 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002042 assert(!argT.isNull() && "Can't find 'SEL' type");
2043 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002044 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002045 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002046 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002047 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002048 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002049 msgSendIdent, msgSendType,
2050 FunctionDecl::Extern, false, 0);
2051}
2052
Steve Naroff1284db82008-05-08 22:02:18 +00002053// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002054void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002055 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2056 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002057 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002058 assert(!argT.isNull() && "Can't find 'id' type");
2059 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002061 assert(!argT.isNull() && "Can't find 'SEL' type");
2062 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002063 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002064 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002065 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002066 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002067 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002068 msgSendIdent, msgSendType,
2069 FunctionDecl::Extern, false, 0);
2070}
2071
Steve Naroff09b266e2007-10-30 23:14:51 +00002072// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002073void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002074 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2075 llvm::SmallVector<QualType, 16> ArgTys;
2076 ArgTys.push_back(Context->getPointerType(
2077 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002079 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002080 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002081 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002082 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002083 getClassIdent, getClassType,
2084 FunctionDecl::Extern, false, 0);
2085}
2086
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002087// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002088void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002089 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2090 llvm::SmallVector<QualType, 16> ArgTys;
2091 ArgTys.push_back(Context->getPointerType(
2092 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002094 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002095 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002096 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002097 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 getClassIdent, getClassType,
2099 FunctionDecl::Extern, false, 0);
2100}
2101
Steve Naroffb29b4272008-04-14 22:03:09 +00002102Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002103 QualType strType = getConstantStringStructType();
2104
2105 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002106
2107 std::string tmpName = InFileName;
2108 unsigned i;
2109 for (i=0; i < tmpName.length(); i++) {
2110 char c = tmpName.at(i);
2111 // replace any non alphanumeric characters with '_'.
2112 if (!isalpha(c) && (c < '0' || c > '9'))
2113 tmpName[i] = '_';
2114 }
2115 S += tmpName;
2116 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002117 S += utostr(NumObjCStringLiterals++);
2118
Steve Naroffba92b2e2008-03-27 22:29:16 +00002119 Preamble += "static __NSConstantStringImpl " + S;
2120 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2121 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002122 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002123 std::string prettyBufS;
2124 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002125 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002126 Preamble += prettyBuf.str();
2127 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002128 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002129 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002130
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002131 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002132 &Context->Idents.get(S.c_str()), strType,
2133 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002134 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2135 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2136 Context->getPointerType(DRE->getType()),
2137 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002138 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002139 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002140 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002141 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002142 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002143 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002144}
2145
Steve Naroffb29b4272008-04-14 22:03:09 +00002146ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002147 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002148 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002149
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002150 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2151 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002152 assert(PT);
2153 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2154 return IT->getDecl();
2155 }
2156 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002157}
2158
2159// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002160QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002161 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002162 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002163 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002164 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002165 QualType FieldTypes[2];
2166
2167 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002168 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002169 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002170 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002171
Steve Naroff874e2322007-11-15 10:28:18 +00002172 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002173 for (unsigned i = 0; i < 2; ++i) {
2174 SuperStructDecl->addDecl(*Context,
2175 FieldDecl::Create(*Context, SuperStructDecl,
2176 SourceLocation(), 0,
2177 FieldTypes[i], /*BitWidth=*/0,
2178 /*Mutable=*/false, 0),
2179 true);
2180 }
Steve Naroff874e2322007-11-15 10:28:18 +00002181
Douglas Gregor44b43212008-12-11 16:49:14 +00002182 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002183 }
2184 return Context->getTagDeclType(SuperStructDecl);
2185}
2186
Steve Naroffb29b4272008-04-14 22:03:09 +00002187QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002188 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002189 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002190 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002191 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002192 QualType FieldTypes[4];
2193
2194 // struct objc_object *receiver;
2195 FieldTypes[0] = Context->getObjCIdType();
2196 // int flags;
2197 FieldTypes[1] = Context->IntTy;
2198 // char *str;
2199 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2200 // long length;
2201 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002202
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002203 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002204 for (unsigned i = 0; i < 4; ++i) {
2205 ConstantStringDecl->addDecl(*Context,
2206 FieldDecl::Create(*Context,
2207 ConstantStringDecl,
2208 SourceLocation(), 0,
2209 FieldTypes[i],
2210 /*BitWidth=*/0,
2211 /*Mutable=*/true, 0),
2212 true);
2213 }
2214
2215 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002216 }
2217 return Context->getTagDeclType(ConstantStringDecl);
2218}
2219
Steve Naroffb29b4272008-04-14 22:03:09 +00002220Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002221 if (!SelGetUidFunctionDecl)
2222 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002223 if (!MsgSendFunctionDecl)
2224 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002225 if (!MsgSendSuperFunctionDecl)
2226 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002227 if (!MsgSendStretFunctionDecl)
2228 SynthMsgSendStretFunctionDecl();
2229 if (!MsgSendSuperStretFunctionDecl)
2230 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002231 if (!MsgSendFpretFunctionDecl)
2232 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002233 if (!GetClassFunctionDecl)
2234 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002235 if (!GetMetaClassFunctionDecl)
2236 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002237
Steve Naroff874e2322007-11-15 10:28:18 +00002238 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002239 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2240 // May need to use objc_msgSend_stret() as well.
2241 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002243 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002244 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002245 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002246 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002247 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002248 }
Steve Naroff874e2322007-11-15 10:28:18 +00002249
Steve Naroff934f2762007-10-24 22:48:43 +00002250 // Synthesize a call to objc_msgSend().
2251 llvm::SmallVector<Expr*, 8> MsgExprs;
2252 IdentifierInfo *clsName = Exp->getClassName();
2253
2254 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2255 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002256 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2257 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002258 if (!strcmp(clsName->getName(), "super")) {
2259 MsgSendFlavor = MsgSendSuperFunctionDecl;
2260 if (MsgSendStretFlavor)
2261 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2262 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2263
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002264 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002265 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002266
2267 llvm::SmallVector<Expr*, 4> InitExprs;
2268
2269 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002270 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002271 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002272 Context->getObjCIdType(),
2273 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002274 llvm::SmallVector<Expr*, 8> ClsExprs;
2275 QualType argType = Context->getPointerType(Context->CharTy);
2276 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2277 SuperDecl->getIdentifier()->getLength(),
2278 false, argType, SourceLocation(),
2279 SourceLocation()));
2280 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2281 &ClsExprs[0],
2282 ClsExprs.size());
2283 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002284 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002285 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002286 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002287 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 // struct objc_super
2289 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002290 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002291
Steve Naroff23f41272008-03-11 18:14:26 +00002292 if (LangOpts.Microsoft) {
2293 SynthSuperContructorFunctionDecl();
2294 // Simulate a contructor call...
2295 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2296 superType, SourceLocation());
2297 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2298 superType, SourceLocation());
2299 } else {
2300 // (struct objc_super) { <exprs from above> }
2301 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2302 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002303 SourceLocation(), false);
2304 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2305 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002306 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002307 // struct objc_super *
2308 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2309 Context->getPointerType(SuperRep->getType()),
2310 SourceLocation());
2311 MsgExprs.push_back(Unop);
2312 } else {
2313 llvm::SmallVector<Expr*, 8> ClsExprs;
2314 QualType argType = Context->getPointerType(Context->CharTy);
2315 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2316 clsName->getLength(),
2317 false, argType, SourceLocation(),
2318 SourceLocation()));
2319 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2320 &ClsExprs[0],
2321 ClsExprs.size());
2322 MsgExprs.push_back(Cls);
2323 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002324 } else { // instance message.
2325 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002326
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002327 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002328 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002329 if (MsgSendStretFlavor)
2330 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002331 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2332
2333 llvm::SmallVector<Expr*, 4> InitExprs;
2334
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002335 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002336 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002337 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002338 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002339 SourceLocation()),
2340 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002341 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002342
2343 llvm::SmallVector<Expr*, 8> ClsExprs;
2344 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002345 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2346 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002347 false, argType, SourceLocation(),
2348 SourceLocation()));
2349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002350 &ClsExprs[0],
2351 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002352 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002353 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002354 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002355 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002356 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002357 // struct objc_super
2358 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002359 Expr *SuperRep;
2360
2361 if (LangOpts.Microsoft) {
2362 SynthSuperContructorFunctionDecl();
2363 // Simulate a contructor call...
2364 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2365 superType, SourceLocation());
2366 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2367 superType, SourceLocation());
2368 } else {
2369 // (struct objc_super) { <exprs from above> }
2370 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2371 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002372 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002373 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2374 }
Steve Naroff874e2322007-11-15 10:28:18 +00002375 // struct objc_super *
2376 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2377 Context->getPointerType(SuperRep->getType()),
2378 SourceLocation());
2379 MsgExprs.push_back(Unop);
2380 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002381 // Remove all type-casts because it may contain objc-style types; e.g.
2382 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002383 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002384 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002385 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002386 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002387 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002388 MsgExprs.push_back(recExpr);
2389 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002390 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002391 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002392 llvm::SmallVector<Expr*, 8> SelExprs;
2393 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002394 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2395 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002396 false, argType, SourceLocation(),
2397 SourceLocation()));
2398 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2399 &SelExprs[0], SelExprs.size());
2400 MsgExprs.push_back(SelExp);
2401
2402 // Now push any user supplied arguments.
2403 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002404 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002405 // Make all implicit casts explicit...ICE comes in handy:-)
2406 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2407 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002408 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002410 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002411 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002412 }
2413 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002414 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002415 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002416 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002417 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002418 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002419 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002420 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002421 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002422 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002423 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002424 // We've transferred the ownership to MsgExprs. Null out the argument in
2425 // the original expression, since we will delete it below.
2426 Exp->setArg(i, 0);
2427 }
Steve Naroffab972d32007-11-04 22:37:50 +00002428 // Generate the funky cast.
2429 CastExpr *cast;
2430 llvm::SmallVector<QualType, 8> ArgTypes;
2431 QualType returnType;
2432
2433 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002434 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2435 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2436 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437 ArgTypes.push_back(Context->getObjCIdType());
2438 ArgTypes.push_back(Context->getObjCSelType());
2439 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002440 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002441 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002442 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2443 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002444 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002445 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2446 if (isBlockPointerType(t)) {
2447 const BlockPointerType *BPT = t->getAsBlockPointerType();
2448 t = Context->getPointerType(BPT->getPointeeType());
2449 }
Steve Naroff352336b2007-11-05 14:36:37 +00002450 ArgTypes.push_back(t);
2451 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2453 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002454 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002456 }
2457 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002458 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002459
2460 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002461 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2462 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002463
2464 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2465 // If we don't do this cast, we get the following bizarre warning/note:
2466 // xx.m:13: warning: function called through a non-compatible type
2467 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002468 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002469 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002470 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002471
Steve Naroffab972d32007-11-04 22:37:50 +00002472 // Now do the "normal" pointer to function cast.
2473 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002474 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002475 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002476 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002477 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002478 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002479
2480 // Don't forget the parens to enforce the proper binding.
2481 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2482
2483 const FunctionType *FT = msgSendType->getAsFunctionType();
2484 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2485 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002486 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002487 if (MsgSendStretFlavor) {
2488 // We have the method which returns a struct/union. Must also generate
2489 // call to objc_msgSend_stret and hang both varieties on a conditional
2490 // expression which dictate which one to envoke depending on size of
2491 // method's return type.
2492
2493 // Create a reference to the objc_msgSend_stret() declaration.
2494 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2495 SourceLocation());
2496 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002497 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002498 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002499 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002500 // Now do the "normal" pointer to function cast.
2501 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002502 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002503 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002504 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002505 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002506
2507 // Don't forget the parens to enforce the proper binding.
2508 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2509
2510 FT = msgSendType->getAsFunctionType();
2511 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2512 FT->getResultType(), SourceLocation());
2513
2514 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002515 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2516 returnType.getAsOpaquePtr(),
2517 Context->getSizeType(),
2518 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002519 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2520 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2521 // For X86 it is more complicated and some kind of target specific routine
2522 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002523 unsigned IntSize =
2524 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002525 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2526 Context->IntTy,
2527 SourceLocation());
2528 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2529 BinaryOperator::LE,
2530 Context->IntTy,
2531 SourceLocation());
2532 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2533 ConditionalOperator *CondExpr =
2534 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002535 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002537 return ReplacingStmt;
2538}
2539
Steve Naroffb29b4272008-04-14 22:03:09 +00002540Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002541 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002542
Steve Naroffc77a6362008-12-04 16:24:46 +00002543 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002544 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002545 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002546
Steve Naroff4c3580e2008-12-04 23:50:32 +00002547 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002548 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002549}
2550
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002551/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2552/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002553Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002554 if (!GetProtocolFunctionDecl)
2555 SynthGetProtocolFunctionDecl();
2556 // Create a call to objc_getProtocol("ProtocolName").
2557 llvm::SmallVector<Expr*, 8> ProtoExprs;
2558 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002559 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2560 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002561 false, argType, SourceLocation(),
2562 SourceLocation()));
2563 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2564 &ProtoExprs[0],
2565 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002566 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002567 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002568 return ProtoExp;
2569
2570}
2571
Steve Naroffbaf58c32008-05-31 14:15:04 +00002572bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2573 const char *endBuf) {
2574 while (startBuf < endBuf) {
2575 if (*startBuf == '#') {
2576 // Skip whitespace.
2577 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2578 ;
2579 if (!strncmp(startBuf, "if", strlen("if")) ||
2580 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2581 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2582 !strncmp(startBuf, "define", strlen("define")) ||
2583 !strncmp(startBuf, "undef", strlen("undef")) ||
2584 !strncmp(startBuf, "else", strlen("else")) ||
2585 !strncmp(startBuf, "elif", strlen("elif")) ||
2586 !strncmp(startBuf, "endif", strlen("endif")) ||
2587 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2588 !strncmp(startBuf, "include", strlen("include")) ||
2589 !strncmp(startBuf, "import", strlen("import")) ||
2590 !strncmp(startBuf, "include_next", strlen("include_next")))
2591 return true;
2592 }
2593 startBuf++;
2594 }
2595 return false;
2596}
2597
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002598/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002599/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002600void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002601 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002602 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002603 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002604 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002605 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002607 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002608 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002609 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002610 SourceLocation LocStart = CDecl->getLocStart();
2611 SourceLocation LocEnd = CDecl->getLocEnd();
2612
2613 const char *startBuf = SM->getCharacterData(LocStart);
2614 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002615
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002616 // If no ivars and no root or if its root, directly or indirectly,
2617 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002618 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2619 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002620 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002621 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002622 return;
2623 }
2624
2625 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002627 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002628 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002629 if (LangOpts.Microsoft)
2630 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002631
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002632 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002633 const char *cursor = strchr(startBuf, '{');
2634 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002635 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002636 // If the buffer contains preprocessor directives, we do more fine-grained
2637 // rewrites. This is intended to fix code that looks like (which occurs in
2638 // NSURL.h, for example):
2639 //
2640 // #ifdef XYZ
2641 // @interface Foo : NSObject
2642 // #else
2643 // @interface FooBar : NSObject
2644 // #endif
2645 // {
2646 // int i;
2647 // }
2648 // @end
2649 //
2650 // This clause is segregated to avoid breaking the common case.
2651 if (BufferContainsPPDirectives(startBuf, cursor)) {
2652 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2653 CDecl->getClassLoc();
2654 const char *endHeader = SM->getCharacterData(L);
2655 endHeader += Lexer::MeasureTokenLength(L, *SM);
2656
Chris Lattner3db6cae2008-07-21 18:19:38 +00002657 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002658 // advance to the end of the referenced protocols.
2659 while (endHeader < cursor && *endHeader != '>') endHeader++;
2660 endHeader++;
2661 }
2662 // rewrite the original header
2663 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2664 } else {
2665 // rewrite the original header *without* disturbing the '{'
2666 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2667 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002668 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002669 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002670 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002671 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002672 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002673 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002674
2675 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002676 SourceLocation OnePastCurly =
2677 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2678 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002679 }
2680 cursor++; // past '{'
2681
2682 // Now comment out any visibility specifiers.
2683 while (cursor < endBuf) {
2684 if (*cursor == '@') {
2685 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002686 // Skip whitespace.
2687 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2688 /*scan*/;
2689
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002690 // FIXME: presence of @public, etc. inside comment results in
2691 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002692 if (!strncmp(cursor, "public", strlen("public")) ||
2693 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002694 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002695 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002696 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002697 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002698 // FIXME: If there are cases where '<' is used in ivar declaration part
2699 // of user code, then scan the ivar list and use needToScanForQualifiers
2700 // for type checking.
2701 else if (*cursor == '<') {
2702 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002703 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002704 cursor = strchr(cursor, '>');
2705 cursor++;
2706 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002707 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002708 } else if (*cursor == '^') { // rewrite block specifier.
2709 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2710 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002711 }
Steve Narofffea763e82007-11-14 19:25:57 +00002712 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002713 }
Steve Narofffea763e82007-11-14 19:25:57 +00002714 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002715 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002716 } else { // we don't have any instance variables - insert super struct.
2717 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2718 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002719 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002720 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002721 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002722 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002723 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002724 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002725 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002726 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002727 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002728}
2729
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002731/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002732void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002733 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002734 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002735 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002736 const char *ClassName,
2737 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002738 if (MethodBegin == MethodEnd) return;
2739
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002740 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002741 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002742 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002743 SEL _cmd;
2744 char *method_types;
2745 void *_imp;
2746 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002747 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002748 Result += "\nstruct _objc_method {\n";
2749 Result += "\tSEL _cmd;\n";
2750 Result += "\tchar *method_types;\n";
2751 Result += "\tvoid *_imp;\n";
2752 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002753
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002754 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002755 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002756
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002758
2759 /* struct {
2760 struct _objc_method_list *next_method;
2761 int method_count;
2762 struct _objc_method method_list[];
2763 }
2764 */
2765 Result += "\nstatic struct {\n";
2766 Result += "\tstruct _objc_method_list *next_method;\n";
2767 Result += "\tint method_count;\n";
2768 Result += "\tstruct _objc_method method_list[";
2769 Result += utostr(MethodEnd-MethodBegin);
2770 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002771 Result += prefix;
2772 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2773 Result += "_METHODS_";
2774 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002775 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002776 Result += IsInstanceMethod ? "inst" : "cls";
2777 Result += "_meth\")))= ";
2778 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002779
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002780 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002781 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002782 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002783 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002784 Result += "\", \"";
2785 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002786 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002787 Result += MethodInternalNames[*MethodBegin];
2788 Result += "}\n";
2789 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2790 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002791 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002792 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002793 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002794 Result += "\", \"";
2795 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002796 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002797 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002798 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002799 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002800 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002801}
2802
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002803/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002804void RewriteObjC::
2805RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2806 const char *prefix,
2807 const char *ClassName,
2808 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002809 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002810 if (Protocols.empty()) return;
2811
2812 for (unsigned i = 0; i != Protocols.size(); i++) {
2813 ObjCProtocolDecl *PDecl = Protocols[i];
2814 // Output struct protocol_methods holder of method selector and type.
2815 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2816 /* struct protocol_methods {
2817 SEL _cmd;
2818 char *method_types;
2819 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002820 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002821 Result += "\nstruct protocol_methods {\n";
2822 Result += "\tSEL _cmd;\n";
2823 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002824 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002825
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002826 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002827 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002828 // Do not synthesize the protocol more than once.
2829 if (ObjCSynthesizedProtocols.count(PDecl))
2830 continue;
2831
2832 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2833 unsigned NumMethods = PDecl->getNumInstanceMethods();
2834 /* struct _objc_protocol_method_list {
2835 int protocol_method_count;
2836 struct protocol_methods protocols[];
2837 }
2838 */
2839 Result += "\nstatic struct {\n";
2840 Result += "\tint protocol_method_count;\n";
2841 Result += "\tstruct protocol_methods protocols[";
2842 Result += utostr(NumMethods);
2843 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002844 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002845 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2846 "{\n\t" + utostr(NumMethods) + "\n";
2847
2848 // Output instance methods declared in this protocol.
2849 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2850 E = PDecl->instmeth_end(); I != E; ++I) {
2851 if (I == PDecl->instmeth_begin())
2852 Result += "\t ,{{(SEL)\"";
2853 else
2854 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002855 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002856 std::string MethodTypeString;
2857 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2858 Result += "\", \"";
2859 Result += MethodTypeString;
2860 Result += "\"}\n";
2861 }
2862 Result += "\t }\n};\n";
2863 }
2864
2865 // Output class methods declared in this protocol.
2866 int NumMethods = PDecl->getNumClassMethods();
2867 if (NumMethods > 0) {
2868 /* struct _objc_protocol_method_list {
2869 int protocol_method_count;
2870 struct protocol_methods protocols[];
2871 }
2872 */
2873 Result += "\nstatic struct {\n";
2874 Result += "\tint protocol_method_count;\n";
2875 Result += "\tstruct protocol_methods protocols[";
2876 Result += utostr(NumMethods);
2877 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002878 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002879 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2880 "{\n\t";
2881 Result += utostr(NumMethods);
2882 Result += "\n";
2883
2884 // Output instance methods declared in this protocol.
2885 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2886 E = PDecl->classmeth_end(); I != E; ++I) {
2887 if (I == PDecl->classmeth_begin())
2888 Result += "\t ,{{(SEL)\"";
2889 else
2890 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002891 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002892 std::string MethodTypeString;
2893 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2894 Result += "\", \"";
2895 Result += MethodTypeString;
2896 Result += "\"}\n";
2897 }
2898 Result += "\t }\n};\n";
2899 }
2900
2901 // Output:
2902 /* struct _objc_protocol {
2903 // Objective-C 1.0 extensions
2904 struct _objc_protocol_extension *isa;
2905 char *protocol_name;
2906 struct _objc_protocol **protocol_list;
2907 struct _objc_protocol_method_list *instance_methods;
2908 struct _objc_protocol_method_list *class_methods;
2909 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002910 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002911 static bool objc_protocol = false;
2912 if (!objc_protocol) {
2913 Result += "\nstruct _objc_protocol {\n";
2914 Result += "\tstruct _objc_protocol_extension *isa;\n";
2915 Result += "\tchar *protocol_name;\n";
2916 Result += "\tstruct _objc_protocol **protocol_list;\n";
2917 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2918 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2919 Result += "};\n";
2920
2921 objc_protocol = true;
2922 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002923
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002924 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002925 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002926 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2927 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002928 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002929 Result += "\", 0, ";
2930 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2931 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002932 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002933 Result += ", ";
2934 }
2935 else
2936 Result += "0, ";
2937 if (PDecl->getNumClassMethods() > 0) {
2938 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002939 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002941 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002942 else
2943 Result += "0\n";
2944 Result += "};\n";
2945
2946 // Mark this protocol as having been generated.
2947 if (!ObjCSynthesizedProtocols.insert(PDecl))
2948 assert(false && "protocol already synthesized");
2949 }
2950 // Output the top lovel protocol meta-data for the class.
2951 /* struct _objc_protocol_list {
2952 struct _objc_protocol_list *next;
2953 int protocol_count;
2954 struct _objc_protocol *class_protocols[];
2955 }
2956 */
2957 Result += "\nstatic struct {\n";
2958 Result += "\tstruct _objc_protocol_list *next;\n";
2959 Result += "\tint protocol_count;\n";
2960 Result += "\tstruct _objc_protocol *class_protocols[";
2961 Result += utostr(Protocols.size());
2962 Result += "];\n} _OBJC_";
2963 Result += prefix;
2964 Result += "_PROTOCOLS_";
2965 Result += ClassName;
2966 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2967 "{\n\t0, ";
2968 Result += utostr(Protocols.size());
2969 Result += "\n";
2970
2971 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002972 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002973 Result += " \n";
2974
2975 for (unsigned i = 1; i != Protocols.size(); i++) {
2976 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002977 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002978 Result += "\n";
2979 }
2980 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002981}
2982
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002983/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002984/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002985void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002986 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002987 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002988 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002989 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002990 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2991 CDecl = CDecl->getNextClassCategory())
2992 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2993 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002995 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002996 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002997 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002998
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002999 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003001 true, "CATEGORY_", FullCategoryName.c_str(),
3002 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003003
3004 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003005 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003006 false, "CATEGORY_", FullCategoryName.c_str(),
3007 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003008
3009 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003010 // Null CDecl is case of a category implementation with no category interface
3011 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003012 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003013 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014
3015 /* struct _objc_category {
3016 char *category_name;
3017 char *class_name;
3018 struct _objc_method_list *instance_methods;
3019 struct _objc_method_list *class_methods;
3020 struct _objc_protocol_list *protocols;
3021 // Objective-C 1.0 extensions
3022 uint32_t size; // sizeof (struct _objc_category)
3023 struct _objc_property_list *instance_properties; // category's own
3024 // @property decl.
3025 };
3026 */
3027
3028 static bool objc_category = false;
3029 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003030 Result += "\nstruct _objc_category {\n";
3031 Result += "\tchar *category_name;\n";
3032 Result += "\tchar *class_name;\n";
3033 Result += "\tstruct _objc_method_list *instance_methods;\n";
3034 Result += "\tstruct _objc_method_list *class_methods;\n";
3035 Result += "\tstruct _objc_protocol_list *protocols;\n";
3036 Result += "\tunsigned int size;\n";
3037 Result += "\tstruct _objc_property_list *instance_properties;\n";
3038 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003039 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003040 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003041 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3042 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003043 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003044 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003045 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003046 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003047 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003048
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003049 if (IDecl->getNumInstanceMethods() > 0) {
3050 Result += "\t, (struct _objc_method_list *)"
3051 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3052 Result += FullCategoryName;
3053 Result += "\n";
3054 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003055 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003056 Result += "\t, 0\n";
3057 if (IDecl->getNumClassMethods() > 0) {
3058 Result += "\t, (struct _objc_method_list *)"
3059 "&_OBJC_CATEGORY_CLASS_METHODS_";
3060 Result += FullCategoryName;
3061 Result += "\n";
3062 }
3063 else
3064 Result += "\t, 0\n";
3065
Chris Lattner780f3292008-07-21 21:32:27 +00003066 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003067 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3068 Result += FullCategoryName;
3069 Result += "\n";
3070 }
3071 else
3072 Result += "\t, 0\n";
3073 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003074}
3075
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003076/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3077/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003078void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003079 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003080 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003081 if (ivar->isBitField()) {
3082 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3083 // place all bitfields at offset 0.
3084 Result += "0";
3085 } else {
3086 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003087 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003088 if (LangOpts.Microsoft)
3089 Result += "_IMPL";
3090 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003091 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003092 Result += ")";
3093 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003094}
3095
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003096//===----------------------------------------------------------------------===//
3097// Meta Data Emission
3098//===----------------------------------------------------------------------===//
3099
Steve Naroffb29b4272008-04-14 22:03:09 +00003100void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003101 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003102 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003103
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003104 // Explictly declared @interface's are already synthesized.
3105 if (CDecl->ImplicitInterfaceDecl()) {
3106 // FIXME: Implementation of a class with no @interface (legacy) doese not
3107 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003108 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003109 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003110
Chris Lattnerbe6df082007-12-12 07:56:42 +00003111 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003112 unsigned NumIvars = !IDecl->ivar_empty()
3113 ? IDecl->ivar_size()
3114 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003115 if (NumIvars > 0) {
3116 static bool objc_ivar = false;
3117 if (!objc_ivar) {
3118 /* struct _objc_ivar {
3119 char *ivar_name;
3120 char *ivar_type;
3121 int ivar_offset;
3122 };
3123 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003124 Result += "\nstruct _objc_ivar {\n";
3125 Result += "\tchar *ivar_name;\n";
3126 Result += "\tchar *ivar_type;\n";
3127 Result += "\tint ivar_offset;\n";
3128 Result += "};\n";
3129
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003130 objc_ivar = true;
3131 }
3132
Steve Naroff946a6932008-03-11 00:12:29 +00003133 /* struct {
3134 int ivar_count;
3135 struct _objc_ivar ivar_list[nIvars];
3136 };
3137 */
3138 Result += "\nstatic struct {\n";
3139 Result += "\tint ivar_count;\n";
3140 Result += "\tstruct _objc_ivar ivar_list[";
3141 Result += utostr(NumIvars);
3142 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003143 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003144 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003145 "{\n\t";
3146 Result += utostr(NumIvars);
3147 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003148
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003149 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003150 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003151 IVI = IDecl->ivar_begin();
3152 IVE = IDecl->ivar_end();
3153 } else {
3154 IVI = CDecl->ivar_begin();
3155 IVE = CDecl->ivar_end();
3156 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003157 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003158 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003159 Result += "\", \"";
3160 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003161 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003162 Result += StrEncoding;
3163 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003164 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003165 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003166 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003167 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003168 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003169 Result += "\", \"";
3170 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003171 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003172 Result += StrEncoding;
3173 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003174 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003175 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 }
3177
3178 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003179 }
3180
3181 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003182 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003183 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003184
3185 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003186 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003187 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003189 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003190 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003191 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003192
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003193
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003194 // Declaration of class/meta-class metadata
3195 /* struct _objc_class {
3196 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003197 const char *super_class_name;
3198 char *name;
3199 long version;
3200 long info;
3201 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003202 struct _objc_ivar_list *ivars;
3203 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003204 struct objc_cache *cache;
3205 struct objc_protocol_list *protocols;
3206 const char *ivar_layout;
3207 struct _objc_class_ext *ext;
3208 };
3209 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003210 static bool objc_class = false;
3211 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003212 Result += "\nstruct _objc_class {\n";
3213 Result += "\tstruct _objc_class *isa;\n";
3214 Result += "\tconst char *super_class_name;\n";
3215 Result += "\tchar *name;\n";
3216 Result += "\tlong version;\n";
3217 Result += "\tlong info;\n";
3218 Result += "\tlong instance_size;\n";
3219 Result += "\tstruct _objc_ivar_list *ivars;\n";
3220 Result += "\tstruct _objc_method_list *methods;\n";
3221 Result += "\tstruct objc_cache *cache;\n";
3222 Result += "\tstruct _objc_protocol_list *protocols;\n";
3223 Result += "\tconst char *ivar_layout;\n";
3224 Result += "\tstruct _objc_class_ext *ext;\n";
3225 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003226 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003227 }
3228
3229 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003230 ObjCInterfaceDecl *RootClass = 0;
3231 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003232 while (SuperClass) {
3233 RootClass = SuperClass;
3234 SuperClass = SuperClass->getSuperClass();
3235 }
3236 SuperClass = CDecl->getSuperClass();
3237
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003238 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003239 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003240 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003241 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003242 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003243 Result += "\"";
3244
3245 if (SuperClass) {
3246 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003247 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003248 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003249 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003250 Result += "\"";
3251 }
3252 else {
3253 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003254 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003255 Result += "\"";
3256 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003257 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003258 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003259 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003260 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003261 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003262 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 Result += "\n";
3264 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003265 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003266 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003267 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003268 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003269 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003270 Result += ",0,0\n";
3271 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003272 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 Result += "\t,0,0,0,0\n";
3274 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003275
3276 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003277 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003279 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003282 if (SuperClass) {
3283 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003284 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003285 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += "\"";
3288 }
3289 else {
3290 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003291 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003292 Result += "\"";
3293 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003294 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003295 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003296 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003297 Result += ",0";
3298 else {
3299 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003300 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003301 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003302 if (LangOpts.Microsoft)
3303 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003304 Result += ")";
3305 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003306 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003307 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003308 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309 Result += "\n\t";
3310 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003311 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003312 Result += ",0";
3313 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003314 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003315 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += ", 0\n\t";
3317 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003318 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003319 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003320 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003321 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003322 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003323 Result += ", 0,0\n";
3324 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003325 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 Result += ",0,0,0\n";
3327 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003328}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003329
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003330/// RewriteImplementations - This routine rewrites all method implementations
3331/// and emits meta-data.
3332
Steve Narofface66252008-11-13 20:07:04 +00003333void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003334 int ClsDefCount = ClassImplementation.size();
3335 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003336
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003337 // Rewrite implemented methods
3338 for (int i = 0; i < ClsDefCount; i++)
3339 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003340
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003341 for (int i = 0; i < CatDefCount; i++)
3342 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003343}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003344
Steve Narofface66252008-11-13 20:07:04 +00003345void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3346 int ClsDefCount = ClassImplementation.size();
3347 int CatDefCount = CategoryImplementation.size();
3348
Steve Naroff5df5b762008-05-07 21:23:49 +00003349 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003350 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003351 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003352 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003353 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003354
3355 // For each implemented category, write out all its meta data.
3356 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003357 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003358
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003359 // Write objc_symtab metadata
3360 /*
3361 struct _objc_symtab
3362 {
3363 long sel_ref_cnt;
3364 SEL *refs;
3365 short cls_def_cnt;
3366 short cat_def_cnt;
3367 void *defs[cls_def_cnt + cat_def_cnt];
3368 };
3369 */
3370
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003371 Result += "\nstruct _objc_symtab {\n";
3372 Result += "\tlong sel_ref_cnt;\n";
3373 Result += "\tSEL *refs;\n";
3374 Result += "\tshort cls_def_cnt;\n";
3375 Result += "\tshort cat_def_cnt;\n";
3376 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3377 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003378
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003379 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003380 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003381 Result += "\t0, 0, " + utostr(ClsDefCount)
3382 + ", " + utostr(CatDefCount) + "\n";
3383 for (int i = 0; i < ClsDefCount; i++) {
3384 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003385 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003386 Result += "\n";
3387 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003388
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003389 for (int i = 0; i < CatDefCount; i++) {
3390 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003391 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003392 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003393 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003394 Result += "\n";
3395 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003396
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003397 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003398
3399 // Write objc_module metadata
3400
3401 /*
3402 struct _objc_module {
3403 long version;
3404 long size;
3405 const char *name;
3406 struct _objc_symtab *symtab;
3407 }
3408 */
3409
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\nstruct _objc_module {\n";
3411 Result += "\tlong version;\n";
3412 Result += "\tlong size;\n";
3413 Result += "\tconst char *name;\n";
3414 Result += "\tstruct _objc_symtab *symtab;\n";
3415 Result += "};\n\n";
3416 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003417 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003418 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3419 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003420 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003421
3422 if (LangOpts.Microsoft) {
3423 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003424 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003425 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3426 Result += "&_OBJC_MODULES;\n";
3427 Result += "#pragma data_seg(pop)\n\n";
3428 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003429}
Chris Lattner311ff022007-10-16 22:36:42 +00003430
Steve Naroff54055232008-10-27 17:20:55 +00003431std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3432 const char *funcName,
3433 std::string Tag) {
3434 const FunctionType *AFT = CE->getFunctionType();
3435 QualType RT = AFT->getResultType();
3436 std::string StructRef = "struct " + Tag;
3437 std::string S = "static " + RT.getAsString() + " __" +
3438 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003439
Steve Naroff54055232008-10-27 17:20:55 +00003440 BlockDecl *BD = CE->getBlockDecl();
3441
3442 if (isa<FunctionTypeNoProto>(AFT)) {
3443 S += "()";
3444 } else if (BD->param_empty()) {
3445 S += "(" + StructRef + " *__cself)";
3446 } else {
3447 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3448 assert(FT && "SynthesizeBlockFunc: No function proto");
3449 S += '(';
3450 // first add the implicit argument.
3451 S += StructRef + " *__cself, ";
3452 std::string ParamStr;
3453 for (BlockDecl::param_iterator AI = BD->param_begin(),
3454 E = BD->param_end(); AI != E; ++AI) {
3455 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003456 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003457 (*AI)->getType().getAsStringInternal(ParamStr);
3458 S += ParamStr;
3459 }
3460 if (FT->isVariadic()) {
3461 if (!BD->param_empty()) S += ", ";
3462 S += "...";
3463 }
3464 S += ')';
3465 }
3466 S += " {\n";
3467
3468 // Create local declarations to avoid rewriting all closure decl ref exprs.
3469 // First, emit a declaration for all "by ref" decls.
3470 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3471 E = BlockByRefDecls.end(); I != E; ++I) {
3472 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003473 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003474 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003475 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003476 }
3477 // Next, emit a declaration for all "by copy" declarations.
3478 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3479 E = BlockByCopyDecls.end(); I != E; ++I) {
3480 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003481 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003482 // Handle nested closure invocation. For example:
3483 //
3484 // void (^myImportedClosure)(void);
3485 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3486 //
3487 // void (^anotherClosure)(void);
3488 // anotherClosure = ^(void) {
3489 // myImportedClosure(); // import and invoke the closure
3490 // };
3491 //
3492 if (isBlockPointerType((*I)->getType()))
3493 S += "struct __block_impl *";
3494 else
3495 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003496 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003497 }
3498 std::string RewrittenStr = RewrittenBlockExprs[CE];
3499 const char *cstr = RewrittenStr.c_str();
3500 while (*cstr++ != '{') ;
3501 S += cstr;
3502 S += "\n";
3503 return S;
3504}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003505
Steve Naroff54055232008-10-27 17:20:55 +00003506std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3507 const char *funcName,
3508 std::string Tag) {
3509 std::string StructRef = "struct " + Tag;
3510 std::string S = "static void __";
3511
3512 S += funcName;
3513 S += "_block_copy_" + utostr(i);
3514 S += "(" + StructRef;
3515 S += "*dst, " + StructRef;
3516 S += "*src) {";
3517 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3518 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff47a24222008-12-11 20:51:38 +00003519 S += "_Block_copy_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003520 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003521 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003522 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003523 S += ");}";
3524 }
3525 S += "\nstatic void __";
3526 S += funcName;
3527 S += "_block_dispose_" + utostr(i);
3528 S += "(" + StructRef;
3529 S += "*src) {";
3530 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3531 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff47a24222008-12-11 20:51:38 +00003532 S += "_Block_destroy((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003533 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003534 S += ");";
3535 }
3536 S += "}\n";
3537 return S;
3538}
3539
3540std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3541 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003542 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003543 std::string Constructor = " " + Tag;
3544
3545 S += " {\n struct __block_impl impl;\n";
3546
3547 if (hasCopyDisposeHelpers)
3548 S += " void *copy;\n void *dispose;\n";
3549
3550 Constructor += "(void *fp";
3551
3552 if (hasCopyDisposeHelpers)
3553 Constructor += ", void *copyHelp, void *disposeHelp";
3554
3555 if (BlockDeclRefs.size()) {
3556 // Output all "by copy" declarations.
3557 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3558 E = BlockByCopyDecls.end(); I != E; ++I) {
3559 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003561 std::string ArgName = "_" + FieldName;
3562 // Handle nested closure invocation. For example:
3563 //
3564 // void (^myImportedBlock)(void);
3565 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3566 //
3567 // void (^anotherBlock)(void);
3568 // anotherBlock = ^(void) {
3569 // myImportedBlock(); // import and invoke the closure
3570 // };
3571 //
3572 if (isBlockPointerType((*I)->getType())) {
3573 S += "struct __block_impl *";
3574 Constructor += ", void *" + ArgName;
3575 } else {
3576 (*I)->getType().getAsStringInternal(FieldName);
3577 (*I)->getType().getAsStringInternal(ArgName);
3578 Constructor += ", " + ArgName;
3579 }
3580 S += FieldName + ";\n";
3581 }
3582 // Output all "by ref" declarations.
3583 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3584 E = BlockByRefDecls.end(); I != E; ++I) {
3585 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003587 std::string ArgName = "_" + FieldName;
3588 // Handle nested closure invocation. For example:
3589 //
3590 // void (^myImportedBlock)(void);
3591 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3592 //
3593 // void (^anotherBlock)(void);
3594 // anotherBlock = ^(void) {
3595 // myImportedBlock(); // import and invoke the closure
3596 // };
3597 //
3598 if (isBlockPointerType((*I)->getType())) {
3599 S += "struct __block_impl *";
3600 Constructor += ", void *" + ArgName;
3601 } else {
3602 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3603 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3604 Constructor += ", " + ArgName;
3605 }
3606 S += FieldName + "; // by ref\n";
3607 }
3608 // Finish writing the constructor.
3609 // FIXME: handle NSConcreteGlobalBlock.
3610 Constructor += ", int flags=0) {\n";
3611 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3612 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3613
3614 if (hasCopyDisposeHelpers)
3615 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3616
3617 // Initialize all "by copy" arguments.
3618 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3619 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003620 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003621 Constructor += " ";
3622 if (isBlockPointerType((*I)->getType()))
3623 Constructor += Name + " = (struct __block_impl *)_";
3624 else
3625 Constructor += Name + " = _";
3626 Constructor += Name + ";\n";
3627 }
3628 // Initialize all "by ref" arguments.
3629 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3630 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003631 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003632 Constructor += " ";
3633 if (isBlockPointerType((*I)->getType()))
3634 Constructor += Name + " = (struct __block_impl *)_";
3635 else
3636 Constructor += Name + " = _";
3637 Constructor += Name + ";\n";
3638 }
3639 } else {
3640 // Finish writing the constructor.
3641 // FIXME: handle NSConcreteGlobalBlock.
3642 Constructor += ", int flags=0) {\n";
3643 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3644 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3645 if (hasCopyDisposeHelpers)
3646 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3647 }
3648 Constructor += " ";
3649 Constructor += "}\n";
3650 S += Constructor;
3651 S += "};\n";
3652 return S;
3653}
3654
3655void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3656 const char *FunName) {
3657 // Insert closures that were part of the function.
3658 for (unsigned i = 0; i < Blocks.size(); i++) {
3659
3660 CollectBlockDeclRefInfo(Blocks[i]);
3661
3662 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3663
3664 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3665 ImportedBlockDecls.size() > 0);
3666
3667 InsertText(FunLocStart, CI.c_str(), CI.size());
3668
3669 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3670
3671 InsertText(FunLocStart, CF.c_str(), CF.size());
3672
3673 if (ImportedBlockDecls.size()) {
3674 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3675 InsertText(FunLocStart, HF.c_str(), HF.size());
3676 }
3677
3678 BlockDeclRefs.clear();
3679 BlockByRefDecls.clear();
3680 BlockByCopyDecls.clear();
3681 BlockCallExprs.clear();
3682 ImportedBlockDecls.clear();
3683 }
3684 Blocks.clear();
3685 RewrittenBlockExprs.clear();
3686}
3687
3688void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3689 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003690 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003691
3692 SynthesizeBlockLiterals(FunLocStart, FuncName);
3693}
3694
3695void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003696 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3697 //SourceLocation FunLocStart = MD->getLocStart();
3698 // FIXME: This hack works around a bug in Rewrite.InsertText().
3699 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003700 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003701 // Convert colons to underscores.
3702 std::string::size_type loc = 0;
3703 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3704 FuncName.replace(loc, 1, "_");
3705
3706 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3707}
3708
3709void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3710 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3711 CI != E; ++CI)
3712 if (*CI) {
3713 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3714 GetBlockDeclRefExprs(CBE->getBody());
3715 else
3716 GetBlockDeclRefExprs(*CI);
3717 }
3718 // Handle specific things.
3719 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3720 // FIXME: Handle enums.
3721 if (!isa<FunctionDecl>(CDRE->getDecl()))
3722 BlockDeclRefs.push_back(CDRE);
3723 return;
3724}
3725
3726void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3727 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3728 CI != E; ++CI)
3729 if (*CI) {
3730 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3731 GetBlockCallExprs(CBE->getBody());
3732 else
3733 GetBlockCallExprs(*CI);
3734 }
3735
3736 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3737 if (CE->getCallee()->getType()->isBlockPointerType()) {
3738 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3739 }
3740 }
3741 return;
3742}
3743
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003744Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003745 // Navigate to relevant type information.
3746 const char *closureName = 0;
3747 const BlockPointerType *CPT = 0;
3748
3749 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003750 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003751 CPT = DRE->getType()->getAsBlockPointerType();
3752 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003753 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003754 CPT = CDRE->getType()->getAsBlockPointerType();
3755 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003756 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003757 CPT = MExpr->getType()->getAsBlockPointerType();
3758 } else {
3759 assert(1 && "RewriteBlockClass: Bad type");
3760 }
3761 assert(CPT && "RewriteBlockClass: Bad type");
3762 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3763 assert(FT && "RewriteBlockClass: Bad type");
3764 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3765 // FTP will be null for closures that don't take arguments.
3766
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003767 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3768 SourceLocation(),
3769 &Context->Idents.get("__block_impl"));
3770 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003771
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003772 // Generate a funky cast.
3773 llvm::SmallVector<QualType, 8> ArgTypes;
3774
3775 // Push the block argument type.
3776 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003777 if (FTP) {
3778 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003779 E = FTP->arg_type_end(); I && (I != E); ++I) {
3780 QualType t = *I;
3781 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3782 if (isBlockPointerType(t)) {
3783 const BlockPointerType *BPT = t->getAsBlockPointerType();
3784 t = Context->getPointerType(BPT->getPointeeType());
3785 }
3786 ArgTypes.push_back(t);
3787 }
Steve Naroff54055232008-10-27 17:20:55 +00003788 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003789 // Now do the pointer to function cast.
3790 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3791 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3792
3793 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003794
Steve Naroffb2f9e512008-11-03 23:29:32 +00003795 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003796 // Don't forget the parens to enforce the proper binding.
3797 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3798 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003799
Douglas Gregor44b43212008-12-11 16:49:14 +00003800 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3801 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
3802 /*BitWidth=*/0, /*Mutable=*/true, 0);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003803 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3804
Steve Naroffb2f9e512008-11-03 23:29:32 +00003805 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003806 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3807
3808 llvm::SmallVector<Expr*, 8> BlkExprs;
3809 // Add the implicit argument.
3810 BlkExprs.push_back(BlkCast);
3811 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003812 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3813 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003814 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003815 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003816 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3817 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003818}
3819
3820void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003821 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3822 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003823}
3824
3825void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3826 // FIXME: Add more elaborate code generation required by the ABI.
3827 InsertText(BDRE->getLocStart(), "*", 1);
3828}
3829
Steve Naroffb2f9e512008-11-03 23:29:32 +00003830void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3831 SourceLocation LocStart = CE->getLParenLoc();
3832 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003833
3834 // Need to avoid trying to rewrite synthesized casts.
3835 if (LocStart.isInvalid())
3836 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003837 // Need to avoid trying to rewrite casts contained in macros.
3838 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3839 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003840
Steve Naroff54055232008-10-27 17:20:55 +00003841 const char *startBuf = SM->getCharacterData(LocStart);
3842 const char *endBuf = SM->getCharacterData(LocEnd);
3843
3844 // advance the location to startArgList.
3845 const char *argPtr = startBuf;
3846
3847 while (*argPtr++ && (argPtr < endBuf)) {
3848 switch (*argPtr) {
3849 case '^':
3850 // Replace the '^' with '*'.
3851 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3852 ReplaceText(LocStart, 1, "*", 1);
3853 break;
3854 }
3855 }
3856 return;
3857}
3858
3859void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3860 SourceLocation DeclLoc = FD->getLocation();
3861 unsigned parenCount = 0;
3862
3863 // We have 1 or more arguments that have closure pointers.
3864 const char *startBuf = SM->getCharacterData(DeclLoc);
3865 const char *startArgList = strchr(startBuf, '(');
3866
3867 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3868
3869 parenCount++;
3870 // advance the location to startArgList.
3871 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3872 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3873
3874 const char *argPtr = startArgList;
3875
3876 while (*argPtr++ && parenCount) {
3877 switch (*argPtr) {
3878 case '^':
3879 // Replace the '^' with '*'.
3880 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3881 ReplaceText(DeclLoc, 1, "*", 1);
3882 break;
3883 case '(':
3884 parenCount++;
3885 break;
3886 case ')':
3887 parenCount--;
3888 break;
3889 }
3890 }
3891 return;
3892}
3893
3894bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3895 const FunctionTypeProto *FTP;
3896 const PointerType *PT = QT->getAsPointerType();
3897 if (PT) {
3898 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3899 } else {
3900 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3901 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3902 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3903 }
3904 if (FTP) {
3905 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3906 E = FTP->arg_type_end(); I != E; ++I)
3907 if (isBlockPointerType(*I))
3908 return true;
3909 }
3910 return false;
3911}
3912
3913void RewriteObjC::GetExtentOfArgList(const char *Name,
3914 const char *&LParen, const char *&RParen) {
3915 const char *argPtr = strchr(Name, '(');
3916 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3917
3918 LParen = argPtr; // output the start.
3919 argPtr++; // skip past the left paren.
3920 unsigned parenCount = 1;
3921
3922 while (*argPtr && parenCount) {
3923 switch (*argPtr) {
3924 case '(': parenCount++; break;
3925 case ')': parenCount--; break;
3926 default: break;
3927 }
3928 if (parenCount) argPtr++;
3929 }
3930 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3931 RParen = argPtr; // output the end
3932}
3933
3934void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3935 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3936 RewriteBlockPointerFunctionArgs(FD);
3937 return;
3938 }
3939 // Handle Variables and Typedefs.
3940 SourceLocation DeclLoc = ND->getLocation();
3941 QualType DeclT;
3942 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3943 DeclT = VD->getType();
3944 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3945 DeclT = TDD->getUnderlyingType();
3946 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3947 DeclT = FD->getType();
3948 else
3949 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3950
3951 const char *startBuf = SM->getCharacterData(DeclLoc);
3952 const char *endBuf = startBuf;
3953 // scan backward (from the decl location) for the end of the previous decl.
3954 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3955 startBuf--;
3956
3957 // *startBuf != '^' if we are dealing with a pointer to function that
3958 // may take block argument types (which will be handled below).
3959 if (*startBuf == '^') {
3960 // Replace the '^' with '*', computing a negative offset.
3961 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3962 ReplaceText(DeclLoc, 1, "*", 1);
3963 }
3964 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3965 // Replace the '^' with '*' for arguments.
3966 DeclLoc = ND->getLocation();
3967 startBuf = SM->getCharacterData(DeclLoc);
3968 const char *argListBegin, *argListEnd;
3969 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3970 while (argListBegin < argListEnd) {
3971 if (*argListBegin == '^') {
3972 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3973 ReplaceText(CaretLoc, 1, "*", 1);
3974 }
3975 argListBegin++;
3976 }
3977 }
3978 return;
3979}
3980
3981void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3982 // Add initializers for any closure decl refs.
3983 GetBlockDeclRefExprs(Exp->getBody());
3984 if (BlockDeclRefs.size()) {
3985 // Unique all "by copy" declarations.
3986 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3987 if (!BlockDeclRefs[i]->isByRef())
3988 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3989 // Unique all "by ref" declarations.
3990 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3991 if (BlockDeclRefs[i]->isByRef()) {
3992 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3993 }
3994 // Find any imported blocks...they will need special attention.
3995 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00003996 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00003997 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003998 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3999 }
4000 }
4001}
4002
Steve Narofffa15fd92008-10-28 20:29:00 +00004003FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4004 IdentifierInfo *ID = &Context->Idents.get(name);
4005 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4006 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
4007 ID, FType, FunctionDecl::Extern, false, 0);
4008}
4009
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004010Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004011 Blocks.push_back(Exp);
4012
4013 CollectBlockDeclRefInfo(Exp);
4014 std::string FuncName;
4015
4016 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004017 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004018 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004019 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004020 // Convert colons to underscores.
4021 std::string::size_type loc = 0;
4022 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4023 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004024 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004025 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004026
4027 std::string BlockNumber = utostr(Blocks.size()-1);
4028
4029 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4030 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4031
4032 // Get a pointer to the function type so we can cast appropriately.
4033 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4034
4035 FunctionDecl *FD;
4036 Expr *NewRep;
4037
4038 // Simulate a contructor call...
4039 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4040 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4041
4042 llvm::SmallVector<Expr*, 4> InitExprs;
4043
Steve Narofffdc03722008-10-29 21:23:59 +00004044 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004045 FD = SynthBlockInitFunctionDecl(Func.c_str());
4046 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4047 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004048 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004049 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004050
4051 if (ImportedBlockDecls.size()) {
4052 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004053 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4054 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4055 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004056 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004057 InitExprs.push_back(castExpr);
4058
Steve Narofffa15fd92008-10-28 20:29:00 +00004059 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004060 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4061 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4062 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004063 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004064 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004065 }
4066 // Add initializers for any closure decl refs.
4067 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004068 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004069 // Output all "by copy" declarations.
4070 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4071 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004072 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004073 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004074 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004075 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004076 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004077 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004078 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4079 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004080 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004081 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004082 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004083 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004084 }
Steve Narofffdc03722008-10-29 21:23:59 +00004085 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004086 }
4087 // Output all "by ref" declarations.
4088 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4089 E = BlockByRefDecls.end(); I != E; ++I) {
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());
4092 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4093 Context->getPointerType(Exp->getType()),
4094 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004095 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004096 }
4097 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004098 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4099 FType, SourceLocation());
4100 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4101 Context->getPointerType(NewRep->getType()),
4102 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004103 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004104 BlockDeclRefs.clear();
4105 BlockByRefDecls.clear();
4106 BlockByCopyDecls.clear();
4107 ImportedBlockDecls.clear();
4108 return NewRep;
4109}
4110
4111//===----------------------------------------------------------------------===//
4112// Function Body / Expression rewriting
4113//===----------------------------------------------------------------------===//
4114
Steve Naroffc77a6362008-12-04 16:24:46 +00004115// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4116// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4117// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4118// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4119// Since the rewriter isn't capable of rewriting rewritten code, it's important
4120// we get this right.
4121void RewriteObjC::CollectPropertySetters(Stmt *S) {
4122 // Perform a bottom up traversal of all children.
4123 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4124 CI != E; ++CI)
4125 if (*CI)
4126 CollectPropertySetters(*CI);
4127
4128 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4129 if (BinOp->isAssignmentOp()) {
4130 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4131 PropSetters[PRE] = BinOp;
4132 }
4133 }
4134}
4135
Steve Narofffa15fd92008-10-28 20:29:00 +00004136Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4137 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4138 isa<DoStmt>(S) || isa<ForStmt>(S))
4139 Stmts.push_back(S);
4140 else if (isa<ObjCForCollectionStmt>(S)) {
4141 Stmts.push_back(S);
4142 ObjCBcLabelNo.push_back(++BcLabelCount);
4143 }
4144
4145 SourceRange OrigStmtRange = S->getSourceRange();
4146
4147 // Perform a bottom up rewrite of all children.
4148 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4149 CI != E; ++CI)
4150 if (*CI) {
4151 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4152 if (newStmt)
4153 *CI = newStmt;
4154 }
4155
4156 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4157 // Rewrite the block body in place.
4158 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4159
4160 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004161 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4162 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004163
4164 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4165 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004166 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004167 return blockTranscribed;
4168 }
4169 // Handle specific things.
4170 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4171 return RewriteAtEncode(AtEncode);
4172
4173 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4174 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4175
Steve Naroffc77a6362008-12-04 16:24:46 +00004176 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4177 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4178 if (BinOp) {
4179 // Because the rewriter doesn't allow us to rewrite rewritten code,
4180 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004181 DisableReplaceStmt = true;
4182 // Save the source range. Even if we disable the replacement, the
4183 // rewritten node will have been inserted into the tree. If the synthesized
4184 // node is at the 'end', the rewriter will fail. Consider this:
4185 // self.errorHandler = handler ? handler :
4186 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4187 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004188 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004189 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004190 //
4191 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4192 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4193 // to see the original expression). Consider this example:
4194 //
4195 // Foo *obj1, *obj2;
4196 //
4197 // obj1.i = [obj2 rrrr];
4198 //
4199 // 'BinOp' for the previous expression looks like:
4200 //
4201 // (BinaryOperator 0x231ccf0 'int' '='
4202 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4203 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4204 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4205 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4206 //
4207 // 'newStmt' represents the rewritten message expression. For example:
4208 //
4209 // (CallExpr 0x231d300 'id':'struct objc_object *'
4210 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4211 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4212 // (CStyleCastExpr 0x231d220 'void *'
4213 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4214 //
4215 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4216 // can be used as the setter argument. ReplaceStmt() will still 'see'
4217 // the original RHS (since we haven't altered BinOp).
4218 //
4219 // This implies the Rewrite* routines can no longer delete the original
4220 // node. As a result, we now leak the original AST nodes.
4221 //
Steve Naroffb619d952008-12-09 12:56:34 +00004222 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004223 } else {
4224 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004225 }
4226 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004227 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4228 return RewriteAtSelector(AtSelector);
4229
4230 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4231 return RewriteObjCStringLiteral(AtString);
4232
4233 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004234#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004235 // Before we rewrite it, put the original message expression in a comment.
4236 SourceLocation startLoc = MessExpr->getLocStart();
4237 SourceLocation endLoc = MessExpr->getLocEnd();
4238
4239 const char *startBuf = SM->getCharacterData(startLoc);
4240 const char *endBuf = SM->getCharacterData(endLoc);
4241
4242 std::string messString;
4243 messString += "// ";
4244 messString.append(startBuf, endBuf-startBuf+1);
4245 messString += "\n";
4246
4247 // FIXME: Missing definition of
4248 // InsertText(clang::SourceLocation, char const*, unsigned int).
4249 // InsertText(startLoc, messString.c_str(), messString.size());
4250 // Tried this, but it didn't work either...
4251 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004252#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004253 return RewriteMessageExpr(MessExpr);
4254 }
4255
4256 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4257 return RewriteObjCTryStmt(StmtTry);
4258
4259 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4260 return RewriteObjCSynchronizedStmt(StmtTry);
4261
4262 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4263 return RewriteObjCThrowStmt(StmtThrow);
4264
4265 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4266 return RewriteObjCProtocolExpr(ProtocolExp);
4267
4268 if (ObjCForCollectionStmt *StmtForCollection =
4269 dyn_cast<ObjCForCollectionStmt>(S))
4270 return RewriteObjCForCollectionStmt(StmtForCollection,
4271 OrigStmtRange.getEnd());
4272 if (BreakStmt *StmtBreakStmt =
4273 dyn_cast<BreakStmt>(S))
4274 return RewriteBreakStmt(StmtBreakStmt);
4275 if (ContinueStmt *StmtContinueStmt =
4276 dyn_cast<ContinueStmt>(S))
4277 return RewriteContinueStmt(StmtContinueStmt);
4278
4279 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4280 // and cast exprs.
4281 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4282 // FIXME: What we're doing here is modifying the type-specifier that
4283 // precedes the first Decl. In the future the DeclGroup should have
4284 // a separate type-specifier that we can rewrite.
4285 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4286
4287 // Blocks rewrite rules.
4288 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4289 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004290 ScopedDecl *SD = *DI;
4291 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4292 if (isBlockPointerType(ND->getType()))
4293 RewriteBlockPointerDecl(ND);
4294 else if (ND->getType()->isFunctionPointerType())
4295 CheckFunctionPointerDecl(ND->getType(), ND);
4296 }
4297 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4298 if (isBlockPointerType(TD->getUnderlyingType()))
4299 RewriteBlockPointerDecl(TD);
4300 else if (TD->getUnderlyingType()->isFunctionPointerType())
4301 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4302 }
4303 }
4304 }
4305
4306 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4307 RewriteObjCQualifiedInterfaceTypes(CE);
4308
4309 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4310 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4311 assert(!Stmts.empty() && "Statement stack is empty");
4312 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4313 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4314 && "Statement stack mismatch");
4315 Stmts.pop_back();
4316 }
4317 // Handle blocks rewriting.
4318 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4319 if (BDRE->isByRef())
4320 RewriteBlockDeclRefExpr(BDRE);
4321 }
4322 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004323 if (CE->getCallee()->getType()->isBlockPointerType()) {
4324 Stmt *BlockCall = SynthesizeBlockCall(CE);
4325 ReplaceStmt(S, BlockCall);
4326 return BlockCall;
4327 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004328 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004329 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004330 RewriteCastExpr(CE);
4331 }
4332#if 0
4333 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4334 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4335 // Get the new text.
4336 std::string SStr;
4337 llvm::raw_string_ostream Buf(SStr);
4338 Replacement->printPretty(Buf);
4339 const std::string &Str = Buf.str();
4340
4341 printf("CAST = %s\n", &Str[0]);
4342 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4343 delete S;
4344 return Replacement;
4345 }
4346#endif
4347 // Return this stmt unmodified.
4348 return S;
4349}
4350
4351/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4352/// main file of the input.
4353void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4355 // Since function prototypes don't have ParmDecl's, we check the function
4356 // prototype. This enables us to rewrite function declarations and
4357 // definitions using the same code.
4358 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4359
4360 if (Stmt *Body = FD->getBody()) {
4361 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004362 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004363 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004364 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004365 CurrentBody = 0;
4366 if (PropParentMap) {
4367 delete PropParentMap;
4368 PropParentMap = 0;
4369 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004370 // This synthesizes and inserts the block "impl" struct, invoke function,
4371 // and any copy/dispose helper functions.
4372 InsertBlockLiteralsWithinFunction(FD);
4373 CurFunctionDef = 0;
4374 }
4375 return;
4376 }
4377 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4378 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004379 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004380 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004381 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004382 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004383 CurrentBody = 0;
4384 if (PropParentMap) {
4385 delete PropParentMap;
4386 PropParentMap = 0;
4387 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004388 InsertBlockLiteralsWithinMethod(MD);
4389 CurMethodDef = 0;
4390 }
4391 }
4392 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4393 ClassImplementation.push_back(CI);
4394 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4395 CategoryImplementation.push_back(CI);
4396 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4397 RewriteForwardClassDecl(CD);
4398 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4399 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004400 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004401 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004402 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004403 CheckFunctionPointerDecl(VD->getType(), VD);
4404 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004405 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004406 RewriteCastExpr(CE);
4407 }
4408 }
4409 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004410 if (VD->getInit()) {
4411 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004412 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004413 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004414 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004415 CurrentBody = 0;
4416 if (PropParentMap) {
4417 delete PropParentMap;
4418 PropParentMap = 0;
4419 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004420 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004421 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004422 GlobalVarDecl = 0;
4423
4424 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004425 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004426 RewriteCastExpr(CE);
4427 }
4428 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004429 return;
4430 }
4431 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4432 if (isBlockPointerType(TD->getUnderlyingType()))
4433 RewriteBlockPointerDecl(TD);
4434 else if (TD->getUnderlyingType()->isFunctionPointerType())
4435 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4436 return;
4437 }
4438 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4439 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004440 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004441 e = RD->field_end(); i != e; ++i) {
4442 FieldDecl *FD = *i;
4443 if (isBlockPointerType(FD->getType()))
4444 RewriteBlockPointerDecl(FD);
4445 }
4446 }
4447 return;
4448 }
4449 // Nothing yet.
4450}
4451
4452void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4453 // Get the top-level buffer that this corresponds to.
4454
4455 // Rewrite tabs if we care.
4456 //RewriteTabs();
4457
4458 if (Diags.hasErrorOccurred())
4459 return;
4460
4461 // Create the output file.
4462
4463 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4464 llvm::raw_ostream *OutFile;
4465 if (OutFileName == "-") {
4466 OutFile = &llvm::outs();
4467 } else if (!OutFileName.empty()) {
4468 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004469 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004470 OwnedStream.reset(OutFile);
4471 } else if (InFileName == "-") {
4472 OutFile = &llvm::outs();
4473 } else {
4474 llvm::sys::Path Path(InFileName);
4475 Path.eraseSuffix();
4476 Path.appendSuffix("cpp");
4477 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004478 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004479 OwnedStream.reset(OutFile);
4480 }
4481
4482 RewriteInclude();
4483
4484 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4485 Preamble.c_str(), Preamble.size(), false);
4486
Steve Naroff0aab7962008-11-14 14:10:01 +00004487 if (ClassImplementation.size() || CategoryImplementation.size())
4488 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004489
4490 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4491 // we are done.
4492 if (const RewriteBuffer *RewriteBuf =
4493 Rewrite.getRewriteBufferFor(MainFileID)) {
4494 //printf("Changed:\n");
4495 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4496 } else {
4497 fprintf(stderr, "No changes\n");
4498 }
Steve Narofface66252008-11-13 20:07:04 +00004499
Steve Naroff0aab7962008-11-14 14:10:01 +00004500 if (ClassImplementation.size() || CategoryImplementation.size()) {
4501 // Rewrite Objective-c meta data*
4502 std::string ResultStr;
4503 SynthesizeMetaDataIntoBuffer(ResultStr);
4504 // Emit metadata.
4505 *OutFile << ResultStr;
4506 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 OutFile->flush();
4508}
4509