blob: 4e262963a973411bd98ba9aad8a7eb0c45ec2265 [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 Lattner2b2453a2009-01-17 06:22:33 +000050 FileID 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);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000227 void RewriteImplementationDecl(Decl *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);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000342 bool isTopLevelBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
Steve Naroff54055232008-10-27 17:20:55 +0000343
344 // FIXME: This predicate seems like it would be useful to add to ASTContext.
345 bool isObjCType(QualType T) {
346 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
347 return false;
348
349 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
350
351 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
352 OCT == Context->getCanonicalType(Context->getObjCClassType()))
353 return true;
354
355 if (const PointerType *PT = OCT->getAsPointerType()) {
356 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
357 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
358 return true;
359 }
360 return false;
361 }
362 bool PointerTypeTakesAnyBlockArguments(QualType QT);
363 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000368 };
369}
370
Steve Naroff54055232008-10-27 17:20:55 +0000371void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
372 NamedDecl *D) {
373 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
374 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
387 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
388}
389
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroffb29b4272008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
413 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000414}
415
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000416ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000417 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000418 Diagnostic &Diags,
419 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000420 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000421}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422
Steve Naroffb29b4272008-04-14 22:03:09 +0000423void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000424 Context = &context;
425 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000426 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000427 MsgSendFunctionDecl = 0;
428 MsgSendSuperFunctionDecl = 0;
429 MsgSendStretFunctionDecl = 0;
430 MsgSendSuperStretFunctionDecl = 0;
431 MsgSendFpretFunctionDecl = 0;
432 GetClassFunctionDecl = 0;
433 GetMetaClassFunctionDecl = 0;
434 SelGetUidFunctionDecl = 0;
435 CFStringFunctionDecl = 0;
436 GetProtocolFunctionDecl = 0;
437 ConstantStringClassReference = 0;
438 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000439 CurMethodDef = 0;
440 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000441 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000442 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000443 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000444 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000445 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000446 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000447 PropParentMap = 0;
448 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000449 DisableReplaceStmt = false;
450
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000451 // Get the ID and start/end of the main file.
452 MainFileID = SM->getMainFileID();
453 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
454 MainFileStart = MainBuf->getBufferStart();
455 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000456
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000457 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000458
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000459 // declaring objc_selector outside the parameter list removes a silly
460 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000462 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000463 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000464 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000465 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000466 if (LangOpts.Microsoft) {
467 // Add a constructor for creating temporary objects.
Steve Naroff46a98a72008-12-23 20:11:22 +0000468 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) : ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000470 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
473 Preamble += "typedef struct objc_object Protocol;\n";
474 Preamble += "#define _REWRITER_typedef_Protocol\n";
475 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000476 if (LangOpts.Microsoft) {
477 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
478 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
479 } else
480 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
481 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000482 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000492 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
496 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000500 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000501 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
504 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
506 Preamble += "struct __objcFastEnumerationState {\n\t";
507 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000508 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "unsigned long *mutationsPtr;\n\t";
510 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000512 Preamble += "#define __FASTENUMERATIONSTATE\n";
513 Preamble += "#endif\n";
514 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
515 Preamble += "struct __NSConstantStringImpl {\n";
516 Preamble += " int *isa;\n";
517 Preamble += " int flags;\n";
518 Preamble += " char *str;\n";
519 Preamble += " long length;\n";
520 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000521 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
522 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
523 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000524 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000525 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000526 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
527 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000528 // Blocks preamble.
529 Preamble += "#ifndef BLOCK_IMPL\n";
530 Preamble += "#define BLOCK_IMPL\n";
531 Preamble += "struct __block_impl {\n";
532 Preamble += " void *isa;\n";
533 Preamble += " int Flags;\n";
534 Preamble += " int Size;\n";
535 Preamble += " void *FuncPtr;\n";
536 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000537 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
538 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
539 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000542 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000543 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
545 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000546 Preamble += "#define __attribute__(X)\n";
547 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548}
549
550
Chris Lattnerf04da132007-10-24 17:06:59 +0000551//===----------------------------------------------------------------------===//
552// Top Level Driver Code
553//===----------------------------------------------------------------------===//
554
Steve Naroffb29b4272008-04-14 22:03:09 +0000555void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000556 // Two cases: either the decl could be in the main file, or it could be in a
557 // #included file. If the former, rewrite it now. If the later, check to see
558 // if we rewrote the #include/#import.
559 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000560 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000561
562 // If this is for a builtin, ignore it.
563 if (Loc.isInvalid()) return;
564
Steve Naroffebf2b562007-10-23 23:50:29 +0000565 // Look for built-in declarations that we need to refer during the rewrite.
566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000567 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000568 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000569 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000570 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000571 ConstantStringClassReference = FVD;
572 return;
573 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000575 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000577 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000578 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000579 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 } else if (ObjCForwardProtocolDecl *FP =
581 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000582 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000583 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
584 // Recurse into linkage specifications
585 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
586 DIEnd = LSD->decls_end();
587 DI != DIEnd; ++DI)
588 HandleTopLevelDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000589 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000590 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000591 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000592 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000593}
594
Chris Lattnerf04da132007-10-24 17:06:59 +0000595//===----------------------------------------------------------------------===//
596// Syntactic (non-AST) Rewriting Code
597//===----------------------------------------------------------------------===//
598
Steve Naroffb29b4272008-04-14 22:03:09 +0000599void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000600 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000601 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
602 const char *MainBufStart = MainBuf.first;
603 const char *MainBufEnd = MainBuf.second;
604 size_t ImportLen = strlen("import");
605 size_t IncludeLen = strlen("include");
606
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000607 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000608 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
609 if (*BufPtr == '#') {
610 if (++BufPtr == MainBufEnd)
611 return;
612 while (*BufPtr == ' ' || *BufPtr == '\t')
613 if (++BufPtr == MainBufEnd)
614 return;
615 if (!strncmp(BufPtr, "import", ImportLen)) {
616 // replace import with include
617 SourceLocation ImportLoc =
618 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000619 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000620 BufPtr += ImportLen;
621 }
622 }
623 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000624}
625
Steve Naroffb29b4272008-04-14 22:03:09 +0000626void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000627 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
628 const char *MainBufStart = MainBuf.first;
629 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000630
Chris Lattnerf04da132007-10-24 17:06:59 +0000631 // Loop over the whole file, looking for tabs.
632 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
633 if (*BufPtr != '\t')
634 continue;
635
636 // Okay, we found a tab. This tab will turn into at least one character,
637 // but it depends on which 'virtual column' it is in. Compute that now.
638 unsigned VCol = 0;
639 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
640 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
641 ++VCol;
642
643 // Okay, now that we know the virtual column, we know how many spaces to
644 // insert. We assume 8-character tab-stops.
645 unsigned Spaces = 8-(VCol & 7);
646
647 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000648 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
649 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000650
651 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000652 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000653 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000654}
655
Steve Naroffeb0646c2008-12-02 15:48:25 +0000656static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
657 ObjCIvarDecl *OID) {
658 std::string S;
659 S = "((struct ";
660 S += ClassDecl->getIdentifier()->getName();
661 S += "_IMPL *)self)->";
662 S += OID->getNameAsCString();
663 return S;
664}
665
Steve Naroffa0876e82008-12-02 17:36:43 +0000666void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
667 ObjCImplementationDecl *IMD,
668 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000669 SourceLocation startLoc = PID->getLocStart();
670 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000671 const char *startBuf = SM->getCharacterData(startLoc);
672 assert((*startBuf == '@') && "bogus @synthesize location");
673 const char *semiBuf = strchr(startBuf, ';');
674 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
675 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
676
677 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
678 return; // FIXME: is this correct?
679
680 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000681 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000683 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000684
685 if (!OID)
686 return;
687
688 std::string Getr;
689 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
690 Getr += "{ ";
691 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000692 // FIXME: deal with code generation implications for various property
693 // attributes (copy, retain, nonatomic).
694 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000695 Getr += "return " + getIvarAccessString(ClassDecl, OID);
696 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000697 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000698
699 // Add the rewritten getter to trigger meta data generation. An alternate, and
700 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
701 // with properties explicitly. The following addInstanceMethod() required far
702 // less code change (and actually models what the rewriter is doing).
703 if (IMD)
704 IMD->addInstanceMethod(PD->getGetterMethodDecl());
705 else
706 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000707
708 if (PD->isReadOnly())
709 return;
710
711 // Generate the 'setter' function.
712 std::string Setr;
713 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000714 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000715 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000716 // FIXME: deal with code generation implications for various property
717 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000718 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000719 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000720 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000721 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000722 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000723
724 // Add the rewritten setter to trigger meta data generation.
725 if (IMD)
726 IMD->addInstanceMethod(PD->getSetterMethodDecl());
727 else
728 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000729}
Chris Lattner8a12c272007-10-11 18:38:32 +0000730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000734
735 // Get the start location and compute the semi location.
736 SourceLocation startLoc = ClassDecl->getLocation();
737 const char *startBuf = SM->getCharacterData(startLoc);
738 const char *semiPtr = strchr(startBuf, ';');
739
740 // Translate to typedef's that forward reference structs with the same name
741 // as the class. As a convenience, we include the original declaration
742 // as a comment.
743 std::string typedefString;
744 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000745 typedefString.append(startBuf, semiPtr-startBuf+1);
746 typedefString += "\n";
747 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000749 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000751 typedefString += "\n";
752 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000754 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000755 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000758 }
759
760 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(startLoc, semiPtr-startBuf+1,
762 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000763}
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000766 SourceLocation LocStart = Method->getLocStart();
767 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000768
Chris Lattner30fc9332009-02-04 01:06:56 +0000769 if (SM->getInstantiationLineNumber(LocEnd) >
770 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000771 InsertText(LocStart, "#if 0\n", 6);
772 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000773 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000774 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000775 }
776}
777
Steve Naroff6327e0d2009-01-11 01:06:09 +0000778void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000779{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000780 SourceLocation Loc = prop->getLocation();
781
782 ReplaceText(Loc, 0, "// ", 3);
783
784 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000785}
786
Steve Naroffb29b4272008-04-14 22:03:09 +0000787void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000788 SourceLocation LocStart = CatDecl->getLocStart();
789
790 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000791 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000792
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000794 E = CatDecl->instmeth_end(); I != E; ++I)
795 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000796 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000797 E = CatDecl->classmeth_end(); I != E; ++I)
798 RewriteMethodDeclaration(*I);
799
Steve Naroff423cb562007-10-30 13:30:57 +0000800 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000801 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000802}
803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000805 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806
Steve Naroff752d6ef2007-10-30 16:42:30 +0000807 SourceLocation LocStart = PDecl->getLocStart();
808
809 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000810 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000811
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000812 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000813 E = PDecl->instmeth_end(); I != E; ++I)
814 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000815 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000816 E = PDecl->classmeth_end(); I != E; ++I)
817 RewriteMethodDeclaration(*I);
818
Steve Naroff752d6ef2007-10-30 16:42:30 +0000819 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000820 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000821 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000822
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000823 // Must comment out @optional/@required
824 const char *startBuf = SM->getCharacterData(LocStart);
825 const char *endBuf = SM->getCharacterData(LocEnd);
826 for (const char *p = startBuf; p < endBuf; p++) {
827 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
828 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000829 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000830 ReplaceText(OptionalLoc, strlen("@optional"),
831 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000832
833 }
834 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
835 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000836 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000837 ReplaceText(OptionalLoc, strlen("@required"),
838 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000839
840 }
841 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000842}
843
Steve Naroffb29b4272008-04-14 22:03:09 +0000844void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000845 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000846 if (LocStart.isInvalid())
847 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000848 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000849 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850}
851
Steve Naroffb29b4272008-04-14 22:03:09 +0000852void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000853 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000854 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000855 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000858 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000859 else if (OMD->getResultType()->isFunctionPointerType() ||
860 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000861 // needs special handling, since pointer-to-functions have special
862 // syntax (where a decaration models use).
863 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000864 QualType PointeeTy;
865 if (const PointerType* PT = retType->getAsPointerType())
866 PointeeTy = PT->getPointeeType();
867 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
868 PointeeTy = BPT->getPointeeType();
869 if ((FPRetType = PointeeTy->getAsFunctionType())) {
870 ResultStr += FPRetType->getResultType().getAsString();
871 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000872 }
873 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000874 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000875 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000876
877 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000878 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000879
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000880 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000881 NameStr += "_I_";
882 else
883 NameStr += "_C_";
884
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000885 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000886 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000887
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000888 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000889 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000890 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000891 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000892 }
Steve Naroff563b8282008-04-04 22:23:44 +0000893 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000894 {
895 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 int len = selString.size();
897 for (int i = 0; i < len; i++)
898 if (selString[i] == ':')
899 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000900 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 // Remember this name for metadata emission
903 MethodInternalNames[OMD] = NameStr;
904 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905
906 // Rewrite arguments
907 ResultStr += "(";
908
909 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000910 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000911 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000912 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000913 if (!LangOpts.Microsoft) {
914 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
915 ResultStr += "struct ";
916 }
917 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000918 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000919 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000920 }
921 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000922 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923
924 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000925 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ResultStr += " _cmd";
927
928 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000929 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ParmVarDecl *PDecl = OMD->getParamDecl(i);
931 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000932 if (PDecl->getType()->isObjCQualifiedIdType()) {
933 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000934 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000935 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000936 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000937 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000938 // Make sure we convert "t (^)(...)" to "t (*)(...)".
939 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
940 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
941 } else
942 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000943 ResultStr += Name;
944 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000945 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000946 if (OMD->isVariadic())
947 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000948 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949
Steve Naroff76e429d2008-07-16 14:40:40 +0000950 if (FPRetType) {
951 ResultStr += ")"; // close the precedence "scope" for "*".
952
953 // Now, emit the argument types (if any).
954 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
955 ResultStr += "(";
956 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
957 if (i) ResultStr += ", ";
958 std::string ParamStr = FT->getArgType(i).getAsString();
959 ResultStr += ParamStr;
960 }
961 if (FT->isVariadic()) {
962 if (FT->getNumArgs()) ResultStr += ", ";
963 ResultStr += "...";
964 }
965 ResultStr += ")";
966 } else {
967 ResultStr += "()";
968 }
969 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000971void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000972 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
973 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000975 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000976 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000977 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000978 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000979
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000980 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000981 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
982 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000983 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 ObjCMethodDecl *OMD = *I;
985 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000986 SourceLocation LocStart = OMD->getLocStart();
987 SourceLocation LocEnd = OMD->getBody()->getLocStart();
988
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000991 ReplaceText(LocStart, endBuf-startBuf,
992 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 }
994
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000995 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000996 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
997 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000999 ObjCMethodDecl *OMD = *I;
1000 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001001 SourceLocation LocStart = OMD->getLocStart();
1002 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1003
1004 const char *startBuf = SM->getCharacterData(LocStart);
1005 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001006 ReplaceText(LocStart, endBuf-startBuf,
1007 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001009 for (ObjCCategoryImplDecl::propimpl_iterator
1010 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1011 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001012 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001013 }
1014
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001015 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001016 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001017 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001018 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001019}
1020
Steve Naroffb29b4272008-04-14 22:03:09 +00001021void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001022 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001023 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001024 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001025 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001026 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001027 ResultStr += "\n";
1028 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001029 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001030 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001031 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001032 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001033 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001034 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001035 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001036 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001037 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001038
Steve Naroff6327e0d2009-01-11 01:06:09 +00001039 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1040 E = ClassDecl->prop_end(); I != E; ++I)
1041 RewriteProperty(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001042 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001043 E = ClassDecl->instmeth_end(); I != E; ++I)
1044 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001045 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001046 E = ClassDecl->classmeth_end(); I != E; ++I)
1047 RewriteMethodDeclaration(*I);
1048
Steve Naroff2feac5e2007-10-30 03:43:13 +00001049 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001050 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001051}
1052
Steve Naroffb619d952008-12-09 12:56:34 +00001053Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1054 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001055 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1056 // This allows us to reuse all the fun and games in SynthMessageExpr().
1057 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1058 ObjCMessageExpr *MsgExpr;
1059 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1060 llvm::SmallVector<Expr *, 1> ExprVec;
1061 ExprVec.push_back(newStmt);
1062
Steve Naroff8599e7a2008-12-08 16:43:47 +00001063 Stmt *Receiver = PropRefExpr->getBase();
1064 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1065 if (PRE && PropGetters[PRE]) {
1066 // This allows us to handle chain/nested property getters.
1067 Receiver = PropGetters[PRE];
1068 }
1069 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001070 PDecl->getSetterName(), PDecl->getType(),
1071 PDecl->getSetterMethodDecl(),
1072 SourceLocation(), SourceLocation(),
1073 &ExprVec[0], 1);
1074 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1075
1076 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001077 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001078 //delete BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00001079 delete MsgExpr;
1080 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001081}
1082
Steve Naroffc77a6362008-12-04 16:24:46 +00001083Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001084 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1085 // This allows us to reuse all the fun and games in SynthMessageExpr().
1086 ObjCMessageExpr *MsgExpr;
1087 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1088
Steve Naroff8599e7a2008-12-08 16:43:47 +00001089 Stmt *Receiver = PropRefExpr->getBase();
1090
1091 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1092 if (PRE && PropGetters[PRE]) {
1093 // This allows us to handle chain/nested property getters.
1094 Receiver = PropGetters[PRE];
1095 }
1096 MsgExpr = new ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001097 PDecl->getGetterName(), PDecl->getType(),
1098 PDecl->getGetterMethodDecl(),
1099 SourceLocation(), SourceLocation(),
1100 0, 0);
1101
Steve Naroff4c3580e2008-12-04 23:50:32 +00001102 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001103
1104 if (!PropParentMap)
1105 PropParentMap = new ParentMap(CurrentBody);
1106
1107 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1108 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1109 // We stash away the ReplacingStmt since actually doing the
1110 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1111 PropGetters[PropRefExpr] = ReplacingStmt;
1112 delete MsgExpr;
1113 return PropRefExpr; // return the original...
1114 } else {
1115 ReplaceStmt(PropRefExpr, ReplacingStmt);
1116 // delete PropRefExpr; elsewhere...
1117 delete MsgExpr;
1118 return ReplacingStmt;
1119 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001120}
1121
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001122Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1123 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001124 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001125 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001126 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001127 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1128 // lookup which class implements the instance variable.
1129 ObjCInterfaceDecl *clsDeclared = 0;
1130 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1131 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1132
1133 // Synthesize an explicit cast to gain access to the ivar.
1134 std::string RecName = clsDeclared->getIdentifier()->getName();
1135 RecName += "_IMPL";
1136 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001137 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001138 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001139 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1140 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001141 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001142 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001143 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001144 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1145 IV->getBase()->getLocEnd(),
1146 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001147 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001148 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001149 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1150 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001151 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001152 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001153 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001154 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001155
1156 ReplaceStmt(IV->getBase(), PE);
1157 // Cannot delete IV->getBase(), since PE points to it.
1158 // Replace the old base with the cast. This is important when doing
1159 // embedded rewrites. For example, [newInv->_container addObject:0].
1160 IV->setBase(PE);
1161 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001162 }
Steve Naroff84472a82008-04-18 21:55:08 +00001163 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001164 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1165
1166 // Explicit ivar refs need to have a cast inserted.
1167 // FIXME: consider sharing some of this code with the code above.
1168 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001169 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001170 // lookup which class implements the instance variable.
1171 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001172 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001173 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1174
1175 // Synthesize an explicit cast to gain access to the ivar.
1176 std::string RecName = clsDeclared->getIdentifier()->getName();
1177 RecName += "_IMPL";
1178 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001179 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001180 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001181 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1182 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001183 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001184 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001185 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001186 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1187 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001188 ReplaceStmt(IV->getBase(), PE);
1189 // Cannot delete IV->getBase(), since PE points to it.
1190 // Replace the old base with the cast. This is important when doing
1191 // embedded rewrites. For example, [newInv->_container addObject:0].
1192 IV->setBase(PE);
1193 return IV;
1194 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001195 }
Steve Naroff84472a82008-04-18 21:55:08 +00001196 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001197}
1198
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001199/// SynthCountByEnumWithState - To print:
1200/// ((unsigned int (*)
1201/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1202/// (void *)objc_msgSend)((id)l_collection,
1203/// sel_registerName(
1204/// "countByEnumeratingWithState:objects:count:"),
1205/// &enumState,
1206/// (id *)items, (unsigned int)16)
1207///
Steve Naroffb29b4272008-04-14 22:03:09 +00001208void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001209 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1210 "id *, unsigned int))(void *)objc_msgSend)";
1211 buf += "\n\t\t";
1212 buf += "((id)l_collection,\n\t\t";
1213 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1214 buf += "\n\t\t";
1215 buf += "&enumState, "
1216 "(id *)items, (unsigned int)16)";
1217}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001218
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001219/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1220/// statement to exit to its outer synthesized loop.
1221///
Steve Naroffb29b4272008-04-14 22:03:09 +00001222Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001223 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1224 return S;
1225 // replace break with goto __break_label
1226 std::string buf;
1227
1228 SourceLocation startLoc = S->getLocStart();
1229 buf = "goto __break_label_";
1230 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001231 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001232
1233 return 0;
1234}
1235
1236/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1237/// statement to continue with its inner synthesized loop.
1238///
Steve Naroffb29b4272008-04-14 22:03:09 +00001239Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001240 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1241 return S;
1242 // replace continue with goto __continue_label
1243 std::string buf;
1244
1245 SourceLocation startLoc = S->getLocStart();
1246 buf = "goto __continue_label_";
1247 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001248 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001249
1250 return 0;
1251}
1252
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001253/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001254/// It rewrites:
1255/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001256
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001257/// Into:
1258/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001259/// type elem;
1260/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001261/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001262/// id l_collection = (id)collection;
1263/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1264/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001265/// if (limit) {
1266/// unsigned long startMutations = *enumState.mutationsPtr;
1267/// do {
1268/// unsigned long counter = 0;
1269/// do {
1270/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001272/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001273/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001274/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001275/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001276/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1277/// objects:items count:16]);
1278/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001279/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001280/// }
1281/// else
1282/// elem = nil;
1283/// }
1284///
Steve Naroffb29b4272008-04-14 22:03:09 +00001285Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001286 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001287 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1288 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1289 "ObjCForCollectionStmt Statement stack mismatch");
1290 assert(!ObjCBcLabelNo.empty() &&
1291 "ObjCForCollectionStmt - Label No stack empty");
1292
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001293 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001295 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001296 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001297 std::string buf;
1298 buf = "\n{\n\t";
1299 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1300 // type elem;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001301 NamedDecl* D = cast<NamedDecl>(DS->getSolitaryDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001302 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001303 elementTypeAsString = ElementType.getAsString();
1304 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001305 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001306 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 buf += elementName;
1308 buf += ";\n\t";
1309 }
Chris Lattner06767512008-04-08 05:52:18 +00001310 else {
1311 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001312 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001313 elementTypeAsString
1314 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001315 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001316
1317 // struct __objcFastEnumerationState enumState = { 0 };
1318 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1319 // id items[16];
1320 buf += "id items[16];\n\t";
1321 // id l_collection = (id)
1322 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001323 // Find start location of 'collection' the hard way!
1324 const char *startCollectionBuf = startBuf;
1325 startCollectionBuf += 3; // skip 'for'
1326 startCollectionBuf = strchr(startCollectionBuf, '(');
1327 startCollectionBuf++; // skip '('
1328 // find 'in' and skip it.
1329 while (*startCollectionBuf != ' ' ||
1330 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1331 (*(startCollectionBuf+3) != ' ' &&
1332 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1333 startCollectionBuf++;
1334 startCollectionBuf += 3;
1335
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001337 ReplaceText(startLoc, startCollectionBuf - startBuf,
1338 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001339 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001340 SourceLocation rightParenLoc = S->getRParenLoc();
1341 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1342 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001343 buf = ";\n\t";
1344
1345 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1346 // objects:items count:16];
1347 // which is synthesized into:
1348 // unsigned int limit =
1349 // ((unsigned int (*)
1350 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1351 // (void *)objc_msgSend)((id)l_collection,
1352 // sel_registerName(
1353 // "countByEnumeratingWithState:objects:count:"),
1354 // (struct __objcFastEnumerationState *)&state,
1355 // (id *)items, (unsigned int)16);
1356 buf += "unsigned long limit =\n\t\t";
1357 SynthCountByEnumWithState(buf);
1358 buf += ";\n\t";
1359 /// if (limit) {
1360 /// unsigned long startMutations = *enumState.mutationsPtr;
1361 /// do {
1362 /// unsigned long counter = 0;
1363 /// do {
1364 /// if (startMutations != *enumState.mutationsPtr)
1365 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001366 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001367 buf += "if (limit) {\n\t";
1368 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1369 buf += "do {\n\t\t";
1370 buf += "unsigned long counter = 0;\n\t\t";
1371 buf += "do {\n\t\t\t";
1372 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1373 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1374 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001375 buf += " = (";
1376 buf += elementTypeAsString;
1377 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001379 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001381 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382 /// } while (counter < limit);
1383 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1384 /// objects:items count:16]);
1385 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001386 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001387 /// }
1388 /// else
1389 /// elem = nil;
1390 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001391 ///
1392 buf = ";\n\t";
1393 buf += "__continue_label_";
1394 buf += utostr(ObjCBcLabelNo.back());
1395 buf += ": ;";
1396 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397 buf += "} while (counter < limit);\n\t";
1398 buf += "} while (limit = ";
1399 SynthCountByEnumWithState(buf);
1400 buf += ");\n\t";
1401 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001402 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001403 buf += "__break_label_";
1404 buf += utostr(ObjCBcLabelNo.back());
1405 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001406 buf += "}\n\t";
1407 buf += "else\n\t\t";
1408 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001409 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001411
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001413 if (isa<CompoundStmt>(S->getBody())) {
1414 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1415 InsertText(endBodyLoc, buf.c_str(), buf.size());
1416 } else {
1417 /* Need to treat single statements specially. For example:
1418 *
1419 * for (A *a in b) if (stuff()) break;
1420 * for (A *a in b) xxxyy;
1421 *
1422 * The following code simply scans ahead to the semi to find the actual end.
1423 */
1424 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1425 const char *semiBuf = strchr(stmtBuf, ';');
1426 assert(semiBuf && "Can't find ';'");
1427 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1428 InsertText(endBodyLoc, buf.c_str(), buf.size());
1429 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001430 Stmts.pop_back();
1431 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001432 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001433}
1434
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001435/// RewriteObjCSynchronizedStmt -
1436/// This routine rewrites @synchronized(expr) stmt;
1437/// into:
1438/// objc_sync_enter(expr);
1439/// @try stmt @finally { objc_sync_exit(expr); }
1440///
Steve Naroffb29b4272008-04-14 22:03:09 +00001441Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001442 // Get the start location and compute the semi location.
1443 SourceLocation startLoc = S->getLocStart();
1444 const char *startBuf = SM->getCharacterData(startLoc);
1445
1446 assert((*startBuf == '@') && "bogus @synchronized location");
1447
1448 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001449 buf = "objc_sync_enter((id)";
1450 const char *lparenBuf = startBuf;
1451 while (*lparenBuf != '(') lparenBuf++;
1452 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001453 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1454 // the sync expression is typically a message expression that's already
1455 // been rewritten! (which implies the SourceLocation's are invalid).
1456 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001457 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001458 while (*endBuf != ')') endBuf--;
1459 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001460 buf = ");\n";
1461 // declare a new scope with two variables, _stack and _rethrow.
1462 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1463 buf += "int buf[18/*32-bit i386*/];\n";
1464 buf += "char *pointers[4];} _stack;\n";
1465 buf += "id volatile _rethrow = 0;\n";
1466 buf += "objc_exception_try_enter(&_stack);\n";
1467 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001468 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001469 startLoc = S->getSynchBody()->getLocEnd();
1470 startBuf = SM->getCharacterData(startLoc);
1471
Steve Naroffc7089f12008-08-19 13:04:19 +00001472 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001473 SourceLocation lastCurlyLoc = startLoc;
1474 buf = "}\nelse {\n";
1475 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1476 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001477 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001478 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001479 S->getSynchExpr(),
1480 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001481 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001482 std::string syncExprBufS;
1483 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001484 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001485 buf += syncExprBuf.str();
1486 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001487 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1488 buf += "}\n";
1489 buf += "}";
1490
Chris Lattneraadaf782008-01-31 19:51:04 +00001491 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001492 return 0;
1493}
1494
Steve Naroff8c565152008-12-05 17:03:39 +00001495void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1496 // Perform a bottom up traversal of all children.
1497 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1498 CI != E; ++CI)
1499 if (*CI)
1500 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1501
1502 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1503 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1504 Diags.Report(Context->getFullLoc(S->getLocStart()),
1505 TryFinallyContainsReturnDiag);
1506 }
1507 return;
1508}
1509
Steve Naroffb29b4272008-04-14 22:03:09 +00001510Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001511 // Get the start location and compute the semi location.
1512 SourceLocation startLoc = S->getLocStart();
1513 const char *startBuf = SM->getCharacterData(startLoc);
1514
1515 assert((*startBuf == '@') && "bogus @try location");
1516
1517 std::string buf;
1518 // declare a new scope with two variables, _stack and _rethrow.
1519 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1520 buf += "int buf[18/*32-bit i386*/];\n";
1521 buf += "char *pointers[4];} _stack;\n";
1522 buf += "id volatile _rethrow = 0;\n";
1523 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001524 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001525
Chris Lattneraadaf782008-01-31 19:51:04 +00001526 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001527
1528 startLoc = S->getTryBody()->getLocEnd();
1529 startBuf = SM->getCharacterData(startLoc);
1530
1531 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001532
Steve Naroff75730982007-11-07 04:08:17 +00001533 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001534 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1535 if (catchList) {
1536 startLoc = startLoc.getFileLocWithOffset(1);
1537 buf = " /* @catch begin */ else {\n";
1538 buf += " id _caught = objc_exception_extract(&_stack);\n";
1539 buf += " objc_exception_try_enter (&_stack);\n";
1540 buf += " if (_setjmp(_stack.buf))\n";
1541 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1542 buf += " else { /* @catch continue */";
1543
1544 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001545 } else { /* no catch list */
1546 buf = "}\nelse {\n";
1547 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1548 buf += "}";
1549 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001550 }
Steve Naroff75730982007-11-07 04:08:17 +00001551 bool sawIdTypedCatch = false;
1552 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001553 while (catchList) {
1554 Stmt *catchStmt = catchList->getCatchParamStmt();
1555
1556 if (catchList == S->getCatchStmts())
1557 buf = "if ("; // we are generating code for the first catch clause
1558 else
1559 buf = "else if (";
1560 startLoc = catchList->getLocStart();
1561 startBuf = SM->getCharacterData(startLoc);
1562
1563 assert((*startBuf == '@') && "bogus @catch location");
1564
1565 const char *lParenLoc = strchr(startBuf, '(');
1566
Steve Naroffbe4b3332008-02-01 22:08:12 +00001567 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001568 // Now rewrite the body...
1569 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001570 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1571 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001572 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1573 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001574 assert((*bodyBuf == '{') && "bogus @catch body location");
1575
1576 buf += "1) { id _tmp = _caught;";
1577 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1578 buf.c_str(), buf.size());
1579 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001580 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001581 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001582 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001583 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001584 sawIdTypedCatch = true;
1585 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001586 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001587
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001588 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001589 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001590 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001591 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001592 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001593 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001594 }
1595 }
1596 // Now rewrite the body...
1597 lastCatchBody = catchList->getCatchBody();
1598 SourceLocation rParenLoc = catchList->getRParenLoc();
1599 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1600 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1601 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1602 assert((*rParenBuf == ')') && "bogus @catch paren location");
1603 assert((*bodyBuf == '{') && "bogus @catch body location");
1604
1605 buf = " = _caught;";
1606 // Here we replace ") {" with "= _caught;" (which initializes and
1607 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001608 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001609 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001610 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001611 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001612 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001613 catchList = catchList->getNextCatchStmt();
1614 }
1615 // Complete the catch list...
1616 if (lastCatchBody) {
1617 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001618 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1619 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001620
Steve Naroff378f47a2008-09-11 15:29:03 +00001621 // Insert the last (implicit) else clause *before* the right curly brace.
1622 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1623 buf = "} /* last catch end */\n";
1624 buf += "else {\n";
1625 buf += " _rethrow = _caught;\n";
1626 buf += " objc_exception_try_exit(&_stack);\n";
1627 buf += "} } /* @catch end */\n";
1628 if (!S->getFinallyStmt())
1629 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001630 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001631
1632 // Set lastCurlyLoc
1633 lastCurlyLoc = lastCatchBody->getLocEnd();
1634 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001635 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001636 startLoc = finalStmt->getLocStart();
1637 startBuf = SM->getCharacterData(startLoc);
1638 assert((*startBuf == '@') && "bogus @finally start");
1639
1640 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001641 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001642
1643 Stmt *body = finalStmt->getFinallyBody();
1644 SourceLocation startLoc = body->getLocStart();
1645 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001646 assert(*SM->getCharacterData(startLoc) == '{' &&
1647 "bogus @finally body location");
1648 assert(*SM->getCharacterData(endLoc) == '}' &&
1649 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001650
1651 startLoc = startLoc.getFileLocWithOffset(1);
1652 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001653 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001654 endLoc = endLoc.getFileLocWithOffset(-1);
1655 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001656 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001657
1658 // Set lastCurlyLoc
1659 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001660
1661 // Now check for any return/continue/go statements within the @try.
1662 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001663 } else { /* no finally clause - make sure we synthesize an implicit one */
1664 buf = "{ /* implicit finally clause */\n";
1665 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1666 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1667 buf += "}";
1668 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001669 }
1670 // Now emit the final closing curly brace...
1671 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1672 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001673 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001674 return 0;
1675}
1676
Steve Naroffb29b4272008-04-14 22:03:09 +00001677Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001678 return 0;
1679}
1680
Steve Naroffb29b4272008-04-14 22:03:09 +00001681Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001682 return 0;
1683}
1684
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001685// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001686// the throw expression is typically a message expression that's already
1687// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001688Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001689 // Get the start location and compute the semi location.
1690 SourceLocation startLoc = S->getLocStart();
1691 const char *startBuf = SM->getCharacterData(startLoc);
1692
1693 assert((*startBuf == '@') && "bogus @throw location");
1694
1695 std::string buf;
1696 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001697 if (S->getThrowExpr())
1698 buf = "objc_exception_throw(";
1699 else // add an implicit argument
1700 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001701
1702 // handle "@ throw" correctly.
1703 const char *wBuf = strchr(startBuf, 'w');
1704 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1705 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1706
Steve Naroff2bd03922007-11-07 15:32:26 +00001707 const char *semiBuf = strchr(startBuf, ';');
1708 assert((*semiBuf == ';') && "@throw: can't find ';'");
1709 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1710 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001711 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001712 return 0;
1713}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001714
Steve Naroffb29b4272008-04-14 22:03:09 +00001715Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001716 // Create a new string expression.
1717 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001718 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001719 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001720 Expr *Replacement = new (*Context) StringLiteral(*Context,StrEncoding.c_str(),
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001721 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001722 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001723 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001724
Chris Lattner07506182007-11-30 22:53:43 +00001725 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001726 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001727 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001728}
1729
Steve Naroffb29b4272008-04-14 22:03:09 +00001730Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001731 if (!SelGetUidFunctionDecl)
1732 SynthSelGetUidFunctionDecl();
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);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001737 SelExprs.push_back(new (*Context) StringLiteral((*Context),
1738 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001739 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001740 false, argType, SourceLocation(),
1741 SourceLocation()));
1742 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1743 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001744 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001745 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001746 return SelExp;
1747}
1748
Steve Naroffb29b4272008-04-14 22:03:09 +00001749CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001750 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001751 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001752 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001753
1754 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001755 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001756
1757 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001758 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001759 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1760 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001761
1762 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001763
Steve Naroff934f2762007-10-24 22:48:43 +00001764 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1765}
1766
Steve Naroffd5255f52007-11-01 13:24:47 +00001767static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1768 const char *&startRef, const char *&endRef) {
1769 while (startBuf < endBuf) {
1770 if (*startBuf == '<')
1771 startRef = startBuf; // mark the start.
1772 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001773 if (startRef && *startRef == '<') {
1774 endRef = startBuf; // mark the end.
1775 return true;
1776 }
1777 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001778 }
1779 startBuf++;
1780 }
1781 return false;
1782}
1783
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001784static void scanToNextArgument(const char *&argRef) {
1785 int angle = 0;
1786 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1787 if (*argRef == '<')
1788 angle++;
1789 else if (*argRef == '>')
1790 angle--;
1791 argRef++;
1792 }
1793 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1794}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001795
Steve Naroffb29b4272008-04-14 22:03:09 +00001796bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001797
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001798 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001799 return true;
1800
Steve Naroffd5255f52007-11-01 13:24:47 +00001801 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001802 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001804 return true; // we have "Class <Protocol> *".
1805 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001806 return false;
1807}
1808
Steve Naroff4f95b752008-07-29 18:15:38 +00001809void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1810 QualType Type = E->getType();
1811 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001812 SourceLocation Loc, EndLoc;
1813
1814 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1815 Loc = ECE->getLParenLoc();
1816 EndLoc = ECE->getRParenLoc();
1817 } else {
1818 Loc = E->getLocStart();
1819 EndLoc = E->getLocEnd();
1820 }
1821 // This will defend against trying to rewrite synthesized expressions.
1822 if (Loc.isInvalid() || EndLoc.isInvalid())
1823 return;
1824
Steve Naroff4f95b752008-07-29 18:15:38 +00001825 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001826 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001827 const char *startRef = 0, *endRef = 0;
1828 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1829 // Get the locations of the startRef, endRef.
1830 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1831 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1832 // Comment out the protocol references.
1833 InsertText(LessLoc, "/*", 2);
1834 InsertText(GreaterLoc, "*/", 2);
1835 }
1836 }
1837}
1838
Steve Naroffb29b4272008-04-14 22:03:09 +00001839void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001840 SourceLocation Loc;
1841 QualType Type;
1842 const FunctionTypeProto *proto = 0;
1843 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1844 Loc = VD->getLocation();
1845 Type = VD->getType();
1846 }
1847 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1848 Loc = FD->getLocation();
1849 // Check for ObjC 'id' and class types that have been adorned with protocol
1850 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1851 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1852 assert(funcType && "missing function type");
1853 proto = dyn_cast<FunctionTypeProto>(funcType);
1854 if (!proto)
1855 return;
1856 Type = proto->getResultType();
1857 }
1858 else
1859 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001860
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001861 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001862 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001863
1864 const char *endBuf = SM->getCharacterData(Loc);
1865 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001866 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001867 startBuf--; // scan backward (from the decl location) for return type.
1868 const char *startRef = 0, *endRef = 0;
1869 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1870 // Get the locations of the startRef, endRef.
1871 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1872 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1873 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001874 InsertText(LessLoc, "/*", 2);
1875 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001876 }
1877 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001878 if (!proto)
1879 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001880 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001881 const char *startBuf = SM->getCharacterData(Loc);
1882 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001883 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1884 if (needToScanForQualifiers(proto->getArgType(i))) {
1885 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001886
Steve Naroffd5255f52007-11-01 13:24:47 +00001887 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001888 // scan forward (from the decl location) for argument types.
1889 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001890 const char *startRef = 0, *endRef = 0;
1891 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1892 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001893 SourceLocation LessLoc =
1894 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1895 SourceLocation GreaterLoc =
1896 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001897 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001898 InsertText(LessLoc, "/*", 2);
1899 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001900 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001901 startBuf = ++endBuf;
1902 }
1903 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001904 // If the function name is derived from a macro expansion, then the
1905 // argument buffer will not follow the name. Need to speak with Chris.
1906 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001907 startBuf++; // scan forward (from the decl location) for argument types.
1908 startBuf++;
1909 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001910 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001911}
1912
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001913// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001914void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001915 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1916 llvm::SmallVector<QualType, 16> ArgTys;
1917 ArgTys.push_back(Context->getPointerType(
1918 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001919 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001920 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001921 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001922 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001923 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001924 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001925 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001926}
1927
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001928// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001929void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001930 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1931 llvm::SmallVector<QualType, 16> ArgTys;
1932 ArgTys.push_back(Context->getPointerType(
1933 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001934 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001935 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001936 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001937 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001938 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001939 SelGetProtoIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001940 FunctionDecl::Extern, false);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001941}
1942
Steve Naroffb29b4272008-04-14 22:03:09 +00001943void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001944 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001945 if (FD->getIdentifier() &&
1946 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001947 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001948 return;
1949 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001951}
1952
Steve Naroffc0a123c2008-03-11 17:37:02 +00001953// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001954void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001955 if (SuperContructorFunctionDecl)
1956 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001957 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001958 llvm::SmallVector<QualType, 16> ArgTys;
1959 QualType argT = Context->getObjCIdType();
1960 assert(!argT.isNull() && "Can't find 'id' type");
1961 ArgTys.push_back(argT);
1962 ArgTys.push_back(argT);
1963 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1964 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001965 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001966 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001967 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001968 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001969 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001970}
1971
Steve Naroff09b266e2007-10-30 23:14:51 +00001972// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001973void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001974 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1975 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001977 assert(!argT.isNull() && "Can't find 'id' type");
1978 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001980 assert(!argT.isNull() && "Can't find 'SEL' type");
1981 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001982 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001983 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001984 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001985 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001986 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001987 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001988 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00001989}
1990
Steve Naroff874e2322007-11-15 10:28:18 +00001991// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001992void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001993 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1994 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001995 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001996 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001997 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001998 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1999 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2000 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002002 assert(!argT.isNull() && "Can't find 'SEL' type");
2003 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002005 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002006 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002007 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002008 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002009 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002010 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002011}
2012
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002013// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002014void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002015 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2016 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002017 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002018 assert(!argT.isNull() && "Can't find 'id' type");
2019 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002021 assert(!argT.isNull() && "Can't find 'SEL' type");
2022 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002024 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002025 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002026 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002027 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002028 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002029 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002030}
2031
2032// SynthMsgSendSuperStretFunctionDecl -
2033// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002034void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002035 IdentifierInfo *msgSendIdent =
2036 &Context->Idents.get("objc_msgSendSuper_stret");
2037 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002038 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002039 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002040 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2042 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2043 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002044 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002045 assert(!argT.isNull() && "Can't find 'SEL' type");
2046 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002047 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002048 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002049 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002050 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002051 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002052 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002053 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002054}
2055
Steve Naroff1284db82008-05-08 22:02:18 +00002056// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002057void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002058 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2059 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002061 assert(!argT.isNull() && "Can't find 'id' type");
2062 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002063 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002064 assert(!argT.isNull() && "Can't find 'SEL' type");
2065 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002066 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002067 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002068 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002069 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002070 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002071 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002072 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002073}
2074
Steve Naroff09b266e2007-10-30 23:14:51 +00002075// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002076void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002077 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2078 llvm::SmallVector<QualType, 16> ArgTys;
2079 ArgTys.push_back(Context->getPointerType(
2080 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002082 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002083 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002084 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002085 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002086 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002087 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002088}
2089
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002090// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002091void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002092 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2093 llvm::SmallVector<QualType, 16> ArgTys;
2094 ArgTys.push_back(Context->getPointerType(
2095 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002096 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002097 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002098 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002099 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002100 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002101 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002102 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002103}
2104
Steve Naroffb29b4272008-04-14 22:03:09 +00002105Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002106 QualType strType = getConstantStringStructType();
2107
2108 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002109
2110 std::string tmpName = InFileName;
2111 unsigned i;
2112 for (i=0; i < tmpName.length(); i++) {
2113 char c = tmpName.at(i);
2114 // replace any non alphanumeric characters with '_'.
2115 if (!isalpha(c) && (c < '0' || c > '9'))
2116 tmpName[i] = '_';
2117 }
2118 S += tmpName;
2119 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002120 S += utostr(NumObjCStringLiterals++);
2121
Steve Naroffba92b2e2008-03-27 22:29:16 +00002122 Preamble += "static __NSConstantStringImpl " + S;
2123 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2124 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002125 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002126 std::string prettyBufS;
2127 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002128 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002129 Preamble += prettyBuf.str();
2130 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002131 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002132 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002133
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002134 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002135 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002136 VarDecl::Static);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002137 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2138 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2139 Context->getPointerType(DRE->getType()),
2140 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002141 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002142 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002143 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002144 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002145 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002146 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002147}
2148
Steve Naroffb29b4272008-04-14 22:03:09 +00002149ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002150 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002151 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002152
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002153 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2154 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002155 assert(PT);
2156 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2157 return IT->getDecl();
2158 }
2159 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002160}
2161
2162// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002163QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002164 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002165 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002166 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002167 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002168 QualType FieldTypes[2];
2169
2170 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002172 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002173 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002174
Steve Naroff874e2322007-11-15 10:28:18 +00002175 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002176 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002177 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002178 SourceLocation(), 0,
2179 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002180 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002181 }
Steve Naroff874e2322007-11-15 10:28:18 +00002182
Douglas Gregor44b43212008-12-11 16:49:14 +00002183 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002184 }
2185 return Context->getTagDeclType(SuperStructDecl);
2186}
2187
Steve Naroffb29b4272008-04-14 22:03:09 +00002188QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002189 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002190 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002191 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002192 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002193 QualType FieldTypes[4];
2194
2195 // struct objc_object *receiver;
2196 FieldTypes[0] = Context->getObjCIdType();
2197 // int flags;
2198 FieldTypes[1] = Context->IntTy;
2199 // char *str;
2200 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2201 // long length;
2202 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002203
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002204 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002205 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002206 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002207 ConstantStringDecl,
2208 SourceLocation(), 0,
2209 FieldTypes[i],
2210 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002211 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002212 }
2213
2214 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002215 }
2216 return Context->getTagDeclType(ConstantStringDecl);
2217}
2218
Steve Naroffb29b4272008-04-14 22:03:09 +00002219Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002220 if (!SelGetUidFunctionDecl)
2221 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002222 if (!MsgSendFunctionDecl)
2223 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002224 if (!MsgSendSuperFunctionDecl)
2225 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002226 if (!MsgSendStretFunctionDecl)
2227 SynthMsgSendStretFunctionDecl();
2228 if (!MsgSendSuperStretFunctionDecl)
2229 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002230 if (!MsgSendFpretFunctionDecl)
2231 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002232 if (!GetClassFunctionDecl)
2233 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002234 if (!GetMetaClassFunctionDecl)
2235 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002236
Steve Naroff874e2322007-11-15 10:28:18 +00002237 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002238 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2239 // May need to use objc_msgSend_stret() as well.
2240 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002241 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002243 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002244 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002245 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002246 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002247 }
Steve Naroff874e2322007-11-15 10:28:18 +00002248
Steve Naroff934f2762007-10-24 22:48:43 +00002249 // Synthesize a call to objc_msgSend().
2250 llvm::SmallVector<Expr*, 8> MsgExprs;
2251 IdentifierInfo *clsName = Exp->getClassName();
2252
2253 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2254 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002255 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2256 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002257 if (!strcmp(clsName->getName(), "super")) {
2258 MsgSendFlavor = MsgSendSuperFunctionDecl;
2259 if (MsgSendStretFlavor)
2260 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2261 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2262
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002263 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002264 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002265
2266 llvm::SmallVector<Expr*, 4> InitExprs;
2267
2268 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002269 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002270 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002271 Context->getObjCIdType(),
2272 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002273 llvm::SmallVector<Expr*, 8> ClsExprs;
2274 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002275 ClsExprs.push_back(new (*Context) StringLiteral(*Context,
2276 SuperDecl->getIdentifier()->getName(),
2277 SuperDecl->getIdentifier()->getLength(),
2278 false, argType, SourceLocation(),
2279 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002280 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2281 &ClsExprs[0],
2282 ClsExprs.size());
2283 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002284 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002285 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002286 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002287 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 // struct objc_super
2289 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002290 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002291
Steve Naroff23f41272008-03-11 18:14:26 +00002292 if (LangOpts.Microsoft) {
2293 SynthSuperContructorFunctionDecl();
2294 // Simulate a contructor call...
2295 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2296 superType, SourceLocation());
2297 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2298 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002299 // The code for super is a little tricky to prevent collision with
2300 // the structure definition in the header. The rewriter has it's own
2301 // internal definition (__rw_objc_super) that is uses. This is why
2302 // we need the cast below. For example:
2303 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2304 //
2305 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2306 Context->getPointerType(SuperRep->getType()),
2307 SourceLocation());
2308 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2309 SuperRep, Context->getPointerType(superType),
2310 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002311 } else {
2312 // (struct objc_super) { <exprs from above> }
2313 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2314 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002315 SourceLocation());
Chris Lattner418f6c72008-10-26 23:43:26 +00002316 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2317 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002318 // struct objc_super *
2319 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2320 Context->getPointerType(SuperRep->getType()),
2321 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002322 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002323 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002324 } else {
2325 llvm::SmallVector<Expr*, 8> ClsExprs;
2326 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002327 ClsExprs.push_back(new (*Context) StringLiteral(*Context,
2328 clsName->getName(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002329 clsName->getLength(),
2330 false, argType, SourceLocation(),
2331 SourceLocation()));
2332 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2333 &ClsExprs[0],
2334 ClsExprs.size());
2335 MsgExprs.push_back(Cls);
2336 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002337 } else { // instance message.
2338 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002339
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002340 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002341 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002342 if (MsgSendStretFlavor)
2343 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002344 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2345
2346 llvm::SmallVector<Expr*, 4> InitExprs;
2347
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002348 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002349 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002350 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002351 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002352 SourceLocation()),
2353 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002354 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002355
2356 llvm::SmallVector<Expr*, 8> ClsExprs;
2357 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002358 ClsExprs.push_back(new (*Context) StringLiteral(*Context,
2359 SuperDecl->getIdentifier()->getName(),
2360 SuperDecl->getIdentifier()->getLength(),
2361 false, argType, SourceLocation(),
2362 SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002363 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002364 &ClsExprs[0],
2365 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002366 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002367 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002368 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002369 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002370 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002371 // struct objc_super
2372 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002373 Expr *SuperRep;
2374
2375 if (LangOpts.Microsoft) {
2376 SynthSuperContructorFunctionDecl();
2377 // Simulate a contructor call...
2378 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2379 superType, SourceLocation());
2380 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2381 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002382 // The code for super is a little tricky to prevent collision with
2383 // the structure definition in the header. The rewriter has it's own
2384 // internal definition (__rw_objc_super) that is uses. This is why
2385 // we need the cast below. For example:
2386 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2387 //
2388 SuperRep = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2389 Context->getPointerType(SuperRep->getType()),
2390 SourceLocation());
2391 SuperRep = new CStyleCastExpr(Context->getPointerType(superType),
2392 SuperRep, Context->getPointerType(superType),
2393 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002394 } else {
2395 // (struct objc_super) { <exprs from above> }
2396 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2397 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002398 SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002399 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2400 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002401 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002402 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002403 // Remove all type-casts because it may contain objc-style types; e.g.
2404 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002405 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002406 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002407 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002408 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002409 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002410 MsgExprs.push_back(recExpr);
2411 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002412 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002413 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002414 llvm::SmallVector<Expr*, 8> SelExprs;
2415 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002416 SelExprs.push_back(new (*Context) StringLiteral(*Context,
2417 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002418 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002419 false, argType, SourceLocation(),
2420 SourceLocation()));
2421 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2422 &SelExprs[0], SelExprs.size());
2423 MsgExprs.push_back(SelExp);
2424
2425 // Now push any user supplied arguments.
2426 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002427 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002428 // Make all implicit casts explicit...ICE comes in handy:-)
2429 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2430 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002431 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002432 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002433 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002434 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002435 }
2436 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002437 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002438 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002439 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002440 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002441 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002442 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002443 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002444 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002445 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002446 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002447 // We've transferred the ownership to MsgExprs. Null out the argument in
2448 // the original expression, since we will delete it below.
2449 Exp->setArg(i, 0);
2450 }
Steve Naroffab972d32007-11-04 22:37:50 +00002451 // Generate the funky cast.
2452 CastExpr *cast;
2453 llvm::SmallVector<QualType, 8> ArgTypes;
2454 QualType returnType;
2455
2456 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002457 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2458 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2459 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 ArgTypes.push_back(Context->getObjCIdType());
2461 ArgTypes.push_back(Context->getObjCSelType());
2462 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002463 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002464 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2466 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002467 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002468 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002469 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002470 const BlockPointerType *BPT = t->getAsBlockPointerType();
2471 t = Context->getPointerType(BPT->getPointeeType());
2472 }
Steve Naroff352336b2007-11-05 14:36:37 +00002473 ArgTypes.push_back(t);
2474 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2476 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002477 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002478 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002479 }
2480 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002481 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002482
2483 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002484 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2485 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002486
2487 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2488 // If we don't do this cast, we get the following bizarre warning/note:
2489 // xx.m:13: warning: function called through a non-compatible type
2490 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002491 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002492 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002493 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002494
Steve Naroffab972d32007-11-04 22:37:50 +00002495 // Now do the "normal" pointer to function cast.
2496 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002497 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002498 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002499 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002500 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002501 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002502
2503 // Don't forget the parens to enforce the proper binding.
2504 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2505
2506 const FunctionType *FT = msgSendType->getAsFunctionType();
2507 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2508 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002509 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510 if (MsgSendStretFlavor) {
2511 // We have the method which returns a struct/union. Must also generate
2512 // call to objc_msgSend_stret and hang both varieties on a conditional
2513 // expression which dictate which one to envoke depending on size of
2514 // method's return type.
2515
2516 // Create a reference to the objc_msgSend_stret() declaration.
2517 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2518 SourceLocation());
2519 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002520 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002521 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002522 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523 // Now do the "normal" pointer to function cast.
2524 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002525 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002526 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002527 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002528 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529
2530 // Don't forget the parens to enforce the proper binding.
2531 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2532
2533 FT = msgSendType->getAsFunctionType();
2534 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2535 FT->getResultType(), SourceLocation());
2536
2537 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002538 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2539 returnType.getAsOpaquePtr(),
2540 Context->getSizeType(),
2541 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2543 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2544 // For X86 it is more complicated and some kind of target specific routine
2545 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002546 unsigned IntSize =
2547 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2549 Context->IntTy,
2550 SourceLocation());
2551 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2552 BinaryOperator::LE,
2553 Context->IntTy,
2554 SourceLocation());
2555 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2556 ConditionalOperator *CondExpr =
2557 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002558 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002560 return ReplacingStmt;
2561}
2562
Steve Naroffb29b4272008-04-14 22:03:09 +00002563Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002564 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002565
Steve Naroffc77a6362008-12-04 16:24:46 +00002566 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002567 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002568 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002569
Steve Naroff4c3580e2008-12-04 23:50:32 +00002570 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002571 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002572}
2573
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002574/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2575/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002576Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002577 if (!GetProtocolFunctionDecl)
2578 SynthGetProtocolFunctionDecl();
2579 // Create a call to objc_getProtocol("ProtocolName").
2580 llvm::SmallVector<Expr*, 8> ProtoExprs;
2581 QualType argType = Context->getPointerType(Context->CharTy);
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002582 ProtoExprs.push_back(new (*Context)
2583 StringLiteral(*Context,
2584 Exp->getProtocol()->getNameAsCString(),
2585 strlen(Exp->getProtocol()->getNameAsCString()),
2586 false, argType, SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002587 SourceLocation()));
2588 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2589 &ProtoExprs[0],
2590 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002591 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002592 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002593 return ProtoExp;
2594
2595}
2596
Steve Naroffbaf58c32008-05-31 14:15:04 +00002597bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2598 const char *endBuf) {
2599 while (startBuf < endBuf) {
2600 if (*startBuf == '#') {
2601 // Skip whitespace.
2602 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2603 ;
2604 if (!strncmp(startBuf, "if", strlen("if")) ||
2605 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2606 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2607 !strncmp(startBuf, "define", strlen("define")) ||
2608 !strncmp(startBuf, "undef", strlen("undef")) ||
2609 !strncmp(startBuf, "else", strlen("else")) ||
2610 !strncmp(startBuf, "elif", strlen("elif")) ||
2611 !strncmp(startBuf, "endif", strlen("endif")) ||
2612 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2613 !strncmp(startBuf, "include", strlen("include")) ||
2614 !strncmp(startBuf, "import", strlen("import")) ||
2615 !strncmp(startBuf, "include_next", strlen("include_next")))
2616 return true;
2617 }
2618 startBuf++;
2619 }
2620 return false;
2621}
2622
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002624/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002625void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002626 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002628 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002629 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002630 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002631 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002632 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002633 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002634 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002635 SourceLocation LocStart = CDecl->getLocStart();
2636 SourceLocation LocEnd = CDecl->getLocEnd();
2637
2638 const char *startBuf = SM->getCharacterData(LocStart);
2639 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002640
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002641 // If no ivars and no root or if its root, directly or indirectly,
2642 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002643 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2644 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002645 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002646 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002647 return;
2648 }
2649
2650 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002652 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002653 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002654 if (LangOpts.Microsoft)
2655 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002656
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002657 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002658 const char *cursor = strchr(startBuf, '{');
2659 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002660 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002661 // If the buffer contains preprocessor directives, we do more fine-grained
2662 // rewrites. This is intended to fix code that looks like (which occurs in
2663 // NSURL.h, for example):
2664 //
2665 // #ifdef XYZ
2666 // @interface Foo : NSObject
2667 // #else
2668 // @interface FooBar : NSObject
2669 // #endif
2670 // {
2671 // int i;
2672 // }
2673 // @end
2674 //
2675 // This clause is segregated to avoid breaking the common case.
2676 if (BufferContainsPPDirectives(startBuf, cursor)) {
2677 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2678 CDecl->getClassLoc();
2679 const char *endHeader = SM->getCharacterData(L);
2680 endHeader += Lexer::MeasureTokenLength(L, *SM);
2681
Chris Lattner3db6cae2008-07-21 18:19:38 +00002682 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002683 // advance to the end of the referenced protocols.
2684 while (endHeader < cursor && *endHeader != '>') endHeader++;
2685 endHeader++;
2686 }
2687 // rewrite the original header
2688 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2689 } else {
2690 // rewrite the original header *without* disturbing the '{'
2691 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2692 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002693 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002694 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002695 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002696 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002697 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002698 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002699
2700 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002701 SourceLocation OnePastCurly =
2702 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2703 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002704 }
2705 cursor++; // past '{'
2706
2707 // Now comment out any visibility specifiers.
2708 while (cursor < endBuf) {
2709 if (*cursor == '@') {
2710 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002711 // Skip whitespace.
2712 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2713 /*scan*/;
2714
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002715 // FIXME: presence of @public, etc. inside comment results in
2716 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002717 if (!strncmp(cursor, "public", strlen("public")) ||
2718 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002719 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002720 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002721 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002722 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002723 // FIXME: If there are cases where '<' is used in ivar declaration part
2724 // of user code, then scan the ivar list and use needToScanForQualifiers
2725 // for type checking.
2726 else if (*cursor == '<') {
2727 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002728 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002729 cursor = strchr(cursor, '>');
2730 cursor++;
2731 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002732 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002733 } else if (*cursor == '^') { // rewrite block specifier.
2734 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2735 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002736 }
Steve Narofffea763e82007-11-14 19:25:57 +00002737 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002738 }
Steve Narofffea763e82007-11-14 19:25:57 +00002739 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002740 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002741 } else { // we don't have any instance variables - insert super struct.
2742 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2743 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002744 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002745 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002746 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002747 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002748 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002749 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002750 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002751 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002752 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002753}
2754
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002757void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002758 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002759 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002760 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002761 const char *ClassName,
2762 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002763 if (MethodBegin == MethodEnd) return;
2764
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002765 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002766 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002767 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002768 SEL _cmd;
2769 char *method_types;
2770 void *_imp;
2771 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002772 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002773 Result += "\nstruct _objc_method {\n";
2774 Result += "\tSEL _cmd;\n";
2775 Result += "\tchar *method_types;\n";
2776 Result += "\tvoid *_imp;\n";
2777 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002778
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002779 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002780 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002781
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002782 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002783
2784 /* struct {
2785 struct _objc_method_list *next_method;
2786 int method_count;
2787 struct _objc_method method_list[];
2788 }
2789 */
2790 Result += "\nstatic struct {\n";
2791 Result += "\tstruct _objc_method_list *next_method;\n";
2792 Result += "\tint method_count;\n";
2793 Result += "\tstruct _objc_method method_list[";
2794 Result += utostr(MethodEnd-MethodBegin);
2795 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002796 Result += prefix;
2797 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2798 Result += "_METHODS_";
2799 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002800 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002801 Result += IsInstanceMethod ? "inst" : "cls";
2802 Result += "_meth\")))= ";
2803 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002804
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002805 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002806 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002807 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002808 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002809 Result += "\", \"";
2810 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002811 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002812 Result += MethodInternalNames[*MethodBegin];
2813 Result += "}\n";
2814 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2815 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002816 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002817 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002819 Result += "\", \"";
2820 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002821 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002822 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002823 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002824 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002825 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002826}
2827
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002828/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002829void RewriteObjC::
2830RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2831 const char *prefix,
2832 const char *ClassName,
2833 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002834 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002835 if (Protocols.empty()) return;
2836
2837 for (unsigned i = 0; i != Protocols.size(); i++) {
2838 ObjCProtocolDecl *PDecl = Protocols[i];
2839 // Output struct protocol_methods holder of method selector and type.
2840 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2841 /* struct protocol_methods {
2842 SEL _cmd;
2843 char *method_types;
2844 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002845 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002846 Result += "\nstruct protocol_methods {\n";
2847 Result += "\tSEL _cmd;\n";
2848 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002849 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002850
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002851 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002852 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002853 // Do not synthesize the protocol more than once.
2854 if (ObjCSynthesizedProtocols.count(PDecl))
2855 continue;
2856
2857 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2858 unsigned NumMethods = PDecl->getNumInstanceMethods();
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_INSTANCE_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_inst_meth\")))= "
2871 "{\n\t" + utostr(NumMethods) + "\n";
2872
2873 // Output instance methods declared in this protocol.
2874 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2875 E = PDecl->instmeth_end(); I != E; ++I) {
2876 if (I == PDecl->instmeth_begin())
2877 Result += "\t ,{{(SEL)\"";
2878 else
2879 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002880 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002881 std::string MethodTypeString;
2882 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2883 Result += "\", \"";
2884 Result += MethodTypeString;
2885 Result += "\"}\n";
2886 }
2887 Result += "\t }\n};\n";
2888 }
2889
2890 // Output class methods declared in this protocol.
2891 int NumMethods = PDecl->getNumClassMethods();
2892 if (NumMethods > 0) {
2893 /* struct _objc_protocol_method_list {
2894 int protocol_method_count;
2895 struct protocol_methods protocols[];
2896 }
2897 */
2898 Result += "\nstatic struct {\n";
2899 Result += "\tint protocol_method_count;\n";
2900 Result += "\tstruct protocol_methods protocols[";
2901 Result += utostr(NumMethods);
2902 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002903 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002904 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2905 "{\n\t";
2906 Result += utostr(NumMethods);
2907 Result += "\n";
2908
2909 // Output instance methods declared in this protocol.
2910 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2911 E = PDecl->classmeth_end(); I != E; ++I) {
2912 if (I == PDecl->classmeth_begin())
2913 Result += "\t ,{{(SEL)\"";
2914 else
2915 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002916 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002917 std::string MethodTypeString;
2918 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2919 Result += "\", \"";
2920 Result += MethodTypeString;
2921 Result += "\"}\n";
2922 }
2923 Result += "\t }\n};\n";
2924 }
2925
2926 // Output:
2927 /* struct _objc_protocol {
2928 // Objective-C 1.0 extensions
2929 struct _objc_protocol_extension *isa;
2930 char *protocol_name;
2931 struct _objc_protocol **protocol_list;
2932 struct _objc_protocol_method_list *instance_methods;
2933 struct _objc_protocol_method_list *class_methods;
2934 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002935 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002936 static bool objc_protocol = false;
2937 if (!objc_protocol) {
2938 Result += "\nstruct _objc_protocol {\n";
2939 Result += "\tstruct _objc_protocol_extension *isa;\n";
2940 Result += "\tchar *protocol_name;\n";
2941 Result += "\tstruct _objc_protocol **protocol_list;\n";
2942 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2943 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2944 Result += "};\n";
2945
2946 objc_protocol = true;
2947 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002948
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002949 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002950 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002951 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2952 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002953 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002954 Result += "\", 0, ";
2955 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2956 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002957 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002958 Result += ", ";
2959 }
2960 else
2961 Result += "0, ";
2962 if (PDecl->getNumClassMethods() > 0) {
2963 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002964 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002965 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002966 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002967 else
2968 Result += "0\n";
2969 Result += "};\n";
2970
2971 // Mark this protocol as having been generated.
2972 if (!ObjCSynthesizedProtocols.insert(PDecl))
2973 assert(false && "protocol already synthesized");
2974 }
2975 // Output the top lovel protocol meta-data for the class.
2976 /* struct _objc_protocol_list {
2977 struct _objc_protocol_list *next;
2978 int protocol_count;
2979 struct _objc_protocol *class_protocols[];
2980 }
2981 */
2982 Result += "\nstatic struct {\n";
2983 Result += "\tstruct _objc_protocol_list *next;\n";
2984 Result += "\tint protocol_count;\n";
2985 Result += "\tstruct _objc_protocol *class_protocols[";
2986 Result += utostr(Protocols.size());
2987 Result += "];\n} _OBJC_";
2988 Result += prefix;
2989 Result += "_PROTOCOLS_";
2990 Result += ClassName;
2991 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2992 "{\n\t0, ";
2993 Result += utostr(Protocols.size());
2994 Result += "\n";
2995
2996 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002997 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002998 Result += " \n";
2999
3000 for (unsigned i = 1; i != Protocols.size(); i++) {
3001 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003002 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003003 Result += "\n";
3004 }
3005 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003006}
3007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003008/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003009/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003010void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003012 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003013 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003014 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003015 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3016 CDecl = CDecl->getNextClassCategory())
3017 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3018 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003020 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003021 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003022 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003023
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003025 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003026 true, "CATEGORY_", FullCategoryName.c_str(),
3027 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003028
3029 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003030 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003031 false, "CATEGORY_", FullCategoryName.c_str(),
3032 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003033
3034 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003035 // Null CDecl is case of a category implementation with no category interface
3036 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003037 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003038 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003039
3040 /* struct _objc_category {
3041 char *category_name;
3042 char *class_name;
3043 struct _objc_method_list *instance_methods;
3044 struct _objc_method_list *class_methods;
3045 struct _objc_protocol_list *protocols;
3046 // Objective-C 1.0 extensions
3047 uint32_t size; // sizeof (struct _objc_category)
3048 struct _objc_property_list *instance_properties; // category's own
3049 // @property decl.
3050 };
3051 */
3052
3053 static bool objc_category = false;
3054 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003055 Result += "\nstruct _objc_category {\n";
3056 Result += "\tchar *category_name;\n";
3057 Result += "\tchar *class_name;\n";
3058 Result += "\tstruct _objc_method_list *instance_methods;\n";
3059 Result += "\tstruct _objc_method_list *class_methods;\n";
3060 Result += "\tstruct _objc_protocol_list *protocols;\n";
3061 Result += "\tunsigned int size;\n";
3062 Result += "\tstruct _objc_property_list *instance_properties;\n";
3063 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003064 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003065 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3067 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003068 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003069 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003070 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003071 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003073
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003074 if (IDecl->getNumInstanceMethods() > 0) {
3075 Result += "\t, (struct _objc_method_list *)"
3076 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3077 Result += FullCategoryName;
3078 Result += "\n";
3079 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003080 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003081 Result += "\t, 0\n";
3082 if (IDecl->getNumClassMethods() > 0) {
3083 Result += "\t, (struct _objc_method_list *)"
3084 "&_OBJC_CATEGORY_CLASS_METHODS_";
3085 Result += FullCategoryName;
3086 Result += "\n";
3087 }
3088 else
3089 Result += "\t, 0\n";
3090
Chris Lattner780f3292008-07-21 21:32:27 +00003091 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003092 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3093 Result += FullCategoryName;
3094 Result += "\n";
3095 }
3096 else
3097 Result += "\t, 0\n";
3098 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003099}
3100
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003101/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3102/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003103void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003104 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003105 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003106 if (ivar->isBitField()) {
3107 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3108 // place all bitfields at offset 0.
3109 Result += "0";
3110 } else {
3111 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003112 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003113 if (LangOpts.Microsoft)
3114 Result += "_IMPL";
3115 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003116 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003117 Result += ")";
3118 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003119}
3120
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003121//===----------------------------------------------------------------------===//
3122// Meta Data Emission
3123//===----------------------------------------------------------------------===//
3124
Steve Naroffb29b4272008-04-14 22:03:09 +00003125void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003126 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003127 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003128
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003129 // Explictly declared @interface's are already synthesized.
3130 if (CDecl->ImplicitInterfaceDecl()) {
3131 // FIXME: Implementation of a class with no @interface (legacy) doese not
3132 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003133 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003134 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003135
Chris Lattnerbe6df082007-12-12 07:56:42 +00003136 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003137 unsigned NumIvars = !IDecl->ivar_empty()
3138 ? IDecl->ivar_size()
3139 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003140 if (NumIvars > 0) {
3141 static bool objc_ivar = false;
3142 if (!objc_ivar) {
3143 /* struct _objc_ivar {
3144 char *ivar_name;
3145 char *ivar_type;
3146 int ivar_offset;
3147 };
3148 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "\nstruct _objc_ivar {\n";
3150 Result += "\tchar *ivar_name;\n";
3151 Result += "\tchar *ivar_type;\n";
3152 Result += "\tint ivar_offset;\n";
3153 Result += "};\n";
3154
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003155 objc_ivar = true;
3156 }
3157
Steve Naroff946a6932008-03-11 00:12:29 +00003158 /* struct {
3159 int ivar_count;
3160 struct _objc_ivar ivar_list[nIvars];
3161 };
3162 */
3163 Result += "\nstatic struct {\n";
3164 Result += "\tint ivar_count;\n";
3165 Result += "\tstruct _objc_ivar ivar_list[";
3166 Result += utostr(NumIvars);
3167 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003168 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003169 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003170 "{\n\t";
3171 Result += utostr(NumIvars);
3172 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003173
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003174 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003175 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003176 IVI = IDecl->ivar_begin();
3177 IVE = IDecl->ivar_end();
3178 } else {
3179 IVI = CDecl->ivar_begin();
3180 IVE = CDecl->ivar_end();
3181 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003182 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003183 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003184 Result += "\", \"";
3185 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003186 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003187 Result += StrEncoding;
3188 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003189 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003190 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003191 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003192 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003193 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003194 Result += "\", \"";
3195 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003196 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003197 Result += StrEncoding;
3198 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003199 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003200 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003201 }
3202
3203 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003204 }
3205
3206 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003207 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003208 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003209
3210 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003212 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003213
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003214 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003215 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003216 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003217
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003218
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003219 // Declaration of class/meta-class metadata
3220 /* struct _objc_class {
3221 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003222 const char *super_class_name;
3223 char *name;
3224 long version;
3225 long info;
3226 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003227 struct _objc_ivar_list *ivars;
3228 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003229 struct objc_cache *cache;
3230 struct objc_protocol_list *protocols;
3231 const char *ivar_layout;
3232 struct _objc_class_ext *ext;
3233 };
3234 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003235 static bool objc_class = false;
3236 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003237 Result += "\nstruct _objc_class {\n";
3238 Result += "\tstruct _objc_class *isa;\n";
3239 Result += "\tconst char *super_class_name;\n";
3240 Result += "\tchar *name;\n";
3241 Result += "\tlong version;\n";
3242 Result += "\tlong info;\n";
3243 Result += "\tlong instance_size;\n";
3244 Result += "\tstruct _objc_ivar_list *ivars;\n";
3245 Result += "\tstruct _objc_method_list *methods;\n";
3246 Result += "\tstruct objc_cache *cache;\n";
3247 Result += "\tstruct _objc_protocol_list *protocols;\n";
3248 Result += "\tconst char *ivar_layout;\n";
3249 Result += "\tstruct _objc_class_ext *ext;\n";
3250 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003251 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003252 }
3253
3254 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003255 ObjCInterfaceDecl *RootClass = 0;
3256 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003257 while (SuperClass) {
3258 RootClass = SuperClass;
3259 SuperClass = SuperClass->getSuperClass();
3260 }
3261 SuperClass = CDecl->getSuperClass();
3262
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003264 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003265 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003266 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003267 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003268 Result += "\"";
3269
3270 if (SuperClass) {
3271 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003272 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003274 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003275 Result += "\"";
3276 }
3277 else {
3278 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 Result += "\"";
3281 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003282 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003283 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003284 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003285 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003286 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003287 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003288 Result += "\n";
3289 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003290 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003292 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003293 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003294 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003295 Result += ",0,0\n";
3296 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003297 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003298 Result += "\t,0,0,0,0\n";
3299 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003300
3301 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003303 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003304 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003305 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307 if (SuperClass) {
3308 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003309 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003311 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003312 Result += "\"";
3313 }
3314 else {
3315 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003316 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003317 Result += "\"";
3318 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003319 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003320 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003321 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003322 Result += ",0";
3323 else {
3324 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003325 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003326 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003327 if (LangOpts.Microsoft)
3328 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003329 Result += ")";
3330 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003331 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003332 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003333 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003334 Result += "\n\t";
3335 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003336 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003337 Result += ",0";
3338 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003339 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003341 Result += ", 0\n\t";
3342 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003343 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003344 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003345 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003346 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003347 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003348 Result += ", 0,0\n";
3349 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003350 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003351 Result += ",0,0,0\n";
3352 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003353}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003354
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003355/// RewriteImplementations - This routine rewrites all method implementations
3356/// and emits meta-data.
3357
Steve Narofface66252008-11-13 20:07:04 +00003358void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003359 int ClsDefCount = ClassImplementation.size();
3360 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003361
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003362 // Rewrite implemented methods
3363 for (int i = 0; i < ClsDefCount; i++)
3364 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003365
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003366 for (int i = 0; i < CatDefCount; i++)
3367 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003368}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003369
Steve Narofface66252008-11-13 20:07:04 +00003370void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3371 int ClsDefCount = ClassImplementation.size();
3372 int CatDefCount = CategoryImplementation.size();
3373
Steve Naroff5df5b762008-05-07 21:23:49 +00003374 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003375 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003376 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003377 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003378 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003379
3380 // For each implemented category, write out all its meta data.
3381 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003382 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003383
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003384 // Write objc_symtab metadata
3385 /*
3386 struct _objc_symtab
3387 {
3388 long sel_ref_cnt;
3389 SEL *refs;
3390 short cls_def_cnt;
3391 short cat_def_cnt;
3392 void *defs[cls_def_cnt + cat_def_cnt];
3393 };
3394 */
3395
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 Result += "\nstruct _objc_symtab {\n";
3397 Result += "\tlong sel_ref_cnt;\n";
3398 Result += "\tSEL *refs;\n";
3399 Result += "\tshort cls_def_cnt;\n";
3400 Result += "\tshort cat_def_cnt;\n";
3401 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3402 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003403
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003404 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003405 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003406 Result += "\t0, 0, " + utostr(ClsDefCount)
3407 + ", " + utostr(CatDefCount) + "\n";
3408 for (int i = 0; i < ClsDefCount; i++) {
3409 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003410 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003411 Result += "\n";
3412 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 for (int i = 0; i < CatDefCount; i++) {
3415 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003417 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003418 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003419 Result += "\n";
3420 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003421
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003422 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003423
3424 // Write objc_module metadata
3425
3426 /*
3427 struct _objc_module {
3428 long version;
3429 long size;
3430 const char *name;
3431 struct _objc_symtab *symtab;
3432 }
3433 */
3434
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003435 Result += "\nstruct _objc_module {\n";
3436 Result += "\tlong version;\n";
3437 Result += "\tlong size;\n";
3438 Result += "\tconst char *name;\n";
3439 Result += "\tstruct _objc_symtab *symtab;\n";
3440 Result += "};\n\n";
3441 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003442 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003443 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3444 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003445 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003446
3447 if (LangOpts.Microsoft) {
3448 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003449 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003450 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3451 Result += "&_OBJC_MODULES;\n";
3452 Result += "#pragma data_seg(pop)\n\n";
3453 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003454}
Chris Lattner311ff022007-10-16 22:36:42 +00003455
Steve Naroff54055232008-10-27 17:20:55 +00003456std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3457 const char *funcName,
3458 std::string Tag) {
3459 const FunctionType *AFT = CE->getFunctionType();
3460 QualType RT = AFT->getResultType();
3461 std::string StructRef = "struct " + Tag;
3462 std::string S = "static " + RT.getAsString() + " __" +
3463 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003464
Steve Naroff54055232008-10-27 17:20:55 +00003465 BlockDecl *BD = CE->getBlockDecl();
3466
3467 if (isa<FunctionTypeNoProto>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003468 // No user-supplied arguments. Still need to pass in a pointer to the
3469 // block (to reference imported block decl refs).
3470 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003471 } else if (BD->param_empty()) {
3472 S += "(" + StructRef + " *__cself)";
3473 } else {
3474 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3475 assert(FT && "SynthesizeBlockFunc: No function proto");
3476 S += '(';
3477 // first add the implicit argument.
3478 S += StructRef + " *__cself, ";
3479 std::string ParamStr;
3480 for (BlockDecl::param_iterator AI = BD->param_begin(),
3481 E = BD->param_end(); AI != E; ++AI) {
3482 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003483 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003484 (*AI)->getType().getAsStringInternal(ParamStr);
3485 S += ParamStr;
3486 }
3487 if (FT->isVariadic()) {
3488 if (!BD->param_empty()) S += ", ";
3489 S += "...";
3490 }
3491 S += ')';
3492 }
3493 S += " {\n";
3494
3495 // Create local declarations to avoid rewriting all closure decl ref exprs.
3496 // First, emit a declaration for all "by ref" decls.
3497 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3498 E = BlockByRefDecls.end(); I != E; ++I) {
3499 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003500 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003501 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003502 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003503 }
3504 // Next, emit a declaration for all "by copy" declarations.
3505 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3506 E = BlockByCopyDecls.end(); I != E; ++I) {
3507 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003508 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003509 // Handle nested closure invocation. For example:
3510 //
3511 // void (^myImportedClosure)(void);
3512 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3513 //
3514 // void (^anotherClosure)(void);
3515 // anotherClosure = ^(void) {
3516 // myImportedClosure(); // import and invoke the closure
3517 // };
3518 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003519 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003520 S += "struct __block_impl *";
3521 else
3522 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003523 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003524 }
3525 std::string RewrittenStr = RewrittenBlockExprs[CE];
3526 const char *cstr = RewrittenStr.c_str();
3527 while (*cstr++ != '{') ;
3528 S += cstr;
3529 S += "\n";
3530 return S;
3531}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003532
Steve Naroff54055232008-10-27 17:20:55 +00003533std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3534 const char *funcName,
3535 std::string Tag) {
3536 std::string StructRef = "struct " + Tag;
3537 std::string S = "static void __";
3538
3539 S += funcName;
3540 S += "_block_copy_" + utostr(i);
3541 S += "(" + StructRef;
3542 S += "*dst, " + StructRef;
3543 S += "*src) {";
3544 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3545 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003546 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003547 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003548 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003549 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003550 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003551 }
3552 S += "\nstatic void __";
3553 S += funcName;
3554 S += "_block_dispose_" + utostr(i);
3555 S += "(" + StructRef;
3556 S += "*src) {";
3557 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3558 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003559 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003561 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003562 }
3563 S += "}\n";
3564 return S;
3565}
3566
3567std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3568 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003569 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003570 std::string Constructor = " " + Tag;
3571
3572 S += " {\n struct __block_impl impl;\n";
3573
3574 if (hasCopyDisposeHelpers)
3575 S += " void *copy;\n void *dispose;\n";
3576
3577 Constructor += "(void *fp";
3578
3579 if (hasCopyDisposeHelpers)
3580 Constructor += ", void *copyHelp, void *disposeHelp";
3581
3582 if (BlockDeclRefs.size()) {
3583 // Output all "by copy" declarations.
3584 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3585 E = BlockByCopyDecls.end(); I != E; ++I) {
3586 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003587 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003588 std::string ArgName = "_" + FieldName;
3589 // Handle nested closure invocation. For example:
3590 //
3591 // void (^myImportedBlock)(void);
3592 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3593 //
3594 // void (^anotherBlock)(void);
3595 // anotherBlock = ^(void) {
3596 // myImportedBlock(); // import and invoke the closure
3597 // };
3598 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003599 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003600 S += "struct __block_impl *";
3601 Constructor += ", void *" + ArgName;
3602 } else {
3603 (*I)->getType().getAsStringInternal(FieldName);
3604 (*I)->getType().getAsStringInternal(ArgName);
3605 Constructor += ", " + ArgName;
3606 }
3607 S += FieldName + ";\n";
3608 }
3609 // Output all "by ref" declarations.
3610 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3611 E = BlockByRefDecls.end(); I != E; ++I) {
3612 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003613 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003614 std::string ArgName = "_" + FieldName;
3615 // Handle nested closure invocation. For example:
3616 //
3617 // void (^myImportedBlock)(void);
3618 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3619 //
3620 // void (^anotherBlock)(void);
3621 // anotherBlock = ^(void) {
3622 // myImportedBlock(); // import and invoke the closure
3623 // };
3624 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003625 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003626 S += "struct __block_impl *";
3627 Constructor += ", void *" + ArgName;
3628 } else {
3629 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3630 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3631 Constructor += ", " + ArgName;
3632 }
3633 S += FieldName + "; // by ref\n";
3634 }
3635 // Finish writing the constructor.
3636 // FIXME: handle NSConcreteGlobalBlock.
3637 Constructor += ", int flags=0) {\n";
3638 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3639 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3640
3641 if (hasCopyDisposeHelpers)
3642 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3643
3644 // Initialize all "by copy" arguments.
3645 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3646 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003647 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003648 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003649 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003650 Constructor += Name + " = (struct __block_impl *)_";
3651 else
3652 Constructor += Name + " = _";
3653 Constructor += Name + ";\n";
3654 }
3655 // Initialize all "by ref" arguments.
3656 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3657 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003658 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003659 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003660 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003661 Constructor += Name + " = (struct __block_impl *)_";
3662 else
3663 Constructor += Name + " = _";
3664 Constructor += Name + ";\n";
3665 }
3666 } else {
3667 // Finish writing the constructor.
3668 // FIXME: handle NSConcreteGlobalBlock.
3669 Constructor += ", int flags=0) {\n";
3670 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3671 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3672 if (hasCopyDisposeHelpers)
3673 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3674 }
3675 Constructor += " ";
3676 Constructor += "}\n";
3677 S += Constructor;
3678 S += "};\n";
3679 return S;
3680}
3681
3682void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3683 const char *FunName) {
3684 // Insert closures that were part of the function.
3685 for (unsigned i = 0; i < Blocks.size(); i++) {
3686
3687 CollectBlockDeclRefInfo(Blocks[i]);
3688
3689 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3690
3691 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3692 ImportedBlockDecls.size() > 0);
3693
3694 InsertText(FunLocStart, CI.c_str(), CI.size());
3695
3696 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3697
3698 InsertText(FunLocStart, CF.c_str(), CF.size());
3699
3700 if (ImportedBlockDecls.size()) {
3701 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3702 InsertText(FunLocStart, HF.c_str(), HF.size());
3703 }
3704
3705 BlockDeclRefs.clear();
3706 BlockByRefDecls.clear();
3707 BlockByCopyDecls.clear();
3708 BlockCallExprs.clear();
3709 ImportedBlockDecls.clear();
3710 }
3711 Blocks.clear();
3712 RewrittenBlockExprs.clear();
3713}
3714
3715void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3716 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003717 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003718
3719 SynthesizeBlockLiterals(FunLocStart, FuncName);
3720}
3721
3722void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003723 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3724 //SourceLocation FunLocStart = MD->getLocStart();
3725 // FIXME: This hack works around a bug in Rewrite.InsertText().
3726 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003727 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003728 // Convert colons to underscores.
3729 std::string::size_type loc = 0;
3730 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3731 FuncName.replace(loc, 1, "_");
3732
3733 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3734}
3735
3736void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3737 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3738 CI != E; ++CI)
3739 if (*CI) {
3740 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3741 GetBlockDeclRefExprs(CBE->getBody());
3742 else
3743 GetBlockDeclRefExprs(*CI);
3744 }
3745 // Handle specific things.
3746 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3747 // FIXME: Handle enums.
3748 if (!isa<FunctionDecl>(CDRE->getDecl()))
3749 BlockDeclRefs.push_back(CDRE);
3750 return;
3751}
3752
3753void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3754 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3755 CI != E; ++CI)
3756 if (*CI) {
3757 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3758 GetBlockCallExprs(CBE->getBody());
3759 else
3760 GetBlockCallExprs(*CI);
3761 }
3762
3763 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3764 if (CE->getCallee()->getType()->isBlockPointerType()) {
3765 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3766 }
3767 }
3768 return;
3769}
3770
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003771Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003772 // Navigate to relevant type information.
3773 const char *closureName = 0;
3774 const BlockPointerType *CPT = 0;
3775
3776 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003777 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003778 CPT = DRE->getType()->getAsBlockPointerType();
3779 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003780 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003781 CPT = CDRE->getType()->getAsBlockPointerType();
3782 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003783 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003784 CPT = MExpr->getType()->getAsBlockPointerType();
3785 } else {
3786 assert(1 && "RewriteBlockClass: Bad type");
3787 }
3788 assert(CPT && "RewriteBlockClass: Bad type");
3789 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3790 assert(FT && "RewriteBlockClass: Bad type");
3791 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3792 // FTP will be null for closures that don't take arguments.
3793
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003794 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3795 SourceLocation(),
3796 &Context->Idents.get("__block_impl"));
3797 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003798
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003799 // Generate a funky cast.
3800 llvm::SmallVector<QualType, 8> ArgTypes;
3801
3802 // Push the block argument type.
3803 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003804 if (FTP) {
3805 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003806 E = FTP->arg_type_end(); I && (I != E); ++I) {
3807 QualType t = *I;
3808 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003809 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003810 const BlockPointerType *BPT = t->getAsBlockPointerType();
3811 t = Context->getPointerType(BPT->getPointeeType());
3812 }
3813 ArgTypes.push_back(t);
3814 }
Steve Naroff54055232008-10-27 17:20:55 +00003815 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003816 // Now do the pointer to function cast.
3817 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3818 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3819
3820 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003821
Steve Naroffb2f9e512008-11-03 23:29:32 +00003822 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003823 // Don't forget the parens to enforce the proper binding.
3824 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3825 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003826
Douglas Gregor44b43212008-12-11 16:49:14 +00003827 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3828 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003829 /*BitWidth=*/0, /*Mutable=*/true);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3831
Steve Naroffb2f9e512008-11-03 23:29:32 +00003832 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003833 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3834
3835 llvm::SmallVector<Expr*, 8> BlkExprs;
3836 // Add the implicit argument.
3837 BlkExprs.push_back(BlkCast);
3838 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003839 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3840 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003841 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003842 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003843 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3844 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003845}
3846
3847void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003848 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3849 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003850}
3851
3852void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3853 // FIXME: Add more elaborate code generation required by the ABI.
Steve Naroffdf8570d2009-02-02 17:19:26 +00003854 Expr *DerefExpr = new UnaryOperator(BDRE, UnaryOperator::Deref,
3855 Context->getPointerType(BDRE->getType()),
3856 SourceLocation());
3857 // Need parens to enforce precedence.
3858 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
3859 ReplaceStmt(BDRE, PE);
Steve Naroff54055232008-10-27 17:20:55 +00003860}
3861
Steve Naroffb2f9e512008-11-03 23:29:32 +00003862void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3863 SourceLocation LocStart = CE->getLParenLoc();
3864 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003865
3866 // Need to avoid trying to rewrite synthesized casts.
3867 if (LocStart.isInvalid())
3868 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003869 // Need to avoid trying to rewrite casts contained in macros.
3870 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3871 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003872
Steve Naroff54055232008-10-27 17:20:55 +00003873 const char *startBuf = SM->getCharacterData(LocStart);
3874 const char *endBuf = SM->getCharacterData(LocEnd);
3875
3876 // advance the location to startArgList.
3877 const char *argPtr = startBuf;
3878
3879 while (*argPtr++ && (argPtr < endBuf)) {
3880 switch (*argPtr) {
3881 case '^':
3882 // Replace the '^' with '*'.
3883 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3884 ReplaceText(LocStart, 1, "*", 1);
3885 break;
3886 }
3887 }
3888 return;
3889}
3890
3891void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3892 SourceLocation DeclLoc = FD->getLocation();
3893 unsigned parenCount = 0;
3894
3895 // We have 1 or more arguments that have closure pointers.
3896 const char *startBuf = SM->getCharacterData(DeclLoc);
3897 const char *startArgList = strchr(startBuf, '(');
3898
3899 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3900
3901 parenCount++;
3902 // advance the location to startArgList.
3903 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3904 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3905
3906 const char *argPtr = startArgList;
3907
3908 while (*argPtr++ && parenCount) {
3909 switch (*argPtr) {
3910 case '^':
3911 // Replace the '^' with '*'.
3912 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3913 ReplaceText(DeclLoc, 1, "*", 1);
3914 break;
3915 case '(':
3916 parenCount++;
3917 break;
3918 case ')':
3919 parenCount--;
3920 break;
3921 }
3922 }
3923 return;
3924}
3925
3926bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3927 const FunctionTypeProto *FTP;
3928 const PointerType *PT = QT->getAsPointerType();
3929 if (PT) {
3930 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3931 } else {
3932 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3933 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3934 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3935 }
3936 if (FTP) {
3937 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3938 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003939 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003940 return true;
3941 }
3942 return false;
3943}
3944
3945void RewriteObjC::GetExtentOfArgList(const char *Name,
3946 const char *&LParen, const char *&RParen) {
3947 const char *argPtr = strchr(Name, '(');
3948 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3949
3950 LParen = argPtr; // output the start.
3951 argPtr++; // skip past the left paren.
3952 unsigned parenCount = 1;
3953
3954 while (*argPtr && parenCount) {
3955 switch (*argPtr) {
3956 case '(': parenCount++; break;
3957 case ')': parenCount--; break;
3958 default: break;
3959 }
3960 if (parenCount) argPtr++;
3961 }
3962 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3963 RParen = argPtr; // output the end
3964}
3965
3966void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3967 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3968 RewriteBlockPointerFunctionArgs(FD);
3969 return;
3970 }
3971 // Handle Variables and Typedefs.
3972 SourceLocation DeclLoc = ND->getLocation();
3973 QualType DeclT;
3974 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3975 DeclT = VD->getType();
3976 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3977 DeclT = TDD->getUnderlyingType();
3978 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3979 DeclT = FD->getType();
3980 else
3981 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3982
3983 const char *startBuf = SM->getCharacterData(DeclLoc);
3984 const char *endBuf = startBuf;
3985 // scan backward (from the decl location) for the end of the previous decl.
3986 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3987 startBuf--;
3988
3989 // *startBuf != '^' if we are dealing with a pointer to function that
3990 // may take block argument types (which will be handled below).
3991 if (*startBuf == '^') {
3992 // Replace the '^' with '*', computing a negative offset.
3993 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3994 ReplaceText(DeclLoc, 1, "*", 1);
3995 }
3996 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3997 // Replace the '^' with '*' for arguments.
3998 DeclLoc = ND->getLocation();
3999 startBuf = SM->getCharacterData(DeclLoc);
4000 const char *argListBegin, *argListEnd;
4001 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4002 while (argListBegin < argListEnd) {
4003 if (*argListBegin == '^') {
4004 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4005 ReplaceText(CaretLoc, 1, "*", 1);
4006 }
4007 argListBegin++;
4008 }
4009 }
4010 return;
4011}
4012
4013void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4014 // Add initializers for any closure decl refs.
4015 GetBlockDeclRefExprs(Exp->getBody());
4016 if (BlockDeclRefs.size()) {
4017 // Unique all "by copy" declarations.
4018 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4019 if (!BlockDeclRefs[i]->isByRef())
4020 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4021 // Unique all "by ref" declarations.
4022 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4023 if (BlockDeclRefs[i]->isByRef()) {
4024 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4025 }
4026 // Find any imported blocks...they will need special attention.
4027 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004028 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004029 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004030 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4031 }
4032 }
4033}
4034
Steve Narofffa15fd92008-10-28 20:29:00 +00004035FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4036 IdentifierInfo *ID = &Context->Idents.get(name);
4037 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4038 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004039 ID, FType, FunctionDecl::Extern, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004040}
4041
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004042Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004043 Blocks.push_back(Exp);
4044
4045 CollectBlockDeclRefInfo(Exp);
4046 std::string FuncName;
4047
4048 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004049 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004050 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004051 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004052 // Convert colons to underscores.
4053 std::string::size_type loc = 0;
4054 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4055 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004056 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004058
4059 std::string BlockNumber = utostr(Blocks.size()-1);
4060
4061 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4062 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4063
4064 // Get a pointer to the function type so we can cast appropriately.
4065 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4066
4067 FunctionDecl *FD;
4068 Expr *NewRep;
4069
4070 // Simulate a contructor call...
4071 FD = SynthBlockInitFunctionDecl(Tag.c_str());
4072 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
4073
4074 llvm::SmallVector<Expr*, 4> InitExprs;
4075
Steve Narofffdc03722008-10-29 21:23:59 +00004076 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004077 FD = SynthBlockInitFunctionDecl(Func.c_str());
4078 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4079 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004080 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004081 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004082
4083 if (ImportedBlockDecls.size()) {
4084 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004085 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4086 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4087 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004088 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004089 InitExprs.push_back(castExpr);
4090
Steve Narofffa15fd92008-10-28 20:29:00 +00004091 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004092 FD = SynthBlockInitFunctionDecl(Buf.c_str());
4093 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4094 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004095 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004096 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004097 }
4098 // Add initializers for any closure decl refs.
4099 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004100 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004101 // Output all "by copy" declarations.
4102 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4103 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004104 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004105 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004106 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004107 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004108 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004109 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004110 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4111 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004112 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004113 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004114 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004115 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004116 }
Steve Narofffdc03722008-10-29 21:23:59 +00004117 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004118 }
4119 // Output all "by ref" declarations.
4120 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4121 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004122 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004123 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4124 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4125 Context->getPointerType(Exp->getType()),
4126 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004127 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004128 }
4129 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004130 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4131 FType, SourceLocation());
4132 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4133 Context->getPointerType(NewRep->getType()),
4134 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004135 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004136 BlockDeclRefs.clear();
4137 BlockByRefDecls.clear();
4138 BlockByCopyDecls.clear();
4139 ImportedBlockDecls.clear();
4140 return NewRep;
4141}
4142
4143//===----------------------------------------------------------------------===//
4144// Function Body / Expression rewriting
4145//===----------------------------------------------------------------------===//
4146
Steve Naroffc77a6362008-12-04 16:24:46 +00004147// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4148// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4149// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4150// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4151// Since the rewriter isn't capable of rewriting rewritten code, it's important
4152// we get this right.
4153void RewriteObjC::CollectPropertySetters(Stmt *S) {
4154 // Perform a bottom up traversal of all children.
4155 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4156 CI != E; ++CI)
4157 if (*CI)
4158 CollectPropertySetters(*CI);
4159
4160 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4161 if (BinOp->isAssignmentOp()) {
4162 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4163 PropSetters[PRE] = BinOp;
4164 }
4165 }
4166}
4167
Steve Narofffa15fd92008-10-28 20:29:00 +00004168Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4169 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4170 isa<DoStmt>(S) || isa<ForStmt>(S))
4171 Stmts.push_back(S);
4172 else if (isa<ObjCForCollectionStmt>(S)) {
4173 Stmts.push_back(S);
4174 ObjCBcLabelNo.push_back(++BcLabelCount);
4175 }
4176
4177 SourceRange OrigStmtRange = S->getSourceRange();
4178
4179 // Perform a bottom up rewrite of all children.
4180 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4181 CI != E; ++CI)
4182 if (*CI) {
4183 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4184 if (newStmt)
4185 *CI = newStmt;
4186 }
4187
4188 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4189 // Rewrite the block body in place.
4190 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4191
4192 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004193 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4194 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004195
4196 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4197 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004198 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004199 return blockTranscribed;
4200 }
4201 // Handle specific things.
4202 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4203 return RewriteAtEncode(AtEncode);
4204
4205 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4206 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4207
Steve Naroffc77a6362008-12-04 16:24:46 +00004208 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4209 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4210 if (BinOp) {
4211 // Because the rewriter doesn't allow us to rewrite rewritten code,
4212 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004213 DisableReplaceStmt = true;
4214 // Save the source range. Even if we disable the replacement, the
4215 // rewritten node will have been inserted into the tree. If the synthesized
4216 // node is at the 'end', the rewriter will fail. Consider this:
4217 // self.errorHandler = handler ? handler :
4218 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4219 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004220 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004221 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004222 //
4223 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4224 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4225 // to see the original expression). Consider this example:
4226 //
4227 // Foo *obj1, *obj2;
4228 //
4229 // obj1.i = [obj2 rrrr];
4230 //
4231 // 'BinOp' for the previous expression looks like:
4232 //
4233 // (BinaryOperator 0x231ccf0 'int' '='
4234 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4235 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4236 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4237 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4238 //
4239 // 'newStmt' represents the rewritten message expression. For example:
4240 //
4241 // (CallExpr 0x231d300 'id':'struct objc_object *'
4242 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4243 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4244 // (CStyleCastExpr 0x231d220 'void *'
4245 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4246 //
4247 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4248 // can be used as the setter argument. ReplaceStmt() will still 'see'
4249 // the original RHS (since we haven't altered BinOp).
4250 //
4251 // This implies the Rewrite* routines can no longer delete the original
4252 // node. As a result, we now leak the original AST nodes.
4253 //
Steve Naroffb619d952008-12-09 12:56:34 +00004254 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004255 } else {
4256 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004257 }
4258 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004259 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4260 return RewriteAtSelector(AtSelector);
4261
4262 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4263 return RewriteObjCStringLiteral(AtString);
4264
4265 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004266#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004267 // Before we rewrite it, put the original message expression in a comment.
4268 SourceLocation startLoc = MessExpr->getLocStart();
4269 SourceLocation endLoc = MessExpr->getLocEnd();
4270
4271 const char *startBuf = SM->getCharacterData(startLoc);
4272 const char *endBuf = SM->getCharacterData(endLoc);
4273
4274 std::string messString;
4275 messString += "// ";
4276 messString.append(startBuf, endBuf-startBuf+1);
4277 messString += "\n";
4278
4279 // FIXME: Missing definition of
4280 // InsertText(clang::SourceLocation, char const*, unsigned int).
4281 // InsertText(startLoc, messString.c_str(), messString.size());
4282 // Tried this, but it didn't work either...
4283 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004284#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004285 return RewriteMessageExpr(MessExpr);
4286 }
4287
4288 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4289 return RewriteObjCTryStmt(StmtTry);
4290
4291 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4292 return RewriteObjCSynchronizedStmt(StmtTry);
4293
4294 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4295 return RewriteObjCThrowStmt(StmtThrow);
4296
4297 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4298 return RewriteObjCProtocolExpr(ProtocolExp);
4299
4300 if (ObjCForCollectionStmt *StmtForCollection =
4301 dyn_cast<ObjCForCollectionStmt>(S))
4302 return RewriteObjCForCollectionStmt(StmtForCollection,
4303 OrigStmtRange.getEnd());
4304 if (BreakStmt *StmtBreakStmt =
4305 dyn_cast<BreakStmt>(S))
4306 return RewriteBreakStmt(StmtBreakStmt);
4307 if (ContinueStmt *StmtContinueStmt =
4308 dyn_cast<ContinueStmt>(S))
4309 return RewriteContinueStmt(StmtContinueStmt);
4310
4311 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4312 // and cast exprs.
4313 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4314 // FIXME: What we're doing here is modifying the type-specifier that
4315 // precedes the first Decl. In the future the DeclGroup should have
4316 // a separate type-specifier that we can rewrite.
4317 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4318
4319 // Blocks rewrite rules.
4320 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4321 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004322 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004323 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004324 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004325 RewriteBlockPointerDecl(ND);
4326 else if (ND->getType()->isFunctionPointerType())
4327 CheckFunctionPointerDecl(ND->getType(), ND);
4328 }
4329 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004330 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004331 RewriteBlockPointerDecl(TD);
4332 else if (TD->getUnderlyingType()->isFunctionPointerType())
4333 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4334 }
4335 }
4336 }
4337
4338 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4339 RewriteObjCQualifiedInterfaceTypes(CE);
4340
4341 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4342 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4343 assert(!Stmts.empty() && "Statement stack is empty");
4344 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4345 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4346 && "Statement stack mismatch");
4347 Stmts.pop_back();
4348 }
4349 // Handle blocks rewriting.
4350 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4351 if (BDRE->isByRef())
4352 RewriteBlockDeclRefExpr(BDRE);
4353 }
4354 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004355 if (CE->getCallee()->getType()->isBlockPointerType()) {
4356 Stmt *BlockCall = SynthesizeBlockCall(CE);
4357 ReplaceStmt(S, BlockCall);
4358 return BlockCall;
4359 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004360 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004361 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004362 RewriteCastExpr(CE);
4363 }
4364#if 0
4365 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4366 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4367 // Get the new text.
4368 std::string SStr;
4369 llvm::raw_string_ostream Buf(SStr);
4370 Replacement->printPretty(Buf);
4371 const std::string &Str = Buf.str();
4372
4373 printf("CAST = %s\n", &Str[0]);
4374 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4375 delete S;
4376 return Replacement;
4377 }
4378#endif
4379 // Return this stmt unmodified.
4380 return S;
4381}
4382
4383/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4384/// main file of the input.
4385void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004387 if (FD->isOverloadedOperator())
4388 return;
4389
Steve Narofffa15fd92008-10-28 20:29:00 +00004390 // Since function prototypes don't have ParmDecl's, we check the function
4391 // prototype. This enables us to rewrite function declarations and
4392 // definitions using the same code.
4393 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4394
4395 if (Stmt *Body = FD->getBody()) {
4396 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004397 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004398 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004399 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004400 CurrentBody = 0;
4401 if (PropParentMap) {
4402 delete PropParentMap;
4403 PropParentMap = 0;
4404 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004405 // This synthesizes and inserts the block "impl" struct, invoke function,
4406 // and any copy/dispose helper functions.
4407 InsertBlockLiteralsWithinFunction(FD);
4408 CurFunctionDef = 0;
4409 }
4410 return;
4411 }
4412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4413 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004414 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004415 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004416 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004417 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004418 CurrentBody = 0;
4419 if (PropParentMap) {
4420 delete PropParentMap;
4421 PropParentMap = 0;
4422 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004423 InsertBlockLiteralsWithinMethod(MD);
4424 CurMethodDef = 0;
4425 }
4426 }
4427 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4428 ClassImplementation.push_back(CI);
4429 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4430 CategoryImplementation.push_back(CI);
4431 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4432 RewriteForwardClassDecl(CD);
4433 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4434 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004435 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004436 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004437 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004438 CheckFunctionPointerDecl(VD->getType(), VD);
4439 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004440 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004441 RewriteCastExpr(CE);
4442 }
4443 }
4444 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004445 if (VD->getInit()) {
4446 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004447 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004448 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004449 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004450 CurrentBody = 0;
4451 if (PropParentMap) {
4452 delete PropParentMap;
4453 PropParentMap = 0;
4454 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004455 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004456 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004457 GlobalVarDecl = 0;
4458
4459 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004460 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004461 RewriteCastExpr(CE);
4462 }
4463 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004464 return;
4465 }
4466 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004467 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004468 RewriteBlockPointerDecl(TD);
4469 else if (TD->getUnderlyingType()->isFunctionPointerType())
4470 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4471 return;
4472 }
4473 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4474 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004475 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004476 e = RD->field_end(); i != e; ++i) {
4477 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004478 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004479 RewriteBlockPointerDecl(FD);
4480 }
4481 }
4482 return;
4483 }
4484 // Nothing yet.
4485}
4486
4487void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4488 // Get the top-level buffer that this corresponds to.
4489
4490 // Rewrite tabs if we care.
4491 //RewriteTabs();
4492
4493 if (Diags.hasErrorOccurred())
4494 return;
4495
4496 // Create the output file.
4497
4498 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4499 llvm::raw_ostream *OutFile;
4500 if (OutFileName == "-") {
4501 OutFile = &llvm::outs();
4502 } else if (!OutFileName.empty()) {
4503 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004504 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4505 // set binary mode (critical for Windoze)
4506 true,
4507 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004508 OwnedStream.reset(OutFile);
4509 } else if (InFileName == "-") {
4510 OutFile = &llvm::outs();
4511 } else {
4512 llvm::sys::Path Path(InFileName);
4513 Path.eraseSuffix();
4514 Path.appendSuffix("cpp");
4515 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004516 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4517 // set binary mode (critical for Windoze)
4518 true,
4519 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 OwnedStream.reset(OutFile);
4521 }
4522
4523 RewriteInclude();
4524
Chris Lattner2b2453a2009-01-17 06:22:33 +00004525 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004526 Preamble.c_str(), Preamble.size(), false);
4527
Steve Naroff0aab7962008-11-14 14:10:01 +00004528 if (ClassImplementation.size() || CategoryImplementation.size())
4529 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004530
4531 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4532 // we are done.
4533 if (const RewriteBuffer *RewriteBuf =
4534 Rewrite.getRewriteBufferFor(MainFileID)) {
4535 //printf("Changed:\n");
4536 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4537 } else {
4538 fprintf(stderr, "No changes\n");
4539 }
Steve Narofface66252008-11-13 20:07:04 +00004540
Steve Naroff0aab7962008-11-14 14:10:01 +00004541 if (ClassImplementation.size() || CategoryImplementation.size()) {
4542 // Rewrite Objective-c meta data*
4543 std::string ResultStr;
4544 SynthesizeMetaDataIntoBuffer(ResultStr);
4545 // Emit metadata.
4546 *OutFile << ResultStr;
4547 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004548 OutFile->flush();
4549}
4550