blob: 6d672337192c4b2f4fd6ea8409fc8ca74a404a51 [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";
540 Preamble += "enum {\n";
541 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
542 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
543 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000544 Preamble += "// Runtime copy/destroy helper functions\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000545 Preamble += "__OBJC_RW_STATICIMPORT void _Block_copy_assign(void *, void *);\n";
546 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_assign_copy(void *, void *);\n";
547 Preamble += "__OBJC_RW_STATICIMPORT void _Block_destroy(void *);\n";
548 Preamble += "__OBJC_RW_STATICIMPORT void _Block_byref_release(void *);\n";
549 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock;\n";
550 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000551 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000552 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000553 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
554 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000555 Preamble += "#define __attribute__(X)\n";
556 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557}
558
559
Chris Lattnerf04da132007-10-24 17:06:59 +0000560//===----------------------------------------------------------------------===//
561// Top Level Driver Code
562//===----------------------------------------------------------------------===//
563
Steve Naroffb29b4272008-04-14 22:03:09 +0000564void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000565 // Two cases: either the decl could be in the main file, or it could be in a
566 // #included file. If the former, rewrite it now. If the later, check to see
567 // if we rewrote the #include/#import.
568 SourceLocation Loc = D->getLocation();
569 Loc = SM->getLogicalLoc(Loc);
570
571 // If this is for a builtin, ignore it.
572 if (Loc.isInvalid()) return;
573
Steve Naroffebf2b562007-10-23 23:50:29 +0000574 // Look for built-in declarations that we need to refer during the rewrite.
575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000576 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000577 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000578 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000579 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000580 ConstantStringClassReference = FVD;
581 return;
582 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000584 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000586 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000587 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000588 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 } else if (ObjCForwardProtocolDecl *FP =
590 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000591 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000592 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000593 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000594 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000595 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000596}
597
Chris Lattnerf04da132007-10-24 17:06:59 +0000598//===----------------------------------------------------------------------===//
599// Syntactic (non-AST) Rewriting Code
600//===----------------------------------------------------------------------===//
601
Steve Naroffb29b4272008-04-14 22:03:09 +0000602void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000603 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
604 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
605 const char *MainBufStart = MainBuf.first;
606 const char *MainBufEnd = MainBuf.second;
607 size_t ImportLen = strlen("import");
608 size_t IncludeLen = strlen("include");
609
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000610 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000611 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
612 if (*BufPtr == '#') {
613 if (++BufPtr == MainBufEnd)
614 return;
615 while (*BufPtr == ' ' || *BufPtr == '\t')
616 if (++BufPtr == MainBufEnd)
617 return;
618 if (!strncmp(BufPtr, "import", ImportLen)) {
619 // replace import with include
620 SourceLocation ImportLoc =
621 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000622 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000623 BufPtr += ImportLen;
624 }
625 }
626 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000627}
628
Steve Naroffb29b4272008-04-14 22:03:09 +0000629void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000630 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
631 const char *MainBufStart = MainBuf.first;
632 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000633
Chris Lattnerf04da132007-10-24 17:06:59 +0000634 // Loop over the whole file, looking for tabs.
635 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
636 if (*BufPtr != '\t')
637 continue;
638
639 // Okay, we found a tab. This tab will turn into at least one character,
640 // but it depends on which 'virtual column' it is in. Compute that now.
641 unsigned VCol = 0;
642 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
643 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
644 ++VCol;
645
646 // Okay, now that we know the virtual column, we know how many spaces to
647 // insert. We assume 8-character tab-stops.
648 unsigned Spaces = 8-(VCol & 7);
649
650 // Get the location of the tab.
651 SourceLocation TabLoc =
652 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
653
654 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000655 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000656 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000657}
658
Steve Naroffeb0646c2008-12-02 15:48:25 +0000659static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
660 ObjCIvarDecl *OID) {
661 std::string S;
662 S = "((struct ";
663 S += ClassDecl->getIdentifier()->getName();
664 S += "_IMPL *)self)->";
665 S += OID->getNameAsCString();
666 return S;
667}
668
Steve Naroffa0876e82008-12-02 17:36:43 +0000669void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
670 ObjCImplementationDecl *IMD,
671 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000672 SourceLocation startLoc = PID->getLocStart();
673 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000674 const char *startBuf = SM->getCharacterData(startLoc);
675 assert((*startBuf == '@') && "bogus @synthesize location");
676 const char *semiBuf = strchr(startBuf, ';');
677 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
678 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
679
680 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
681 return; // FIXME: is this correct?
682
683 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000684 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000685 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000686 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000687
688 if (!OID)
689 return;
690
691 std::string Getr;
692 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
693 Getr += "{ ";
694 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000695 // FIXME: deal with code generation implications for various property
696 // attributes (copy, retain, nonatomic).
697 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000698 Getr += "return " + getIvarAccessString(ClassDecl, OID);
699 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000700 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000701
702 // Add the rewritten getter to trigger meta data generation. An alternate, and
703 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
704 // with properties explicitly. The following addInstanceMethod() required far
705 // less code change (and actually models what the rewriter is doing).
706 if (IMD)
707 IMD->addInstanceMethod(PD->getGetterMethodDecl());
708 else
709 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000710
711 if (PD->isReadOnly())
712 return;
713
714 // Generate the 'setter' function.
715 std::string Setr;
716 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000717 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000718 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000719 // FIXME: deal with code generation implications for various property
720 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000721 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000722 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
723 Setr += OID->getNameAsCString();
724 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000725 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000726
727 // Add the rewritten setter to trigger meta data generation.
728 if (IMD)
729 IMD->addInstanceMethod(PD->getSetterMethodDecl());
730 else
731 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000732}
Chris Lattner8a12c272007-10-11 18:38:32 +0000733
Steve Naroffb29b4272008-04-14 22:03:09 +0000734void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000735 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000737
738 // Get the start location and compute the semi location.
739 SourceLocation startLoc = ClassDecl->getLocation();
740 const char *startBuf = SM->getCharacterData(startLoc);
741 const char *semiPtr = strchr(startBuf, ';');
742
743 // Translate to typedef's that forward reference structs with the same name
744 // as the class. As a convenience, we include the original declaration
745 // as a comment.
746 std::string typedefString;
747 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000748 typedefString.append(startBuf, semiPtr-startBuf+1);
749 typedefString += "\n";
750 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000754 typedefString += "\n";
755 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000758 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000759 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000760 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000761 }
762
763 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(startLoc, semiPtr-startBuf+1,
765 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000766}
767
Steve Naroffb29b4272008-04-14 22:03:09 +0000768void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 SourceLocation LocStart = Method->getLocStart();
770 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000771
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000773 InsertText(LocStart, "#if 0\n", 6);
774 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000775 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000776 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000777 }
778}
779
Steve Naroffb29b4272008-04-14 22:03:09 +0000780void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000781{
Chris Lattner55d13b42008-03-16 21:23:50 +0000782 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000784 SourceLocation Loc = Property->getLocation();
785
Chris Lattneraadaf782008-01-31 19:51:04 +0000786 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000787
788 // FIXME: handle properties that are declared across multiple lines.
789 }
790}
791
Steve Naroffb29b4272008-04-14 22:03:09 +0000792void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000793 SourceLocation LocStart = CatDecl->getLocStart();
794
795 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000796 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000797
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000798 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000799 E = CatDecl->instmeth_end(); I != E; ++I)
800 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000802 E = CatDecl->classmeth_end(); I != E; ++I)
803 RewriteMethodDeclaration(*I);
804
Steve Naroff423cb562007-10-30 13:30:57 +0000805 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000806 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000807}
808
Steve Naroffb29b4272008-04-14 22:03:09 +0000809void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812 SourceLocation LocStart = PDecl->getLocStart();
813
814 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000816
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000817 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000818 E = PDecl->instmeth_end(); I != E; ++I)
819 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000821 E = PDecl->classmeth_end(); I != E; ++I)
822 RewriteMethodDeclaration(*I);
823
Steve Naroff752d6ef2007-10-30 16:42:30 +0000824 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000825 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000826 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000827
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000828 // Must comment out @optional/@required
829 const char *startBuf = SM->getCharacterData(LocStart);
830 const char *endBuf = SM->getCharacterData(LocEnd);
831 for (const char *p = startBuf; p < endBuf; p++) {
832 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
833 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000834 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000835 ReplaceText(OptionalLoc, strlen("@optional"),
836 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000837
838 }
839 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
840 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000841 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000842 ReplaceText(OptionalLoc, strlen("@required"),
843 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000844
845 }
846 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000847}
848
Steve Naroffb29b4272008-04-14 22:03:09 +0000849void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000851 if (LocStart.isInvalid())
852 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000853 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000854 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000855}
856
Steve Naroffb29b4272008-04-14 22:03:09 +0000857void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000859 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000860 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000863 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000864 else if (OMD->getResultType()->isFunctionPointerType()) {
865 // needs special handling, since pointer-to-functions have special
866 // syntax (where a decaration models use).
867 QualType retType = OMD->getResultType();
868 if (const PointerType* PT = retType->getAsPointerType()) {
869 QualType PointeeTy = PT->getPointeeType();
870 if ((FPRetType = PointeeTy->getAsFunctionType())) {
871 ResultStr += FPRetType->getResultType().getAsString();
872 ResultStr += "(*";
873 }
874 }
875 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000876 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000877 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878
879 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000880 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000881
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000882 if (OMD->isInstance())
883 NameStr += "_I_";
884 else
885 NameStr += "_C_";
886
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000887 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000889
890 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000891 if (ObjCCategoryImplDecl *CID =
892 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000893 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000894 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000895 }
Steve Naroff563b8282008-04-04 22:23:44 +0000896 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000897 {
898 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000899 int len = selString.size();
900 for (int i = 0; i < len; i++)
901 if (selString[i] == ':')
902 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000903 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000904 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000905 // Remember this name for metadata emission
906 MethodInternalNames[OMD] = NameStr;
907 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000908
909 // Rewrite arguments
910 ResultStr += "(";
911
912 // invisible arguments
913 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000914 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000915 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000916 if (!LangOpts.Microsoft) {
917 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
918 ResultStr += "struct ";
919 }
920 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000921 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000922 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923 }
924 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000925 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926
927 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929 ResultStr += " _cmd";
930
931 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000932 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000933 ParmVarDecl *PDecl = OMD->getParamDecl(i);
934 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000935 if (PDecl->getType()->isObjCQualifiedIdType()) {
936 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000937 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000938 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000940 if (isBlockPointerType(PDecl->getType())) {
941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
942 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
943 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
944 } else
945 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000946 ResultStr += Name;
947 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000949 if (OMD->isVariadic())
950 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000951 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000952
Steve Naroff76e429d2008-07-16 14:40:40 +0000953 if (FPRetType) {
954 ResultStr += ")"; // close the precedence "scope" for "*".
955
956 // Now, emit the argument types (if any).
957 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
958 ResultStr += "(";
959 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
960 if (i) ResultStr += ", ";
961 std::string ParamStr = FT->getArgType(i).getAsString();
962 ResultStr += ParamStr;
963 }
964 if (FT->isVariadic()) {
965 if (FT->getNumArgs()) ResultStr += ", ";
966 ResultStr += "...";
967 }
968 ResultStr += ")";
969 } else {
970 ResultStr += "()";
971 }
972 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000973}
Steve Naroffb29b4272008-04-14 22:03:09 +0000974void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
976 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000977
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000978 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000979 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000980 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000981 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000982
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000983 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000984 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
985 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000986 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000987 ObjCMethodDecl *OMD = *I;
988 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989 SourceLocation LocStart = OMD->getLocStart();
990 SourceLocation LocEnd = OMD->getBody()->getLocStart();
991
992 const char *startBuf = SM->getCharacterData(LocStart);
993 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000994 ReplaceText(LocStart, endBuf-startBuf,
995 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 }
997
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000999 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1000 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001001 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001002 ObjCMethodDecl *OMD = *I;
1003 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 SourceLocation LocStart = OMD->getLocStart();
1005 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1006
1007 const char *startBuf = SM->getCharacterData(LocStart);
1008 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001009 ReplaceText(LocStart, endBuf-startBuf,
1010 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001011 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001012 for (ObjCCategoryImplDecl::propimpl_iterator
1013 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1014 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001015 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001016 }
1017
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001018 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001019 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001020 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001021 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001022}
1023
Steve Naroffb29b4272008-04-14 22:03:09 +00001024void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001025 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001027 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001028 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001029 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001030 ResultStr += "\n";
1031 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001032 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001033 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001034 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001035 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001036 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001037 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001038 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001039 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001040 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001041
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001042 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1043 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001044 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001045 E = ClassDecl->instmeth_end(); I != E; ++I)
1046 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001048 E = ClassDecl->classmeth_end(); I != E; ++I)
1049 RewriteMethodDeclaration(*I);
1050
Steve Naroff2feac5e2007-10-30 03:43:13 +00001051 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001052 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001053}
1054
Steve Naroffb619d952008-12-09 12:56:34 +00001055Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1056 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001057 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1058 // This allows us to reuse all the fun and games in SynthMessageExpr().
1059 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1060 ObjCMessageExpr *MsgExpr;
1061 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1062 llvm::SmallVector<Expr *, 1> ExprVec;
1063 ExprVec.push_back(newStmt);
1064
Steve Naroff8599e7a2008-12-08 16:43:47 +00001065 Stmt *Receiver = PropRefExpr->getBase();
1066 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1067 if (PRE && PropGetters[PRE]) {
1068 // This allows us to handle chain/nested property getters.
1069 Receiver = PropGetters[PRE];
1070 }
1071 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001072 PDecl->getSetterName(), PDecl->getType(),
1073 PDecl->getSetterMethodDecl(),
1074 SourceLocation(), SourceLocation(),
1075 &ExprVec[0], 1);
1076 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1077
1078 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001079 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00001080 delete BinOp;
1081 delete MsgExpr;
1082 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001083}
1084
Steve Naroffc77a6362008-12-04 16:24:46 +00001085Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001086 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1087 // This allows us to reuse all the fun and games in SynthMessageExpr().
1088 ObjCMessageExpr *MsgExpr;
1089 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1090
Steve Naroff8599e7a2008-12-08 16:43:47 +00001091 Stmt *Receiver = PropRefExpr->getBase();
1092
1093 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1094 if (PRE && PropGetters[PRE]) {
1095 // This allows us to handle chain/nested property getters.
1096 Receiver = PropGetters[PRE];
1097 }
1098 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001099 PDecl->getGetterName(), PDecl->getType(),
1100 PDecl->getGetterMethodDecl(),
1101 SourceLocation(), SourceLocation(),
1102 0, 0);
1103
Steve Naroff4c3580e2008-12-04 23:50:32 +00001104 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001105
1106 if (!PropParentMap)
1107 PropParentMap = new ParentMap(CurrentBody);
1108
1109 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1110 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1111 // We stash away the ReplacingStmt since actually doing the
1112 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1113 PropGetters[PropRefExpr] = ReplacingStmt;
1114 delete MsgExpr;
1115 return PropRefExpr; // return the original...
1116 } else {
1117 ReplaceStmt(PropRefExpr, ReplacingStmt);
1118 // delete PropRefExpr; elsewhere...
1119 delete MsgExpr;
1120 return ReplacingStmt;
1121 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001122}
1123
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001124Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1125 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001126 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001127 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001128 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001129 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1130 // lookup which class implements the instance variable.
1131 ObjCInterfaceDecl *clsDeclared = 0;
1132 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1133 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1134
1135 // Synthesize an explicit cast to gain access to the ivar.
1136 std::string RecName = clsDeclared->getIdentifier()->getName();
1137 RecName += "_IMPL";
1138 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001139 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001140 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001141 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1142 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001143 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001144 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001145 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001146 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1147 IV->getBase()->getLocEnd(),
1148 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001149 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001150 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001151 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1152 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001153 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001154 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001155 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001156 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001157
1158 ReplaceStmt(IV->getBase(), PE);
1159 // Cannot delete IV->getBase(), since PE points to it.
1160 // Replace the old base with the cast. This is important when doing
1161 // embedded rewrites. For example, [newInv->_container addObject:0].
1162 IV->setBase(PE);
1163 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001164 }
Steve Naroff84472a82008-04-18 21:55:08 +00001165 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001166 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1167
1168 // Explicit ivar refs need to have a cast inserted.
1169 // FIXME: consider sharing some of this code with the code above.
1170 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001171 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001172 // lookup which class implements the instance variable.
1173 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001174 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001175 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1176
1177 // Synthesize an explicit cast to gain access to the ivar.
1178 std::string RecName = clsDeclared->getIdentifier()->getName();
1179 RecName += "_IMPL";
1180 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001181 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001182 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001183 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1184 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001185 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001186 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001187 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001188 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1189 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001190 ReplaceStmt(IV->getBase(), PE);
1191 // Cannot delete IV->getBase(), since PE points to it.
1192 // Replace the old base with the cast. This is important when doing
1193 // embedded rewrites. For example, [newInv->_container addObject:0].
1194 IV->setBase(PE);
1195 return IV;
1196 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001197 }
Steve Naroff84472a82008-04-18 21:55:08 +00001198 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001199}
1200
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001201/// SynthCountByEnumWithState - To print:
1202/// ((unsigned int (*)
1203/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1204/// (void *)objc_msgSend)((id)l_collection,
1205/// sel_registerName(
1206/// "countByEnumeratingWithState:objects:count:"),
1207/// &enumState,
1208/// (id *)items, (unsigned int)16)
1209///
Steve Naroffb29b4272008-04-14 22:03:09 +00001210void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001211 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1212 "id *, unsigned int))(void *)objc_msgSend)";
1213 buf += "\n\t\t";
1214 buf += "((id)l_collection,\n\t\t";
1215 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1216 buf += "\n\t\t";
1217 buf += "&enumState, "
1218 "(id *)items, (unsigned int)16)";
1219}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001220
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001221/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1222/// statement to exit to its outer synthesized loop.
1223///
Steve Naroffb29b4272008-04-14 22:03:09 +00001224Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001225 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1226 return S;
1227 // replace break with goto __break_label
1228 std::string buf;
1229
1230 SourceLocation startLoc = S->getLocStart();
1231 buf = "goto __break_label_";
1232 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001233 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001234
1235 return 0;
1236}
1237
1238/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1239/// statement to continue with its inner synthesized loop.
1240///
Steve Naroffb29b4272008-04-14 22:03:09 +00001241Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001242 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1243 return S;
1244 // replace continue with goto __continue_label
1245 std::string buf;
1246
1247 SourceLocation startLoc = S->getLocStart();
1248 buf = "goto __continue_label_";
1249 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001250 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001251
1252 return 0;
1253}
1254
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001255/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001256/// It rewrites:
1257/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001258
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001259/// Into:
1260/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001261/// type elem;
1262/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001263/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264/// id l_collection = (id)collection;
1265/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1266/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001267/// if (limit) {
1268/// unsigned long startMutations = *enumState.mutationsPtr;
1269/// do {
1270/// unsigned long counter = 0;
1271/// do {
1272/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001274/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001275/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001276/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001277/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001278/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1279/// objects:items count:16]);
1280/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001281/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282/// }
1283/// else
1284/// elem = nil;
1285/// }
1286///
Steve Naroffb29b4272008-04-14 22:03:09 +00001287Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001288 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001289 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1290 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1291 "ObjCForCollectionStmt Statement stack mismatch");
1292 assert(!ObjCBcLabelNo.empty() &&
1293 "ObjCForCollectionStmt - Label No stack empty");
1294
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001295 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001296 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001297 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001298 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001299 std::string buf;
1300 buf = "\n{\n\t";
1301 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1302 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001303 ScopedDecl* D = DS->getSolitaryDecl();
1304 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001305 elementTypeAsString = ElementType.getAsString();
1306 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001308 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001309 buf += elementName;
1310 buf += ";\n\t";
1311 }
Chris Lattner06767512008-04-08 05:52:18 +00001312 else {
1313 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001314 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001315 elementTypeAsString
1316 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001317 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001318
1319 // struct __objcFastEnumerationState enumState = { 0 };
1320 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1321 // id items[16];
1322 buf += "id items[16];\n\t";
1323 // id l_collection = (id)
1324 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001325 // Find start location of 'collection' the hard way!
1326 const char *startCollectionBuf = startBuf;
1327 startCollectionBuf += 3; // skip 'for'
1328 startCollectionBuf = strchr(startCollectionBuf, '(');
1329 startCollectionBuf++; // skip '('
1330 // find 'in' and skip it.
1331 while (*startCollectionBuf != ' ' ||
1332 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1333 (*(startCollectionBuf+3) != ' ' &&
1334 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1335 startCollectionBuf++;
1336 startCollectionBuf += 3;
1337
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001338 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001339 ReplaceText(startLoc, startCollectionBuf - startBuf,
1340 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001341 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001342 SourceLocation rightParenLoc = S->getRParenLoc();
1343 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1344 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001345 buf = ";\n\t";
1346
1347 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1348 // objects:items count:16];
1349 // which is synthesized into:
1350 // unsigned int limit =
1351 // ((unsigned int (*)
1352 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1353 // (void *)objc_msgSend)((id)l_collection,
1354 // sel_registerName(
1355 // "countByEnumeratingWithState:objects:count:"),
1356 // (struct __objcFastEnumerationState *)&state,
1357 // (id *)items, (unsigned int)16);
1358 buf += "unsigned long limit =\n\t\t";
1359 SynthCountByEnumWithState(buf);
1360 buf += ";\n\t";
1361 /// if (limit) {
1362 /// unsigned long startMutations = *enumState.mutationsPtr;
1363 /// do {
1364 /// unsigned long counter = 0;
1365 /// do {
1366 /// if (startMutations != *enumState.mutationsPtr)
1367 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001368 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369 buf += "if (limit) {\n\t";
1370 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1371 buf += "do {\n\t\t";
1372 buf += "unsigned long counter = 0;\n\t\t";
1373 buf += "do {\n\t\t\t";
1374 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1375 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1376 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001377 buf += " = (";
1378 buf += elementTypeAsString;
1379 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001381 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001383 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384 /// } while (counter < limit);
1385 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1386 /// objects:items count:16]);
1387 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001388 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389 /// }
1390 /// else
1391 /// elem = nil;
1392 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001393 ///
1394 buf = ";\n\t";
1395 buf += "__continue_label_";
1396 buf += utostr(ObjCBcLabelNo.back());
1397 buf += ": ;";
1398 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001399 buf += "} while (counter < limit);\n\t";
1400 buf += "} while (limit = ";
1401 SynthCountByEnumWithState(buf);
1402 buf += ");\n\t";
1403 buf += elementName;
1404 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001405 buf += "__break_label_";
1406 buf += utostr(ObjCBcLabelNo.back());
1407 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001408 buf += "}\n\t";
1409 buf += "else\n\t\t";
1410 buf += elementName;
1411 buf += " = nil;\n";
1412 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001413
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001415 if (isa<CompoundStmt>(S->getBody())) {
1416 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1417 InsertText(endBodyLoc, buf.c_str(), buf.size());
1418 } else {
1419 /* Need to treat single statements specially. For example:
1420 *
1421 * for (A *a in b) if (stuff()) break;
1422 * for (A *a in b) xxxyy;
1423 *
1424 * The following code simply scans ahead to the semi to find the actual end.
1425 */
1426 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1427 const char *semiBuf = strchr(stmtBuf, ';');
1428 assert(semiBuf && "Can't find ';'");
1429 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1430 InsertText(endBodyLoc, buf.c_str(), buf.size());
1431 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001432 Stmts.pop_back();
1433 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001435}
1436
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001437/// RewriteObjCSynchronizedStmt -
1438/// This routine rewrites @synchronized(expr) stmt;
1439/// into:
1440/// objc_sync_enter(expr);
1441/// @try stmt @finally { objc_sync_exit(expr); }
1442///
Steve Naroffb29b4272008-04-14 22:03:09 +00001443Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001444 // Get the start location and compute the semi location.
1445 SourceLocation startLoc = S->getLocStart();
1446 const char *startBuf = SM->getCharacterData(startLoc);
1447
1448 assert((*startBuf == '@') && "bogus @synchronized location");
1449
1450 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001451 buf = "objc_sync_enter((id)";
1452 const char *lparenBuf = startBuf;
1453 while (*lparenBuf != '(') lparenBuf++;
1454 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001455 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1456 // the sync expression is typically a message expression that's already
1457 // been rewritten! (which implies the SourceLocation's are invalid).
1458 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001459 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001460 while (*endBuf != ')') endBuf--;
1461 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001462 buf = ");\n";
1463 // declare a new scope with two variables, _stack and _rethrow.
1464 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1465 buf += "int buf[18/*32-bit i386*/];\n";
1466 buf += "char *pointers[4];} _stack;\n";
1467 buf += "id volatile _rethrow = 0;\n";
1468 buf += "objc_exception_try_enter(&_stack);\n";
1469 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001470 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001471 startLoc = S->getSynchBody()->getLocEnd();
1472 startBuf = SM->getCharacterData(startLoc);
1473
Steve Naroffc7089f12008-08-19 13:04:19 +00001474 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001475 SourceLocation lastCurlyLoc = startLoc;
1476 buf = "}\nelse {\n";
1477 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1478 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001479 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001480 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001481 S->getSynchExpr(),
1482 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001483 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001484 std::string syncExprBufS;
1485 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001486 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001487 buf += syncExprBuf.str();
1488 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001489 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1490 buf += "}\n";
1491 buf += "}";
1492
Chris Lattneraadaf782008-01-31 19:51:04 +00001493 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001494 return 0;
1495}
1496
Steve Naroff8c565152008-12-05 17:03:39 +00001497void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1498 // Perform a bottom up traversal of all children.
1499 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1500 CI != E; ++CI)
1501 if (*CI)
1502 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1503
1504 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1505 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1506 Diags.Report(Context->getFullLoc(S->getLocStart()),
1507 TryFinallyContainsReturnDiag);
1508 }
1509 return;
1510}
1511
Steve Naroffb29b4272008-04-14 22:03:09 +00001512Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001513 // Get the start location and compute the semi location.
1514 SourceLocation startLoc = S->getLocStart();
1515 const char *startBuf = SM->getCharacterData(startLoc);
1516
1517 assert((*startBuf == '@') && "bogus @try location");
1518
1519 std::string buf;
1520 // declare a new scope with two variables, _stack and _rethrow.
1521 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1522 buf += "int buf[18/*32-bit i386*/];\n";
1523 buf += "char *pointers[4];} _stack;\n";
1524 buf += "id volatile _rethrow = 0;\n";
1525 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001526 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001527
Chris Lattneraadaf782008-01-31 19:51:04 +00001528 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001529
1530 startLoc = S->getTryBody()->getLocEnd();
1531 startBuf = SM->getCharacterData(startLoc);
1532
1533 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001534
Steve Naroff75730982007-11-07 04:08:17 +00001535 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001536 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1537 if (catchList) {
1538 startLoc = startLoc.getFileLocWithOffset(1);
1539 buf = " /* @catch begin */ else {\n";
1540 buf += " id _caught = objc_exception_extract(&_stack);\n";
1541 buf += " objc_exception_try_enter (&_stack);\n";
1542 buf += " if (_setjmp(_stack.buf))\n";
1543 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1544 buf += " else { /* @catch continue */";
1545
1546 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001547 } else { /* no catch list */
1548 buf = "}\nelse {\n";
1549 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1550 buf += "}";
1551 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001552 }
Steve Naroff75730982007-11-07 04:08:17 +00001553 bool sawIdTypedCatch = false;
1554 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001555 while (catchList) {
1556 Stmt *catchStmt = catchList->getCatchParamStmt();
1557
1558 if (catchList == S->getCatchStmts())
1559 buf = "if ("; // we are generating code for the first catch clause
1560 else
1561 buf = "else if (";
1562 startLoc = catchList->getLocStart();
1563 startBuf = SM->getCharacterData(startLoc);
1564
1565 assert((*startBuf == '@') && "bogus @catch location");
1566
1567 const char *lParenLoc = strchr(startBuf, '(');
1568
Steve Naroffbe4b3332008-02-01 22:08:12 +00001569 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001570 // Now rewrite the body...
1571 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001572 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1573 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001574 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1575 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001576 assert((*bodyBuf == '{') && "bogus @catch body location");
1577
1578 buf += "1) { id _tmp = _caught;";
1579 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1580 buf.c_str(), buf.size());
1581 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001582 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001584 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001585 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001586 sawIdTypedCatch = true;
1587 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001588 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001589
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001590 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001591 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001592 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001593 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001594 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001595 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001596 }
1597 }
1598 // Now rewrite the body...
1599 lastCatchBody = catchList->getCatchBody();
1600 SourceLocation rParenLoc = catchList->getRParenLoc();
1601 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1602 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1603 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1604 assert((*rParenBuf == ')') && "bogus @catch paren location");
1605 assert((*bodyBuf == '{') && "bogus @catch body location");
1606
1607 buf = " = _caught;";
1608 // Here we replace ") {" with "= _caught;" (which initializes and
1609 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001610 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001611 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001612 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001613 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001614 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001615 catchList = catchList->getNextCatchStmt();
1616 }
1617 // Complete the catch list...
1618 if (lastCatchBody) {
1619 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001620 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1621 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001622
Steve Naroff378f47a2008-09-11 15:29:03 +00001623 // Insert the last (implicit) else clause *before* the right curly brace.
1624 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1625 buf = "} /* last catch end */\n";
1626 buf += "else {\n";
1627 buf += " _rethrow = _caught;\n";
1628 buf += " objc_exception_try_exit(&_stack);\n";
1629 buf += "} } /* @catch end */\n";
1630 if (!S->getFinallyStmt())
1631 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001632 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001633
1634 // Set lastCurlyLoc
1635 lastCurlyLoc = lastCatchBody->getLocEnd();
1636 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001637 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001638 startLoc = finalStmt->getLocStart();
1639 startBuf = SM->getCharacterData(startLoc);
1640 assert((*startBuf == '@') && "bogus @finally start");
1641
1642 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001643 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001644
1645 Stmt *body = finalStmt->getFinallyBody();
1646 SourceLocation startLoc = body->getLocStart();
1647 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001648 assert(*SM->getCharacterData(startLoc) == '{' &&
1649 "bogus @finally body location");
1650 assert(*SM->getCharacterData(endLoc) == '}' &&
1651 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001652
1653 startLoc = startLoc.getFileLocWithOffset(1);
1654 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001655 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001656 endLoc = endLoc.getFileLocWithOffset(-1);
1657 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001658 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001659
1660 // Set lastCurlyLoc
1661 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001662
1663 // Now check for any return/continue/go statements within the @try.
1664 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001665 } else { /* no finally clause - make sure we synthesize an implicit one */
1666 buf = "{ /* implicit finally clause */\n";
1667 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1668 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1669 buf += "}";
1670 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001671 }
1672 // Now emit the final closing curly brace...
1673 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1674 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001675 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001676 return 0;
1677}
1678
Steve Naroffb29b4272008-04-14 22:03:09 +00001679Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001680 return 0;
1681}
1682
Steve Naroffb29b4272008-04-14 22:03:09 +00001683Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001684 return 0;
1685}
1686
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001687// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001688// the throw expression is typically a message expression that's already
1689// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001690Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001691 // Get the start location and compute the semi location.
1692 SourceLocation startLoc = S->getLocStart();
1693 const char *startBuf = SM->getCharacterData(startLoc);
1694
1695 assert((*startBuf == '@') && "bogus @throw location");
1696
1697 std::string buf;
1698 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001699 if (S->getThrowExpr())
1700 buf = "objc_exception_throw(";
1701 else // add an implicit argument
1702 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001703
1704 // handle "@ throw" correctly.
1705 const char *wBuf = strchr(startBuf, 'w');
1706 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1707 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1708
Steve Naroff2bd03922007-11-07 15:32:26 +00001709 const char *semiBuf = strchr(startBuf, ';');
1710 assert((*semiBuf == ';') && "@throw: can't find ';'");
1711 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1712 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001713 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001714 return 0;
1715}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001716
Steve Naroffb29b4272008-04-14 22:03:09 +00001717Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001718 // Create a new string expression.
1719 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001720 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001721 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001722 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1723 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001724 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001725 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001726
Chris Lattner07506182007-11-30 22:53:43 +00001727 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001728 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001729 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001730}
1731
Steve Naroffb29b4272008-04-14 22:03:09 +00001732Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001733 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1734 // Create a call to sel_registerName("selName").
1735 llvm::SmallVector<Expr*, 8> SelExprs;
1736 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001737 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1738 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001739 false, argType, SourceLocation(),
1740 SourceLocation()));
1741 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1742 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001743 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001744 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001745 return SelExp;
1746}
1747
Steve Naroffb29b4272008-04-14 22:03:09 +00001748CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001749 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001750 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001751 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001752
1753 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001754 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001755
1756 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001757 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001758 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1759 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001760
1761 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001762
Steve Naroff934f2762007-10-24 22:48:43 +00001763 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1764}
1765
Steve Naroffd5255f52007-11-01 13:24:47 +00001766static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1767 const char *&startRef, const char *&endRef) {
1768 while (startBuf < endBuf) {
1769 if (*startBuf == '<')
1770 startRef = startBuf; // mark the start.
1771 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001772 if (startRef && *startRef == '<') {
1773 endRef = startBuf; // mark the end.
1774 return true;
1775 }
1776 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001777 }
1778 startBuf++;
1779 }
1780 return false;
1781}
1782
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001783static void scanToNextArgument(const char *&argRef) {
1784 int angle = 0;
1785 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1786 if (*argRef == '<')
1787 angle++;
1788 else if (*argRef == '>')
1789 angle--;
1790 argRef++;
1791 }
1792 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1793}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001794
Steve Naroffb29b4272008-04-14 22:03:09 +00001795bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001796
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001797 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001798 return true;
1799
Steve Naroffd5255f52007-11-01 13:24:47 +00001800 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001801 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001802 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001803 return true; // we have "Class <Protocol> *".
1804 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001805 return false;
1806}
1807
Steve Naroff4f95b752008-07-29 18:15:38 +00001808void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1809 QualType Type = E->getType();
1810 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001811 SourceLocation Loc, EndLoc;
1812
1813 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1814 Loc = ECE->getLParenLoc();
1815 EndLoc = ECE->getRParenLoc();
1816 } else {
1817 Loc = E->getLocStart();
1818 EndLoc = E->getLocEnd();
1819 }
1820 // This will defend against trying to rewrite synthesized expressions.
1821 if (Loc.isInvalid() || EndLoc.isInvalid())
1822 return;
1823
Steve Naroff4f95b752008-07-29 18:15:38 +00001824 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001825 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001826 const char *startRef = 0, *endRef = 0;
1827 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1828 // Get the locations of the startRef, endRef.
1829 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1830 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1831 // Comment out the protocol references.
1832 InsertText(LessLoc, "/*", 2);
1833 InsertText(GreaterLoc, "*/", 2);
1834 }
1835 }
1836}
1837
Steve Naroffb29b4272008-04-14 22:03:09 +00001838void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001839 SourceLocation Loc;
1840 QualType Type;
1841 const FunctionTypeProto *proto = 0;
1842 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1843 Loc = VD->getLocation();
1844 Type = VD->getType();
1845 }
1846 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1847 Loc = FD->getLocation();
1848 // Check for ObjC 'id' and class types that have been adorned with protocol
1849 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1850 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1851 assert(funcType && "missing function type");
1852 proto = dyn_cast<FunctionTypeProto>(funcType);
1853 if (!proto)
1854 return;
1855 Type = proto->getResultType();
1856 }
1857 else
1858 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001859
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001860 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001861 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001862
1863 const char *endBuf = SM->getCharacterData(Loc);
1864 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001865 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001866 startBuf--; // scan backward (from the decl location) for return type.
1867 const char *startRef = 0, *endRef = 0;
1868 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1869 // Get the locations of the startRef, endRef.
1870 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1871 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1872 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001873 InsertText(LessLoc, "/*", 2);
1874 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001875 }
1876 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001877 if (!proto)
1878 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001879 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001880 const char *startBuf = SM->getCharacterData(Loc);
1881 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001882 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1883 if (needToScanForQualifiers(proto->getArgType(i))) {
1884 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001885
Steve Naroffd5255f52007-11-01 13:24:47 +00001886 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001887 // scan forward (from the decl location) for argument types.
1888 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001889 const char *startRef = 0, *endRef = 0;
1890 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1891 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001892 SourceLocation LessLoc =
1893 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1894 SourceLocation GreaterLoc =
1895 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001896 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001897 InsertText(LessLoc, "/*", 2);
1898 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001899 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001900 startBuf = ++endBuf;
1901 }
1902 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001903 // If the function name is derived from a macro expansion, then the
1904 // argument buffer will not follow the name. Need to speak with Chris.
1905 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001906 startBuf++; // scan forward (from the decl location) for argument types.
1907 startBuf++;
1908 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001909 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001910}
1911
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001912// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001913void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001914 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1915 llvm::SmallVector<QualType, 16> ArgTys;
1916 ArgTys.push_back(Context->getPointerType(
1917 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001918 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001919 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001920 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001921 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001922 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001923 SelGetUidIdent, getFuncType,
1924 FunctionDecl::Extern, false, 0);
1925}
1926
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001927// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001928void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001929 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1930 llvm::SmallVector<QualType, 16> ArgTys;
1931 ArgTys.push_back(Context->getPointerType(
1932 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001934 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001935 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001936 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001937 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001938 SelGetProtoIdent, getFuncType,
1939 FunctionDecl::Extern, false, 0);
1940}
1941
Steve Naroffb29b4272008-04-14 22:03:09 +00001942void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001943 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001944 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001945 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001946 return;
1947 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001949}
1950
Steve Naroffc0a123c2008-03-11 17:37:02 +00001951// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001952void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001953 if (SuperContructorFunctionDecl)
1954 return;
1955 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1956 llvm::SmallVector<QualType, 16> ArgTys;
1957 QualType argT = Context->getObjCIdType();
1958 assert(!argT.isNull() && "Can't find 'id' type");
1959 ArgTys.push_back(argT);
1960 ArgTys.push_back(argT);
1961 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1962 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001963 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001964 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001965 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001966 msgSendIdent, msgSendType,
1967 FunctionDecl::Extern, false, 0);
1968}
1969
Steve Naroff09b266e2007-10-30 23:14:51 +00001970// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001971void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001972 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1973 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001974 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001975 assert(!argT.isNull() && "Can't find 'id' type");
1976 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001977 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001978 assert(!argT.isNull() && "Can't find 'SEL' type");
1979 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001981 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001982 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001983 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001984 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001985 msgSendIdent, msgSendType,
1986 FunctionDecl::Extern, false, 0);
1987}
1988
Steve Naroff874e2322007-11-15 10:28:18 +00001989// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001993 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001994 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001995 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001996 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1997 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1998 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002000 assert(!argT.isNull() && "Can't find 'SEL' type");
2001 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002003 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002004 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002005 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002006 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002007 msgSendIdent, msgSendType,
2008 FunctionDecl::Extern, false, 0);
2009}
2010
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002011// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002012void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002013 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2014 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002016 assert(!argT.isNull() && "Can't find 'id' type");
2017 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002022 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002024 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002025 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002026 msgSendIdent, msgSendType,
2027 FunctionDecl::Extern, false, 0);
2028}
2029
2030// SynthMsgSendSuperStretFunctionDecl -
2031// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002032void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002033 IdentifierInfo *msgSendIdent =
2034 &Context->Idents.get("objc_msgSendSuper_stret");
2035 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002036 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002037 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002038 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002039 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2040 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2041 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002042 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002043 assert(!argT.isNull() && "Can't find 'SEL' type");
2044 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002047 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002048 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002049 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 msgSendIdent, msgSendType,
2051 FunctionDecl::Extern, false, 0);
2052}
2053
Steve Naroff1284db82008-05-08 22:02:18 +00002054// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002055void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002056 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2057 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002059 assert(!argT.isNull() && "Can't find 'id' type");
2060 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002064 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002065 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002067 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002068 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002069 msgSendIdent, msgSendType,
2070 FunctionDecl::Extern, false, 0);
2071}
2072
Steve Naroff09b266e2007-10-30 23:14:51 +00002073// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002074void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002075 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2076 llvm::SmallVector<QualType, 16> ArgTys;
2077 ArgTys.push_back(Context->getPointerType(
2078 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002080 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002081 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002082 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002083 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002084 getClassIdent, getClassType,
2085 FunctionDecl::Extern, false, 0);
2086}
2087
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002088// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002089void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002090 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2091 llvm::SmallVector<QualType, 16> ArgTys;
2092 ArgTys.push_back(Context->getPointerType(
2093 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002095 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002096 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002097 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002098 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002099 getClassIdent, getClassType,
2100 FunctionDecl::Extern, false, 0);
2101}
2102
Steve Naroffb29b4272008-04-14 22:03:09 +00002103Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002104 QualType strType = getConstantStringStructType();
2105
2106 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002107
2108 std::string tmpName = InFileName;
2109 unsigned i;
2110 for (i=0; i < tmpName.length(); i++) {
2111 char c = tmpName.at(i);
2112 // replace any non alphanumeric characters with '_'.
2113 if (!isalpha(c) && (c < '0' || c > '9'))
2114 tmpName[i] = '_';
2115 }
2116 S += tmpName;
2117 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002118 S += utostr(NumObjCStringLiterals++);
2119
Steve Naroffba92b2e2008-03-27 22:29:16 +00002120 Preamble += "static __NSConstantStringImpl " + S;
2121 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2122 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002123 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002124 std::string prettyBufS;
2125 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002126 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002127 Preamble += prettyBuf.str();
2128 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002129 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002130 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002131
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002132 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002133 &Context->Idents.get(S.c_str()), strType,
2134 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002135 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2136 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2137 Context->getPointerType(DRE->getType()),
2138 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002139 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002140 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002141 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002142 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002143 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002144 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002145}
2146
Steve Naroffb29b4272008-04-14 22:03:09 +00002147ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002148 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002149 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002150
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002151 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2152 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002153 assert(PT);
2154 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2155 return IT->getDecl();
2156 }
2157 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002158}
2159
2160// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002161QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002162 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002163 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002164 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002165 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002166 QualType FieldTypes[2];
2167
2168 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002170 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002172 // Create fields
2173 FieldDecl *FieldDecls[2];
2174
2175 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002176 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002177 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002178
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002179 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002180 }
2181 return Context->getTagDeclType(SuperStructDecl);
2182}
2183
Steve Naroffb29b4272008-04-14 22:03:09 +00002184QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002185 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002186 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002187 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002188 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002189 QualType FieldTypes[4];
2190
2191 // struct objc_object *receiver;
2192 FieldTypes[0] = Context->getObjCIdType();
2193 // int flags;
2194 FieldTypes[1] = Context->IntTy;
2195 // char *str;
2196 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2197 // long length;
2198 FieldTypes[3] = Context->LongTy;
2199 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002200 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002201
2202 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002203 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002204 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002205
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002206 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002207 }
2208 return Context->getTagDeclType(ConstantStringDecl);
2209}
2210
Steve Naroffb29b4272008-04-14 22:03:09 +00002211Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002212 if (!SelGetUidFunctionDecl)
2213 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002214 if (!MsgSendFunctionDecl)
2215 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002216 if (!MsgSendSuperFunctionDecl)
2217 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002218 if (!MsgSendStretFunctionDecl)
2219 SynthMsgSendStretFunctionDecl();
2220 if (!MsgSendSuperStretFunctionDecl)
2221 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002222 if (!MsgSendFpretFunctionDecl)
2223 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002224 if (!GetClassFunctionDecl)
2225 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002226 if (!GetMetaClassFunctionDecl)
2227 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002228
Steve Naroff874e2322007-11-15 10:28:18 +00002229 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002230 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2231 // May need to use objc_msgSend_stret() as well.
2232 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002234 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002235 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002236 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002237 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002238 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002239 }
Steve Naroff874e2322007-11-15 10:28:18 +00002240
Steve Naroff934f2762007-10-24 22:48:43 +00002241 // Synthesize a call to objc_msgSend().
2242 llvm::SmallVector<Expr*, 8> MsgExprs;
2243 IdentifierInfo *clsName = Exp->getClassName();
2244
2245 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2246 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002247 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2248 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002249 if (!strcmp(clsName->getName(), "super")) {
2250 MsgSendFlavor = MsgSendSuperFunctionDecl;
2251 if (MsgSendStretFlavor)
2252 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2253 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2254
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002255 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002256 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002257
2258 llvm::SmallVector<Expr*, 4> InitExprs;
2259
2260 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002261 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002262 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002263 Context->getObjCIdType(),
2264 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002265 llvm::SmallVector<Expr*, 8> ClsExprs;
2266 QualType argType = Context->getPointerType(Context->CharTy);
2267 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2268 SuperDecl->getIdentifier()->getLength(),
2269 false, argType, SourceLocation(),
2270 SourceLocation()));
2271 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2272 &ClsExprs[0],
2273 ClsExprs.size());
2274 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002275 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002276 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002277 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002278 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002279 // struct objc_super
2280 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002281 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002282
Steve Naroff23f41272008-03-11 18:14:26 +00002283 if (LangOpts.Microsoft) {
2284 SynthSuperContructorFunctionDecl();
2285 // Simulate a contructor call...
2286 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2287 superType, SourceLocation());
2288 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2289 superType, SourceLocation());
2290 } else {
2291 // (struct objc_super) { <exprs from above> }
2292 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2293 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002294 SourceLocation(), false);
2295 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2296 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002297 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002298 // struct objc_super *
2299 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2300 Context->getPointerType(SuperRep->getType()),
2301 SourceLocation());
2302 MsgExprs.push_back(Unop);
2303 } else {
2304 llvm::SmallVector<Expr*, 8> ClsExprs;
2305 QualType argType = Context->getPointerType(Context->CharTy);
2306 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2307 clsName->getLength(),
2308 false, argType, SourceLocation(),
2309 SourceLocation()));
2310 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2311 &ClsExprs[0],
2312 ClsExprs.size());
2313 MsgExprs.push_back(Cls);
2314 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002315 } else { // instance message.
2316 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002317
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002318 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002319 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002320 if (MsgSendStretFlavor)
2321 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002322 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2323
2324 llvm::SmallVector<Expr*, 4> InitExprs;
2325
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002326 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002327 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002328 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002329 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002330 SourceLocation()),
2331 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002332 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002333
2334 llvm::SmallVector<Expr*, 8> ClsExprs;
2335 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002336 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2337 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002338 false, argType, SourceLocation(),
2339 SourceLocation()));
2340 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002341 &ClsExprs[0],
2342 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002343 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002344 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002345 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002346 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002347 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002348 // struct objc_super
2349 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002350 Expr *SuperRep;
2351
2352 if (LangOpts.Microsoft) {
2353 SynthSuperContructorFunctionDecl();
2354 // Simulate a contructor call...
2355 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2356 superType, SourceLocation());
2357 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2358 superType, SourceLocation());
2359 } else {
2360 // (struct objc_super) { <exprs from above> }
2361 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2362 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002363 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002364 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2365 }
Steve Naroff874e2322007-11-15 10:28:18 +00002366 // struct objc_super *
2367 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2368 Context->getPointerType(SuperRep->getType()),
2369 SourceLocation());
2370 MsgExprs.push_back(Unop);
2371 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002372 // Remove all type-casts because it may contain objc-style types; e.g.
2373 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002374 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002375 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002376 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002377 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002378 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002379 MsgExprs.push_back(recExpr);
2380 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002381 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002382 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002383 llvm::SmallVector<Expr*, 8> SelExprs;
2384 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002385 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2386 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002387 false, argType, SourceLocation(),
2388 SourceLocation()));
2389 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2390 &SelExprs[0], SelExprs.size());
2391 MsgExprs.push_back(SelExp);
2392
2393 // Now push any user supplied arguments.
2394 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002395 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002396 // Make all implicit casts explicit...ICE comes in handy:-)
2397 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2398 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002399 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002401 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002402 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002403 }
2404 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002405 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002407 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002408 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002409 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002410 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002411 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002412 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002413 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002414 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002415 // We've transferred the ownership to MsgExprs. Null out the argument in
2416 // the original expression, since we will delete it below.
2417 Exp->setArg(i, 0);
2418 }
Steve Naroffab972d32007-11-04 22:37:50 +00002419 // Generate the funky cast.
2420 CastExpr *cast;
2421 llvm::SmallVector<QualType, 8> ArgTypes;
2422 QualType returnType;
2423
2424 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002425 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2426 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2427 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 ArgTypes.push_back(Context->getObjCIdType());
2429 ArgTypes.push_back(Context->getObjCSelType());
2430 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002431 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002432 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2434 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002435 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002436 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2437 if (isBlockPointerType(t)) {
2438 const BlockPointerType *BPT = t->getAsBlockPointerType();
2439 t = Context->getPointerType(BPT->getPointeeType());
2440 }
Steve Naroff352336b2007-11-05 14:36:37 +00002441 ArgTypes.push_back(t);
2442 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2444 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002445 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002446 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002447 }
2448 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002449 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002450
2451 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002452 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2453 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002454
2455 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2456 // If we don't do this cast, we get the following bizarre warning/note:
2457 // xx.m:13: warning: function called through a non-compatible type
2458 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002459 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002460 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002461 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002462
Steve Naroffab972d32007-11-04 22:37:50 +00002463 // Now do the "normal" pointer to function cast.
2464 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002465 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002466 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002467 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002468 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002469 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002470
2471 // Don't forget the parens to enforce the proper binding.
2472 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2473
2474 const FunctionType *FT = msgSendType->getAsFunctionType();
2475 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2476 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002477 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002478 if (MsgSendStretFlavor) {
2479 // We have the method which returns a struct/union. Must also generate
2480 // call to objc_msgSend_stret and hang both varieties on a conditional
2481 // expression which dictate which one to envoke depending on size of
2482 // method's return type.
2483
2484 // Create a reference to the objc_msgSend_stret() declaration.
2485 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2486 SourceLocation());
2487 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002488 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002489 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002490 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002491 // Now do the "normal" pointer to function cast.
2492 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002493 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002494 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002495 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002496 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002497
2498 // Don't forget the parens to enforce the proper binding.
2499 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2500
2501 FT = msgSendType->getAsFunctionType();
2502 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2503 FT->getResultType(), SourceLocation());
2504
2505 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002506 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2507 returnType.getAsOpaquePtr(),
2508 Context->getSizeType(),
2509 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2511 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2512 // For X86 it is more complicated and some kind of target specific routine
2513 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002514 unsigned IntSize =
2515 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2517 Context->IntTy,
2518 SourceLocation());
2519 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2520 BinaryOperator::LE,
2521 Context->IntTy,
2522 SourceLocation());
2523 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2524 ConditionalOperator *CondExpr =
2525 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002526 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002527 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002528 return ReplacingStmt;
2529}
2530
Steve Naroffb29b4272008-04-14 22:03:09 +00002531Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002532 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002533
Steve Naroffc77a6362008-12-04 16:24:46 +00002534 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002535 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002536 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002537
Steve Naroff4c3580e2008-12-04 23:50:32 +00002538 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002539 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002540}
2541
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002542/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2543/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002544Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002545 if (!GetProtocolFunctionDecl)
2546 SynthGetProtocolFunctionDecl();
2547 // Create a call to objc_getProtocol("ProtocolName").
2548 llvm::SmallVector<Expr*, 8> ProtoExprs;
2549 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002550 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2551 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002552 false, argType, SourceLocation(),
2553 SourceLocation()));
2554 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2555 &ProtoExprs[0],
2556 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002557 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002558 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002559 return ProtoExp;
2560
2561}
2562
Steve Naroffbaf58c32008-05-31 14:15:04 +00002563bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2564 const char *endBuf) {
2565 while (startBuf < endBuf) {
2566 if (*startBuf == '#') {
2567 // Skip whitespace.
2568 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2569 ;
2570 if (!strncmp(startBuf, "if", strlen("if")) ||
2571 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2572 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2573 !strncmp(startBuf, "define", strlen("define")) ||
2574 !strncmp(startBuf, "undef", strlen("undef")) ||
2575 !strncmp(startBuf, "else", strlen("else")) ||
2576 !strncmp(startBuf, "elif", strlen("elif")) ||
2577 !strncmp(startBuf, "endif", strlen("endif")) ||
2578 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2579 !strncmp(startBuf, "include", strlen("include")) ||
2580 !strncmp(startBuf, "import", strlen("import")) ||
2581 !strncmp(startBuf, "include_next", strlen("include_next")))
2582 return true;
2583 }
2584 startBuf++;
2585 }
2586 return false;
2587}
2588
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002589/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002590/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002591void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002592 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002593 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002594 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002595 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002596 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002597 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002598 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002599 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002600 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002601 SourceLocation LocStart = CDecl->getLocStart();
2602 SourceLocation LocEnd = CDecl->getLocEnd();
2603
2604 const char *startBuf = SM->getCharacterData(LocStart);
2605 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002606
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002607 // If no ivars and no root or if its root, directly or indirectly,
2608 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002609 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2610 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002611 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002612 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002613 return;
2614 }
2615
2616 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002617 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002618 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002619 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002620 if (LangOpts.Microsoft)
2621 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002622
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002623 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002624 const char *cursor = strchr(startBuf, '{');
2625 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002627 // If the buffer contains preprocessor directives, we do more fine-grained
2628 // rewrites. This is intended to fix code that looks like (which occurs in
2629 // NSURL.h, for example):
2630 //
2631 // #ifdef XYZ
2632 // @interface Foo : NSObject
2633 // #else
2634 // @interface FooBar : NSObject
2635 // #endif
2636 // {
2637 // int i;
2638 // }
2639 // @end
2640 //
2641 // This clause is segregated to avoid breaking the common case.
2642 if (BufferContainsPPDirectives(startBuf, cursor)) {
2643 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2644 CDecl->getClassLoc();
2645 const char *endHeader = SM->getCharacterData(L);
2646 endHeader += Lexer::MeasureTokenLength(L, *SM);
2647
Chris Lattner3db6cae2008-07-21 18:19:38 +00002648 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002649 // advance to the end of the referenced protocols.
2650 while (endHeader < cursor && *endHeader != '>') endHeader++;
2651 endHeader++;
2652 }
2653 // rewrite the original header
2654 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2655 } else {
2656 // rewrite the original header *without* disturbing the '{'
2657 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2658 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002659 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002660 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002661 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002662 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002663 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002664 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002665
2666 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002667 SourceLocation OnePastCurly =
2668 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2669 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002670 }
2671 cursor++; // past '{'
2672
2673 // Now comment out any visibility specifiers.
2674 while (cursor < endBuf) {
2675 if (*cursor == '@') {
2676 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002677 // Skip whitespace.
2678 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2679 /*scan*/;
2680
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002681 // FIXME: presence of @public, etc. inside comment results in
2682 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002683 if (!strncmp(cursor, "public", strlen("public")) ||
2684 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002685 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002686 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002687 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002688 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002689 // FIXME: If there are cases where '<' is used in ivar declaration part
2690 // of user code, then scan the ivar list and use needToScanForQualifiers
2691 // for type checking.
2692 else if (*cursor == '<') {
2693 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002694 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002695 cursor = strchr(cursor, '>');
2696 cursor++;
2697 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002698 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002699 } else if (*cursor == '^') { // rewrite block specifier.
2700 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2701 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002702 }
Steve Narofffea763e82007-11-14 19:25:57 +00002703 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002704 }
Steve Narofffea763e82007-11-14 19:25:57 +00002705 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002706 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002707 } else { // we don't have any instance variables - insert super struct.
2708 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2709 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002710 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002711 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002712 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002713 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002714 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002715 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002716 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002717 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002718 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002719}
2720
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002721// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002722/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002723void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002724 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002725 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002726 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002727 const char *ClassName,
2728 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002729 if (MethodBegin == MethodEnd) return;
2730
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002731 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002732 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002733 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002734 SEL _cmd;
2735 char *method_types;
2736 void *_imp;
2737 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002738 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002739 Result += "\nstruct _objc_method {\n";
2740 Result += "\tSEL _cmd;\n";
2741 Result += "\tchar *method_types;\n";
2742 Result += "\tvoid *_imp;\n";
2743 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002744
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002745 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002746 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002747
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002748 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002749
2750 /* struct {
2751 struct _objc_method_list *next_method;
2752 int method_count;
2753 struct _objc_method method_list[];
2754 }
2755 */
2756 Result += "\nstatic struct {\n";
2757 Result += "\tstruct _objc_method_list *next_method;\n";
2758 Result += "\tint method_count;\n";
2759 Result += "\tstruct _objc_method method_list[";
2760 Result += utostr(MethodEnd-MethodBegin);
2761 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002762 Result += prefix;
2763 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2764 Result += "_METHODS_";
2765 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002766 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002767 Result += IsInstanceMethod ? "inst" : "cls";
2768 Result += "_meth\")))= ";
2769 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002770
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002771 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002772 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002773 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002774 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002775 Result += "\", \"";
2776 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002777 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002778 Result += MethodInternalNames[*MethodBegin];
2779 Result += "}\n";
2780 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2781 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002782 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002783 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002784 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002785 Result += "\", \"";
2786 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002787 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002788 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002789 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002790 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002791 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792}
2793
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002794/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002795void RewriteObjC::
2796RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2797 const char *prefix,
2798 const char *ClassName,
2799 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002800 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002801 if (Protocols.empty()) return;
2802
2803 for (unsigned i = 0; i != Protocols.size(); i++) {
2804 ObjCProtocolDecl *PDecl = Protocols[i];
2805 // Output struct protocol_methods holder of method selector and type.
2806 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2807 /* struct protocol_methods {
2808 SEL _cmd;
2809 char *method_types;
2810 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002811 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002812 Result += "\nstruct protocol_methods {\n";
2813 Result += "\tSEL _cmd;\n";
2814 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002815 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002816
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002817 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002818 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002819 // Do not synthesize the protocol more than once.
2820 if (ObjCSynthesizedProtocols.count(PDecl))
2821 continue;
2822
2823 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2824 unsigned NumMethods = PDecl->getNumInstanceMethods();
2825 /* struct _objc_protocol_method_list {
2826 int protocol_method_count;
2827 struct protocol_methods protocols[];
2828 }
2829 */
2830 Result += "\nstatic struct {\n";
2831 Result += "\tint protocol_method_count;\n";
2832 Result += "\tstruct protocol_methods protocols[";
2833 Result += utostr(NumMethods);
2834 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002835 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002836 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2837 "{\n\t" + utostr(NumMethods) + "\n";
2838
2839 // Output instance methods declared in this protocol.
2840 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2841 E = PDecl->instmeth_end(); I != E; ++I) {
2842 if (I == PDecl->instmeth_begin())
2843 Result += "\t ,{{(SEL)\"";
2844 else
2845 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002846 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002847 std::string MethodTypeString;
2848 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2849 Result += "\", \"";
2850 Result += MethodTypeString;
2851 Result += "\"}\n";
2852 }
2853 Result += "\t }\n};\n";
2854 }
2855
2856 // Output class methods declared in this protocol.
2857 int NumMethods = PDecl->getNumClassMethods();
2858 if (NumMethods > 0) {
2859 /* struct _objc_protocol_method_list {
2860 int protocol_method_count;
2861 struct protocol_methods protocols[];
2862 }
2863 */
2864 Result += "\nstatic struct {\n";
2865 Result += "\tint protocol_method_count;\n";
2866 Result += "\tstruct protocol_methods protocols[";
2867 Result += utostr(NumMethods);
2868 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002869 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002870 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2871 "{\n\t";
2872 Result += utostr(NumMethods);
2873 Result += "\n";
2874
2875 // Output instance methods declared in this protocol.
2876 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2877 E = PDecl->classmeth_end(); I != E; ++I) {
2878 if (I == PDecl->classmeth_begin())
2879 Result += "\t ,{{(SEL)\"";
2880 else
2881 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002882 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002883 std::string MethodTypeString;
2884 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2885 Result += "\", \"";
2886 Result += MethodTypeString;
2887 Result += "\"}\n";
2888 }
2889 Result += "\t }\n};\n";
2890 }
2891
2892 // Output:
2893 /* struct _objc_protocol {
2894 // Objective-C 1.0 extensions
2895 struct _objc_protocol_extension *isa;
2896 char *protocol_name;
2897 struct _objc_protocol **protocol_list;
2898 struct _objc_protocol_method_list *instance_methods;
2899 struct _objc_protocol_method_list *class_methods;
2900 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002901 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002902 static bool objc_protocol = false;
2903 if (!objc_protocol) {
2904 Result += "\nstruct _objc_protocol {\n";
2905 Result += "\tstruct _objc_protocol_extension *isa;\n";
2906 Result += "\tchar *protocol_name;\n";
2907 Result += "\tstruct _objc_protocol **protocol_list;\n";
2908 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2909 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2910 Result += "};\n";
2911
2912 objc_protocol = true;
2913 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002914
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002915 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002916 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002917 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2918 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002919 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002920 Result += "\", 0, ";
2921 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2922 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002923 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002924 Result += ", ";
2925 }
2926 else
2927 Result += "0, ";
2928 if (PDecl->getNumClassMethods() > 0) {
2929 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002930 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002931 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002932 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002933 else
2934 Result += "0\n";
2935 Result += "};\n";
2936
2937 // Mark this protocol as having been generated.
2938 if (!ObjCSynthesizedProtocols.insert(PDecl))
2939 assert(false && "protocol already synthesized");
2940 }
2941 // Output the top lovel protocol meta-data for the class.
2942 /* struct _objc_protocol_list {
2943 struct _objc_protocol_list *next;
2944 int protocol_count;
2945 struct _objc_protocol *class_protocols[];
2946 }
2947 */
2948 Result += "\nstatic struct {\n";
2949 Result += "\tstruct _objc_protocol_list *next;\n";
2950 Result += "\tint protocol_count;\n";
2951 Result += "\tstruct _objc_protocol *class_protocols[";
2952 Result += utostr(Protocols.size());
2953 Result += "];\n} _OBJC_";
2954 Result += prefix;
2955 Result += "_PROTOCOLS_";
2956 Result += ClassName;
2957 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2958 "{\n\t0, ";
2959 Result += utostr(Protocols.size());
2960 Result += "\n";
2961
2962 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002963 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002964 Result += " \n";
2965
2966 for (unsigned i = 1; i != Protocols.size(); i++) {
2967 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002968 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002969 Result += "\n";
2970 }
2971 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002972}
2973
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002974/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002975/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002976void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002977 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002978 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002979 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002980 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002981 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2982 CDecl = CDecl->getNextClassCategory())
2983 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2984 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002985
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002986 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002987 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002988 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002989
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002990 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002991 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002992 true, "CATEGORY_", FullCategoryName.c_str(),
2993 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994
2995 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002996 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002997 false, "CATEGORY_", FullCategoryName.c_str(),
2998 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002999
3000 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003001 // Null CDecl is case of a category implementation with no category interface
3002 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003003 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003004 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003005
3006 /* struct _objc_category {
3007 char *category_name;
3008 char *class_name;
3009 struct _objc_method_list *instance_methods;
3010 struct _objc_method_list *class_methods;
3011 struct _objc_protocol_list *protocols;
3012 // Objective-C 1.0 extensions
3013 uint32_t size; // sizeof (struct _objc_category)
3014 struct _objc_property_list *instance_properties; // category's own
3015 // @property decl.
3016 };
3017 */
3018
3019 static bool objc_category = false;
3020 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003021 Result += "\nstruct _objc_category {\n";
3022 Result += "\tchar *category_name;\n";
3023 Result += "\tchar *class_name;\n";
3024 Result += "\tstruct _objc_method_list *instance_methods;\n";
3025 Result += "\tstruct _objc_method_list *class_methods;\n";
3026 Result += "\tstruct _objc_protocol_list *protocols;\n";
3027 Result += "\tunsigned int size;\n";
3028 Result += "\tstruct _objc_property_list *instance_properties;\n";
3029 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003030 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003031 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003032 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3033 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003034 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003035 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003036 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003037 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003038 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003039
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003040 if (IDecl->getNumInstanceMethods() > 0) {
3041 Result += "\t, (struct _objc_method_list *)"
3042 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3043 Result += FullCategoryName;
3044 Result += "\n";
3045 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003046 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003047 Result += "\t, 0\n";
3048 if (IDecl->getNumClassMethods() > 0) {
3049 Result += "\t, (struct _objc_method_list *)"
3050 "&_OBJC_CATEGORY_CLASS_METHODS_";
3051 Result += FullCategoryName;
3052 Result += "\n";
3053 }
3054 else
3055 Result += "\t, 0\n";
3056
Chris Lattner780f3292008-07-21 21:32:27 +00003057 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003058 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3059 Result += FullCategoryName;
3060 Result += "\n";
3061 }
3062 else
3063 Result += "\t, 0\n";
3064 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003065}
3066
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003067/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3068/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003069void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003071 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003072 if (ivar->isBitField()) {
3073 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3074 // place all bitfields at offset 0.
3075 Result += "0";
3076 } else {
3077 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003078 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003079 if (LangOpts.Microsoft)
3080 Result += "_IMPL";
3081 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003082 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003083 Result += ")";
3084 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003085}
3086
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003087//===----------------------------------------------------------------------===//
3088// Meta Data Emission
3089//===----------------------------------------------------------------------===//
3090
Steve Naroffb29b4272008-04-14 22:03:09 +00003091void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003092 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003093 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003094
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003095 // Explictly declared @interface's are already synthesized.
3096 if (CDecl->ImplicitInterfaceDecl()) {
3097 // FIXME: Implementation of a class with no @interface (legacy) doese not
3098 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003100 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003101
Chris Lattnerbe6df082007-12-12 07:56:42 +00003102 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003103 unsigned NumIvars = !IDecl->ivar_empty()
3104 ? IDecl->ivar_size()
3105 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003106 if (NumIvars > 0) {
3107 static bool objc_ivar = false;
3108 if (!objc_ivar) {
3109 /* struct _objc_ivar {
3110 char *ivar_name;
3111 char *ivar_type;
3112 int ivar_offset;
3113 };
3114 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003115 Result += "\nstruct _objc_ivar {\n";
3116 Result += "\tchar *ivar_name;\n";
3117 Result += "\tchar *ivar_type;\n";
3118 Result += "\tint ivar_offset;\n";
3119 Result += "};\n";
3120
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003121 objc_ivar = true;
3122 }
3123
Steve Naroff946a6932008-03-11 00:12:29 +00003124 /* struct {
3125 int ivar_count;
3126 struct _objc_ivar ivar_list[nIvars];
3127 };
3128 */
3129 Result += "\nstatic struct {\n";
3130 Result += "\tint ivar_count;\n";
3131 Result += "\tstruct _objc_ivar ivar_list[";
3132 Result += utostr(NumIvars);
3133 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003134 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003135 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003136 "{\n\t";
3137 Result += utostr(NumIvars);
3138 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003139
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003140 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003141 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003142 IVI = IDecl->ivar_begin();
3143 IVE = IDecl->ivar_end();
3144 } else {
3145 IVI = CDecl->ivar_begin();
3146 IVE = CDecl->ivar_end();
3147 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003149 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003150 Result += "\", \"";
3151 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003152 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003153 Result += StrEncoding;
3154 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003155 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003156 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003157 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003158 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003159 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003160 Result += "\", \"";
3161 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003162 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003163 Result += StrEncoding;
3164 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003165 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003166 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003167 }
3168
3169 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003170 }
3171
3172 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003173 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003174 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003175
3176 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003177 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003178 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003179
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003180 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003181 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003182 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003183
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003184
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003185 // Declaration of class/meta-class metadata
3186 /* struct _objc_class {
3187 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003188 const char *super_class_name;
3189 char *name;
3190 long version;
3191 long info;
3192 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003193 struct _objc_ivar_list *ivars;
3194 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003195 struct objc_cache *cache;
3196 struct objc_protocol_list *protocols;
3197 const char *ivar_layout;
3198 struct _objc_class_ext *ext;
3199 };
3200 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003201 static bool objc_class = false;
3202 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003203 Result += "\nstruct _objc_class {\n";
3204 Result += "\tstruct _objc_class *isa;\n";
3205 Result += "\tconst char *super_class_name;\n";
3206 Result += "\tchar *name;\n";
3207 Result += "\tlong version;\n";
3208 Result += "\tlong info;\n";
3209 Result += "\tlong instance_size;\n";
3210 Result += "\tstruct _objc_ivar_list *ivars;\n";
3211 Result += "\tstruct _objc_method_list *methods;\n";
3212 Result += "\tstruct objc_cache *cache;\n";
3213 Result += "\tstruct _objc_protocol_list *protocols;\n";
3214 Result += "\tconst char *ivar_layout;\n";
3215 Result += "\tstruct _objc_class_ext *ext;\n";
3216 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003217 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003218 }
3219
3220 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003221 ObjCInterfaceDecl *RootClass = 0;
3222 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003223 while (SuperClass) {
3224 RootClass = SuperClass;
3225 SuperClass = SuperClass->getSuperClass();
3226 }
3227 SuperClass = CDecl->getSuperClass();
3228
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003229 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003230 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003231 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003232 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003234 Result += "\"";
3235
3236 if (SuperClass) {
3237 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003239 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003240 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003241 Result += "\"";
3242 }
3243 else {
3244 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003245 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003246 Result += "\"";
3247 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003248 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003249 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003250 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003251 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003252 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003253 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003254 Result += "\n";
3255 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003256 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003257 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003258 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003259 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003260 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003261 Result += ",0,0\n";
3262 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003263 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003264 Result += "\t,0,0,0,0\n";
3265 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003266
3267 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003268 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003269 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003270 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003271 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003272 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 if (SuperClass) {
3274 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003275 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003277 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003278 Result += "\"";
3279 }
3280 else {
3281 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += "\"";
3284 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003285 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003286 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003287 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003288 Result += ",0";
3289 else {
3290 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003291 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003292 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003293 if (LangOpts.Microsoft)
3294 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003295 Result += ")";
3296 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003297 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003298 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003299 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += "\n\t";
3301 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003302 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003303 Result += ",0";
3304 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003305 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307 Result += ", 0\n\t";
3308 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003309 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003311 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003312 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003313 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003314 Result += ", 0,0\n";
3315 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003316 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003317 Result += ",0,0,0\n";
3318 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003319}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003320
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003321/// RewriteImplementations - This routine rewrites all method implementations
3322/// and emits meta-data.
3323
Steve Narofface66252008-11-13 20:07:04 +00003324void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003325 int ClsDefCount = ClassImplementation.size();
3326 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003327
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003328 // Rewrite implemented methods
3329 for (int i = 0; i < ClsDefCount; i++)
3330 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003331
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003332 for (int i = 0; i < CatDefCount; i++)
3333 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003334}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003335
Steve Narofface66252008-11-13 20:07:04 +00003336void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3337 int ClsDefCount = ClassImplementation.size();
3338 int CatDefCount = CategoryImplementation.size();
3339
Steve Naroff5df5b762008-05-07 21:23:49 +00003340 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003341 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003342 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003343 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003344 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003345
3346 // For each implemented category, write out all its meta data.
3347 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003348 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003349
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003350 // Write objc_symtab metadata
3351 /*
3352 struct _objc_symtab
3353 {
3354 long sel_ref_cnt;
3355 SEL *refs;
3356 short cls_def_cnt;
3357 short cat_def_cnt;
3358 void *defs[cls_def_cnt + cat_def_cnt];
3359 };
3360 */
3361
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003362 Result += "\nstruct _objc_symtab {\n";
3363 Result += "\tlong sel_ref_cnt;\n";
3364 Result += "\tSEL *refs;\n";
3365 Result += "\tshort cls_def_cnt;\n";
3366 Result += "\tshort cat_def_cnt;\n";
3367 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3368 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003369
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003370 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003371 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003372 Result += "\t0, 0, " + utostr(ClsDefCount)
3373 + ", " + utostr(CatDefCount) + "\n";
3374 for (int i = 0; i < ClsDefCount; i++) {
3375 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003376 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003377 Result += "\n";
3378 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003379
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003380 for (int i = 0; i < CatDefCount; i++) {
3381 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003382 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003383 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003385 Result += "\n";
3386 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003387
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003389
3390 // Write objc_module metadata
3391
3392 /*
3393 struct _objc_module {
3394 long version;
3395 long size;
3396 const char *name;
3397 struct _objc_symtab *symtab;
3398 }
3399 */
3400
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003401 Result += "\nstruct _objc_module {\n";
3402 Result += "\tlong version;\n";
3403 Result += "\tlong size;\n";
3404 Result += "\tconst char *name;\n";
3405 Result += "\tstruct _objc_symtab *symtab;\n";
3406 Result += "};\n\n";
3407 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003408 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003409 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3410 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003411 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003412
3413 if (LangOpts.Microsoft) {
3414 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003415 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003416 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3417 Result += "&_OBJC_MODULES;\n";
3418 Result += "#pragma data_seg(pop)\n\n";
3419 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003420}
Chris Lattner311ff022007-10-16 22:36:42 +00003421
Steve Naroff54055232008-10-27 17:20:55 +00003422std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3423 const char *funcName,
3424 std::string Tag) {
3425 const FunctionType *AFT = CE->getFunctionType();
3426 QualType RT = AFT->getResultType();
3427 std::string StructRef = "struct " + Tag;
3428 std::string S = "static " + RT.getAsString() + " __" +
3429 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003430
Steve Naroff54055232008-10-27 17:20:55 +00003431 BlockDecl *BD = CE->getBlockDecl();
3432
3433 if (isa<FunctionTypeNoProto>(AFT)) {
3434 S += "()";
3435 } else if (BD->param_empty()) {
3436 S += "(" + StructRef + " *__cself)";
3437 } else {
3438 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3439 assert(FT && "SynthesizeBlockFunc: No function proto");
3440 S += '(';
3441 // first add the implicit argument.
3442 S += StructRef + " *__cself, ";
3443 std::string ParamStr;
3444 for (BlockDecl::param_iterator AI = BD->param_begin(),
3445 E = BD->param_end(); AI != E; ++AI) {
3446 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003447 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003448 (*AI)->getType().getAsStringInternal(ParamStr);
3449 S += ParamStr;
3450 }
3451 if (FT->isVariadic()) {
3452 if (!BD->param_empty()) S += ", ";
3453 S += "...";
3454 }
3455 S += ')';
3456 }
3457 S += " {\n";
3458
3459 // Create local declarations to avoid rewriting all closure decl ref exprs.
3460 // First, emit a declaration for all "by ref" decls.
3461 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3462 E = BlockByRefDecls.end(); I != E; ++I) {
3463 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003464 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003465 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003466 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003467 }
3468 // Next, emit a declaration for all "by copy" declarations.
3469 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3470 E = BlockByCopyDecls.end(); I != E; ++I) {
3471 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003472 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003473 // Handle nested closure invocation. For example:
3474 //
3475 // void (^myImportedClosure)(void);
3476 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3477 //
3478 // void (^anotherClosure)(void);
3479 // anotherClosure = ^(void) {
3480 // myImportedClosure(); // import and invoke the closure
3481 // };
3482 //
3483 if (isBlockPointerType((*I)->getType()))
3484 S += "struct __block_impl *";
3485 else
3486 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003487 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003488 }
3489 std::string RewrittenStr = RewrittenBlockExprs[CE];
3490 const char *cstr = RewrittenStr.c_str();
3491 while (*cstr++ != '{') ;
3492 S += cstr;
3493 S += "\n";
3494 return S;
3495}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003496
Steve Naroff54055232008-10-27 17:20:55 +00003497std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3498 const char *funcName,
3499 std::string Tag) {
3500 std::string StructRef = "struct " + Tag;
3501 std::string S = "static void __";
3502
3503 S += funcName;
3504 S += "_block_copy_" + utostr(i);
3505 S += "(" + StructRef;
3506 S += "*dst, " + StructRef;
3507 S += "*src) {";
3508 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3509 E = ImportedBlockDecls.end(); I != E; ++I) {
3510 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003511 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003512 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003513 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003514 S += ");}";
3515 }
3516 S += "\nstatic void __";
3517 S += funcName;
3518 S += "_block_dispose_" + utostr(i);
3519 S += "(" + StructRef;
3520 S += "*src) {";
3521 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3522 E = ImportedBlockDecls.end(); I != E; ++I) {
3523 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003525 S += ");";
3526 }
3527 S += "}\n";
3528 return S;
3529}
3530
3531std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3532 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003533 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003534 std::string Constructor = " " + Tag;
3535
3536 S += " {\n struct __block_impl impl;\n";
3537
3538 if (hasCopyDisposeHelpers)
3539 S += " void *copy;\n void *dispose;\n";
3540
3541 Constructor += "(void *fp";
3542
3543 if (hasCopyDisposeHelpers)
3544 Constructor += ", void *copyHelp, void *disposeHelp";
3545
3546 if (BlockDeclRefs.size()) {
3547 // Output all "by copy" declarations.
3548 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3549 E = BlockByCopyDecls.end(); I != E; ++I) {
3550 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003551 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003552 std::string ArgName = "_" + FieldName;
3553 // Handle nested closure invocation. For example:
3554 //
3555 // void (^myImportedBlock)(void);
3556 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3557 //
3558 // void (^anotherBlock)(void);
3559 // anotherBlock = ^(void) {
3560 // myImportedBlock(); // import and invoke the closure
3561 // };
3562 //
3563 if (isBlockPointerType((*I)->getType())) {
3564 S += "struct __block_impl *";
3565 Constructor += ", void *" + ArgName;
3566 } else {
3567 (*I)->getType().getAsStringInternal(FieldName);
3568 (*I)->getType().getAsStringInternal(ArgName);
3569 Constructor += ", " + ArgName;
3570 }
3571 S += FieldName + ";\n";
3572 }
3573 // Output all "by ref" declarations.
3574 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3575 E = BlockByRefDecls.end(); I != E; ++I) {
3576 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003578 std::string ArgName = "_" + FieldName;
3579 // Handle nested closure invocation. For example:
3580 //
3581 // void (^myImportedBlock)(void);
3582 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3583 //
3584 // void (^anotherBlock)(void);
3585 // anotherBlock = ^(void) {
3586 // myImportedBlock(); // import and invoke the closure
3587 // };
3588 //
3589 if (isBlockPointerType((*I)->getType())) {
3590 S += "struct __block_impl *";
3591 Constructor += ", void *" + ArgName;
3592 } else {
3593 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3594 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3595 Constructor += ", " + ArgName;
3596 }
3597 S += FieldName + "; // by ref\n";
3598 }
3599 // Finish writing the constructor.
3600 // FIXME: handle NSConcreteGlobalBlock.
3601 Constructor += ", int flags=0) {\n";
3602 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3603 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3604
3605 if (hasCopyDisposeHelpers)
3606 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3607
3608 // Initialize all "by copy" arguments.
3609 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3610 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003611 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003612 Constructor += " ";
3613 if (isBlockPointerType((*I)->getType()))
3614 Constructor += Name + " = (struct __block_impl *)_";
3615 else
3616 Constructor += Name + " = _";
3617 Constructor += Name + ";\n";
3618 }
3619 // Initialize all "by ref" arguments.
3620 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3621 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003622 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003623 Constructor += " ";
3624 if (isBlockPointerType((*I)->getType()))
3625 Constructor += Name + " = (struct __block_impl *)_";
3626 else
3627 Constructor += Name + " = _";
3628 Constructor += Name + ";\n";
3629 }
3630 } else {
3631 // Finish writing the constructor.
3632 // FIXME: handle NSConcreteGlobalBlock.
3633 Constructor += ", int flags=0) {\n";
3634 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3635 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3636 if (hasCopyDisposeHelpers)
3637 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3638 }
3639 Constructor += " ";
3640 Constructor += "}\n";
3641 S += Constructor;
3642 S += "};\n";
3643 return S;
3644}
3645
3646void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3647 const char *FunName) {
3648 // Insert closures that were part of the function.
3649 for (unsigned i = 0; i < Blocks.size(); i++) {
3650
3651 CollectBlockDeclRefInfo(Blocks[i]);
3652
3653 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3654
3655 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3656 ImportedBlockDecls.size() > 0);
3657
3658 InsertText(FunLocStart, CI.c_str(), CI.size());
3659
3660 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3661
3662 InsertText(FunLocStart, CF.c_str(), CF.size());
3663
3664 if (ImportedBlockDecls.size()) {
3665 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3666 InsertText(FunLocStart, HF.c_str(), HF.size());
3667 }
3668
3669 BlockDeclRefs.clear();
3670 BlockByRefDecls.clear();
3671 BlockByCopyDecls.clear();
3672 BlockCallExprs.clear();
3673 ImportedBlockDecls.clear();
3674 }
3675 Blocks.clear();
3676 RewrittenBlockExprs.clear();
3677}
3678
3679void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3680 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003681 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003682
3683 SynthesizeBlockLiterals(FunLocStart, FuncName);
3684}
3685
3686void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003687 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3688 //SourceLocation FunLocStart = MD->getLocStart();
3689 // FIXME: This hack works around a bug in Rewrite.InsertText().
3690 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003691 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003692 // Convert colons to underscores.
3693 std::string::size_type loc = 0;
3694 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3695 FuncName.replace(loc, 1, "_");
3696
3697 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3698}
3699
3700void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3701 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3702 CI != E; ++CI)
3703 if (*CI) {
3704 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3705 GetBlockDeclRefExprs(CBE->getBody());
3706 else
3707 GetBlockDeclRefExprs(*CI);
3708 }
3709 // Handle specific things.
3710 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3711 // FIXME: Handle enums.
3712 if (!isa<FunctionDecl>(CDRE->getDecl()))
3713 BlockDeclRefs.push_back(CDRE);
3714 return;
3715}
3716
3717void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3718 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3719 CI != E; ++CI)
3720 if (*CI) {
3721 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3722 GetBlockCallExprs(CBE->getBody());
3723 else
3724 GetBlockCallExprs(*CI);
3725 }
3726
3727 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3728 if (CE->getCallee()->getType()->isBlockPointerType()) {
3729 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3730 }
3731 }
3732 return;
3733}
3734
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003735Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003736 // Navigate to relevant type information.
3737 const char *closureName = 0;
3738 const BlockPointerType *CPT = 0;
3739
3740 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003741 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003742 CPT = DRE->getType()->getAsBlockPointerType();
3743 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003744 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003745 CPT = CDRE->getType()->getAsBlockPointerType();
3746 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003747 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003748 CPT = MExpr->getType()->getAsBlockPointerType();
3749 } else {
3750 assert(1 && "RewriteBlockClass: Bad type");
3751 }
3752 assert(CPT && "RewriteBlockClass: Bad type");
3753 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3754 assert(FT && "RewriteBlockClass: Bad type");
3755 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3756 // FTP will be null for closures that don't take arguments.
3757
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003758 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3759 SourceLocation(),
3760 &Context->Idents.get("__block_impl"));
3761 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003762
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003763 // Generate a funky cast.
3764 llvm::SmallVector<QualType, 8> ArgTypes;
3765
3766 // Push the block argument type.
3767 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003768 if (FTP) {
3769 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003770 E = FTP->arg_type_end(); I && (I != E); ++I) {
3771 QualType t = *I;
3772 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3773 if (isBlockPointerType(t)) {
3774 const BlockPointerType *BPT = t->getAsBlockPointerType();
3775 t = Context->getPointerType(BPT->getPointeeType());
3776 }
3777 ArgTypes.push_back(t);
3778 }
Steve Naroff54055232008-10-27 17:20:55 +00003779 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003780 // Now do the pointer to function cast.
3781 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3782 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3783
3784 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003785
Steve Naroffb2f9e512008-11-03 23:29:32 +00003786 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003787 // Don't forget the parens to enforce the proper binding.
3788 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3789 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003790
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003791 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3792 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3793 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3794
Steve Naroffb2f9e512008-11-03 23:29:32 +00003795 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003796 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3797
3798 llvm::SmallVector<Expr*, 8> BlkExprs;
3799 // Add the implicit argument.
3800 BlkExprs.push_back(BlkCast);
3801 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003802 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3803 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003804 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003805 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003806 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3807 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003808}
3809
3810void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003811 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3812 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003813}
3814
3815void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3816 // FIXME: Add more elaborate code generation required by the ABI.
3817 InsertText(BDRE->getLocStart(), "*", 1);
3818}
3819
Steve Naroffb2f9e512008-11-03 23:29:32 +00003820void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3821 SourceLocation LocStart = CE->getLParenLoc();
3822 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003823
3824 // Need to avoid trying to rewrite synthesized casts.
3825 if (LocStart.isInvalid())
3826 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003827 // Need to avoid trying to rewrite casts contained in macros.
3828 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3829 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003830
Steve Naroff54055232008-10-27 17:20:55 +00003831 const char *startBuf = SM->getCharacterData(LocStart);
3832 const char *endBuf = SM->getCharacterData(LocEnd);
3833
3834 // advance the location to startArgList.
3835 const char *argPtr = startBuf;
3836
3837 while (*argPtr++ && (argPtr < endBuf)) {
3838 switch (*argPtr) {
3839 case '^':
3840 // Replace the '^' with '*'.
3841 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3842 ReplaceText(LocStart, 1, "*", 1);
3843 break;
3844 }
3845 }
3846 return;
3847}
3848
3849void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3850 SourceLocation DeclLoc = FD->getLocation();
3851 unsigned parenCount = 0;
3852
3853 // We have 1 or more arguments that have closure pointers.
3854 const char *startBuf = SM->getCharacterData(DeclLoc);
3855 const char *startArgList = strchr(startBuf, '(');
3856
3857 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3858
3859 parenCount++;
3860 // advance the location to startArgList.
3861 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3862 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3863
3864 const char *argPtr = startArgList;
3865
3866 while (*argPtr++ && parenCount) {
3867 switch (*argPtr) {
3868 case '^':
3869 // Replace the '^' with '*'.
3870 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3871 ReplaceText(DeclLoc, 1, "*", 1);
3872 break;
3873 case '(':
3874 parenCount++;
3875 break;
3876 case ')':
3877 parenCount--;
3878 break;
3879 }
3880 }
3881 return;
3882}
3883
3884bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3885 const FunctionTypeProto *FTP;
3886 const PointerType *PT = QT->getAsPointerType();
3887 if (PT) {
3888 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3889 } else {
3890 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3891 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3892 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3893 }
3894 if (FTP) {
3895 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3896 E = FTP->arg_type_end(); I != E; ++I)
3897 if (isBlockPointerType(*I))
3898 return true;
3899 }
3900 return false;
3901}
3902
3903void RewriteObjC::GetExtentOfArgList(const char *Name,
3904 const char *&LParen, const char *&RParen) {
3905 const char *argPtr = strchr(Name, '(');
3906 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3907
3908 LParen = argPtr; // output the start.
3909 argPtr++; // skip past the left paren.
3910 unsigned parenCount = 1;
3911
3912 while (*argPtr && parenCount) {
3913 switch (*argPtr) {
3914 case '(': parenCount++; break;
3915 case ')': parenCount--; break;
3916 default: break;
3917 }
3918 if (parenCount) argPtr++;
3919 }
3920 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3921 RParen = argPtr; // output the end
3922}
3923
3924void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3925 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3926 RewriteBlockPointerFunctionArgs(FD);
3927 return;
3928 }
3929 // Handle Variables and Typedefs.
3930 SourceLocation DeclLoc = ND->getLocation();
3931 QualType DeclT;
3932 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3933 DeclT = VD->getType();
3934 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3935 DeclT = TDD->getUnderlyingType();
3936 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3937 DeclT = FD->getType();
3938 else
3939 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3940
3941 const char *startBuf = SM->getCharacterData(DeclLoc);
3942 const char *endBuf = startBuf;
3943 // scan backward (from the decl location) for the end of the previous decl.
3944 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3945 startBuf--;
3946
3947 // *startBuf != '^' if we are dealing with a pointer to function that
3948 // may take block argument types (which will be handled below).
3949 if (*startBuf == '^') {
3950 // Replace the '^' with '*', computing a negative offset.
3951 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3952 ReplaceText(DeclLoc, 1, "*", 1);
3953 }
3954 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3955 // Replace the '^' with '*' for arguments.
3956 DeclLoc = ND->getLocation();
3957 startBuf = SM->getCharacterData(DeclLoc);
3958 const char *argListBegin, *argListEnd;
3959 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3960 while (argListBegin < argListEnd) {
3961 if (*argListBegin == '^') {
3962 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3963 ReplaceText(CaretLoc, 1, "*", 1);
3964 }
3965 argListBegin++;
3966 }
3967 }
3968 return;
3969}
3970
3971void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3972 // Add initializers for any closure decl refs.
3973 GetBlockDeclRefExprs(Exp->getBody());
3974 if (BlockDeclRefs.size()) {
3975 // Unique all "by copy" declarations.
3976 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3977 if (!BlockDeclRefs[i]->isByRef())
3978 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3979 // Unique all "by ref" declarations.
3980 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3981 if (BlockDeclRefs[i]->isByRef()) {
3982 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3983 }
3984 // Find any imported blocks...they will need special attention.
3985 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3986 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003987 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003988 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3989 }
3990 }
3991}
3992
Steve Narofffa15fd92008-10-28 20:29:00 +00003993FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3994 IdentifierInfo *ID = &Context->Idents.get(name);
3995 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3996 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3997 ID, FType, FunctionDecl::Extern, false, 0);
3998}
3999
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004000Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004001 Blocks.push_back(Exp);
4002
4003 CollectBlockDeclRefInfo(Exp);
4004 std::string FuncName;
4005
4006 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004007 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004008 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004009 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004010 // Convert colons to underscores.
4011 std::string::size_type loc = 0;
4012 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4013 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004014 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004015 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004016
4017 std::string BlockNumber = utostr(Blocks.size()-1);
4018
4019 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4020 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4021
4022 // Get a pointer to the function type so we can cast appropriately.
4023 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4024
4025 FunctionDecl *FD;
4026 Expr *NewRep;
4027
4028 // Simulate a contructor call...
4029 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4030 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4031
4032 llvm::SmallVector<Expr*, 4> InitExprs;
4033
Steve Narofffdc03722008-10-29 21:23:59 +00004034 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004035 FD = SynthBlockInitFunctionDecl(Func.c_str());
4036 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4037 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004038 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004039 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004040
4041 if (ImportedBlockDecls.size()) {
4042 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004043 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4044 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4045 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004046 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004047 InitExprs.push_back(castExpr);
4048
Steve Narofffa15fd92008-10-28 20:29:00 +00004049 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004050 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4051 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4052 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004053 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004054 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004055 }
4056 // Add initializers for any closure decl refs.
4057 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004058 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004059 // Output all "by copy" declarations.
4060 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4061 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004062 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004063 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004064 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004065 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004066 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004067 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004068 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4069 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004070 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004071 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004072 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004073 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004074 }
Steve Narofffdc03722008-10-29 21:23:59 +00004075 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004076 }
4077 // Output all "by ref" declarations.
4078 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4079 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004080 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004081 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4082 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4083 Context->getPointerType(Exp->getType()),
4084 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004085 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004086 }
4087 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004088 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4089 FType, SourceLocation());
4090 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4091 Context->getPointerType(NewRep->getType()),
4092 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004093 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004094 BlockDeclRefs.clear();
4095 BlockByRefDecls.clear();
4096 BlockByCopyDecls.clear();
4097 ImportedBlockDecls.clear();
4098 return NewRep;
4099}
4100
4101//===----------------------------------------------------------------------===//
4102// Function Body / Expression rewriting
4103//===----------------------------------------------------------------------===//
4104
Steve Naroffc77a6362008-12-04 16:24:46 +00004105// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4106// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4107// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4108// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4109// Since the rewriter isn't capable of rewriting rewritten code, it's important
4110// we get this right.
4111void RewriteObjC::CollectPropertySetters(Stmt *S) {
4112 // Perform a bottom up traversal of all children.
4113 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4114 CI != E; ++CI)
4115 if (*CI)
4116 CollectPropertySetters(*CI);
4117
4118 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4119 if (BinOp->isAssignmentOp()) {
4120 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4121 PropSetters[PRE] = BinOp;
4122 }
4123 }
4124}
4125
Steve Narofffa15fd92008-10-28 20:29:00 +00004126Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4127 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4128 isa<DoStmt>(S) || isa<ForStmt>(S))
4129 Stmts.push_back(S);
4130 else if (isa<ObjCForCollectionStmt>(S)) {
4131 Stmts.push_back(S);
4132 ObjCBcLabelNo.push_back(++BcLabelCount);
4133 }
4134
4135 SourceRange OrigStmtRange = S->getSourceRange();
4136
4137 // Perform a bottom up rewrite of all children.
4138 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4139 CI != E; ++CI)
4140 if (*CI) {
4141 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4142 if (newStmt)
4143 *CI = newStmt;
4144 }
4145
4146 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4147 // Rewrite the block body in place.
4148 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4149
4150 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004151 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4152 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004153
4154 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4155 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004156 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004157 return blockTranscribed;
4158 }
4159 // Handle specific things.
4160 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4161 return RewriteAtEncode(AtEncode);
4162
4163 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4164 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4165
Steve Naroffc77a6362008-12-04 16:24:46 +00004166 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4167 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4168 if (BinOp) {
4169 // Because the rewriter doesn't allow us to rewrite rewritten code,
4170 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004171 DisableReplaceStmt = true;
4172 // Save the source range. Even if we disable the replacement, the
4173 // rewritten node will have been inserted into the tree. If the synthesized
4174 // node is at the 'end', the rewriter will fail. Consider this:
4175 // self.errorHandler = handler ? handler :
4176 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4177 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004178 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004179 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004180 //
4181 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4182 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4183 // to see the original expression). Consider this example:
4184 //
4185 // Foo *obj1, *obj2;
4186 //
4187 // obj1.i = [obj2 rrrr];
4188 //
4189 // 'BinOp' for the previous expression looks like:
4190 //
4191 // (BinaryOperator 0x231ccf0 'int' '='
4192 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4193 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4194 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4195 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4196 //
4197 // 'newStmt' represents the rewritten message expression. For example:
4198 //
4199 // (CallExpr 0x231d300 'id':'struct objc_object *'
4200 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4201 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4202 // (CStyleCastExpr 0x231d220 'void *'
4203 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4204 //
4205 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4206 // can be used as the setter argument. ReplaceStmt() will still 'see'
4207 // the original RHS (since we haven't altered BinOp).
4208 //
4209 // This implies the Rewrite* routines can no longer delete the original
4210 // node. As a result, we now leak the original AST nodes.
4211 //
Steve Naroffb619d952008-12-09 12:56:34 +00004212 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004213 } else {
4214 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004215 }
4216 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004217 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4218 return RewriteAtSelector(AtSelector);
4219
4220 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4221 return RewriteObjCStringLiteral(AtString);
4222
4223 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004224#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004225 // Before we rewrite it, put the original message expression in a comment.
4226 SourceLocation startLoc = MessExpr->getLocStart();
4227 SourceLocation endLoc = MessExpr->getLocEnd();
4228
4229 const char *startBuf = SM->getCharacterData(startLoc);
4230 const char *endBuf = SM->getCharacterData(endLoc);
4231
4232 std::string messString;
4233 messString += "// ";
4234 messString.append(startBuf, endBuf-startBuf+1);
4235 messString += "\n";
4236
4237 // FIXME: Missing definition of
4238 // InsertText(clang::SourceLocation, char const*, unsigned int).
4239 // InsertText(startLoc, messString.c_str(), messString.size());
4240 // Tried this, but it didn't work either...
4241 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004242#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004243 return RewriteMessageExpr(MessExpr);
4244 }
4245
4246 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4247 return RewriteObjCTryStmt(StmtTry);
4248
4249 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4250 return RewriteObjCSynchronizedStmt(StmtTry);
4251
4252 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4253 return RewriteObjCThrowStmt(StmtThrow);
4254
4255 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4256 return RewriteObjCProtocolExpr(ProtocolExp);
4257
4258 if (ObjCForCollectionStmt *StmtForCollection =
4259 dyn_cast<ObjCForCollectionStmt>(S))
4260 return RewriteObjCForCollectionStmt(StmtForCollection,
4261 OrigStmtRange.getEnd());
4262 if (BreakStmt *StmtBreakStmt =
4263 dyn_cast<BreakStmt>(S))
4264 return RewriteBreakStmt(StmtBreakStmt);
4265 if (ContinueStmt *StmtContinueStmt =
4266 dyn_cast<ContinueStmt>(S))
4267 return RewriteContinueStmt(StmtContinueStmt);
4268
4269 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4270 // and cast exprs.
4271 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4272 // FIXME: What we're doing here is modifying the type-specifier that
4273 // precedes the first Decl. In the future the DeclGroup should have
4274 // a separate type-specifier that we can rewrite.
4275 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4276
4277 // Blocks rewrite rules.
4278 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4279 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004280 ScopedDecl *SD = *DI;
4281 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4282 if (isBlockPointerType(ND->getType()))
4283 RewriteBlockPointerDecl(ND);
4284 else if (ND->getType()->isFunctionPointerType())
4285 CheckFunctionPointerDecl(ND->getType(), ND);
4286 }
4287 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4288 if (isBlockPointerType(TD->getUnderlyingType()))
4289 RewriteBlockPointerDecl(TD);
4290 else if (TD->getUnderlyingType()->isFunctionPointerType())
4291 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4292 }
4293 }
4294 }
4295
4296 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4297 RewriteObjCQualifiedInterfaceTypes(CE);
4298
4299 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4300 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4301 assert(!Stmts.empty() && "Statement stack is empty");
4302 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4303 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4304 && "Statement stack mismatch");
4305 Stmts.pop_back();
4306 }
4307 // Handle blocks rewriting.
4308 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4309 if (BDRE->isByRef())
4310 RewriteBlockDeclRefExpr(BDRE);
4311 }
4312 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004313 if (CE->getCallee()->getType()->isBlockPointerType()) {
4314 Stmt *BlockCall = SynthesizeBlockCall(CE);
4315 ReplaceStmt(S, BlockCall);
4316 return BlockCall;
4317 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004318 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004319 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004320 RewriteCastExpr(CE);
4321 }
4322#if 0
4323 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4324 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4325 // Get the new text.
4326 std::string SStr;
4327 llvm::raw_string_ostream Buf(SStr);
4328 Replacement->printPretty(Buf);
4329 const std::string &Str = Buf.str();
4330
4331 printf("CAST = %s\n", &Str[0]);
4332 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4333 delete S;
4334 return Replacement;
4335 }
4336#endif
4337 // Return this stmt unmodified.
4338 return S;
4339}
4340
4341/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4342/// main file of the input.
4343void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4345 // Since function prototypes don't have ParmDecl's, we check the function
4346 // prototype. This enables us to rewrite function declarations and
4347 // definitions using the same code.
4348 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4349
4350 if (Stmt *Body = FD->getBody()) {
4351 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004352 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004353 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004354 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004355 CurrentBody = 0;
4356 if (PropParentMap) {
4357 delete PropParentMap;
4358 PropParentMap = 0;
4359 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004360 // This synthesizes and inserts the block "impl" struct, invoke function,
4361 // and any copy/dispose helper functions.
4362 InsertBlockLiteralsWithinFunction(FD);
4363 CurFunctionDef = 0;
4364 }
4365 return;
4366 }
4367 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4368 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004369 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004370 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004371 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004372 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004373 CurrentBody = 0;
4374 if (PropParentMap) {
4375 delete PropParentMap;
4376 PropParentMap = 0;
4377 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004378 InsertBlockLiteralsWithinMethod(MD);
4379 CurMethodDef = 0;
4380 }
4381 }
4382 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4383 ClassImplementation.push_back(CI);
4384 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4385 CategoryImplementation.push_back(CI);
4386 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4387 RewriteForwardClassDecl(CD);
4388 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4389 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004390 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004391 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004392 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004393 CheckFunctionPointerDecl(VD->getType(), VD);
4394 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004395 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004396 RewriteCastExpr(CE);
4397 }
4398 }
4399 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004400 if (VD->getInit()) {
4401 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004402 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004403 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004404 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004405 CurrentBody = 0;
4406 if (PropParentMap) {
4407 delete PropParentMap;
4408 PropParentMap = 0;
4409 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004410 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004411 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004412 GlobalVarDecl = 0;
4413
4414 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004415 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004416 RewriteCastExpr(CE);
4417 }
4418 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004419 return;
4420 }
4421 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4422 if (isBlockPointerType(TD->getUnderlyingType()))
4423 RewriteBlockPointerDecl(TD);
4424 else if (TD->getUnderlyingType()->isFunctionPointerType())
4425 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4426 return;
4427 }
4428 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4429 if (RD->isDefinition()) {
4430 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4431 e = RD->field_end(); i != e; ++i) {
4432 FieldDecl *FD = *i;
4433 if (isBlockPointerType(FD->getType()))
4434 RewriteBlockPointerDecl(FD);
4435 }
4436 }
4437 return;
4438 }
4439 // Nothing yet.
4440}
4441
4442void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4443 // Get the top-level buffer that this corresponds to.
4444
4445 // Rewrite tabs if we care.
4446 //RewriteTabs();
4447
4448 if (Diags.hasErrorOccurred())
4449 return;
4450
4451 // Create the output file.
4452
4453 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4454 llvm::raw_ostream *OutFile;
4455 if (OutFileName == "-") {
4456 OutFile = &llvm::outs();
4457 } else if (!OutFileName.empty()) {
4458 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004459 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004460 OwnedStream.reset(OutFile);
4461 } else if (InFileName == "-") {
4462 OutFile = &llvm::outs();
4463 } else {
4464 llvm::sys::Path Path(InFileName);
4465 Path.eraseSuffix();
4466 Path.appendSuffix("cpp");
4467 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004468 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004469 OwnedStream.reset(OutFile);
4470 }
4471
4472 RewriteInclude();
4473
4474 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4475 Preamble.c_str(), Preamble.size(), false);
4476
Steve Naroff0aab7962008-11-14 14:10:01 +00004477 if (ClassImplementation.size() || CategoryImplementation.size())
4478 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004479
4480 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4481 // we are done.
4482 if (const RewriteBuffer *RewriteBuf =
4483 Rewrite.getRewriteBufferFor(MainFileID)) {
4484 //printf("Changed:\n");
4485 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4486 } else {
4487 fprintf(stderr, "No changes\n");
4488 }
Steve Narofface66252008-11-13 20:07:04 +00004489
Steve Naroff0aab7962008-11-14 14:10:01 +00004490 if (ClassImplementation.size() || CategoryImplementation.size()) {
4491 // Rewrite Objective-c meta data*
4492 std::string ResultStr;
4493 SynthesizeMetaDataIntoBuffer(ResultStr);
4494 // Emit metadata.
4495 *OutFile << ResultStr;
4496 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 OutFile->flush();
4498}
4499