blob: e78bd6d356d780fb868616c3b5bc220d89763fcc [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
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner07506182007-11-30 22:53:43 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000024#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000030
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Chris Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000035 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000036 protected:
37
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000038 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000039 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000040 block, ... */
41 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
42 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
43 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000044 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000045 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000046 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000047 support routines */
48 BLOCK_BYREF_CURRENT_MAX = 256
49 };
50
51 enum {
52 BLOCK_NEEDS_FREE = (1 << 24),
53 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
54 BLOCK_HAS_CXX_OBJ = (1 << 26),
55 BLOCK_IS_GC = (1 << 27),
56 BLOCK_IS_GLOBAL = (1 << 28),
57 BLOCK_HAS_DESCRIPTOR = (1 << 29)
58 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000059 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000060
Chris Lattner2c64b7b2007-10-16 21:07:07 +000061 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000062 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000063 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000064 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000065 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000066 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000067 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000068 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000069 Stmt *CurrentBody;
70 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000071 std::string InFileName;
72 raw_ostream* OutFile;
73 std::string Preamble;
74
75 TypeDecl *ProtocolTypeDecl;
76 VarDecl *GlobalVarDecl;
77 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000078 // ObjC string constant support.
79 unsigned NumObjCStringLiterals;
80 VarDecl *ConstantStringClassReference;
81 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000082
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000083 // ObjC foreach break/continue generation support.
84 int BcLabelCount;
85
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000086 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000087 // Needed for super.
88 ObjCMethodDecl *CurMethodDef;
89 RecordDecl *SuperStructDecl;
90 RecordDecl *ConstantStringDecl;
91
92 FunctionDecl *MsgSendFunctionDecl;
93 FunctionDecl *MsgSendSuperFunctionDecl;
94 FunctionDecl *MsgSendStretFunctionDecl;
95 FunctionDecl *MsgSendSuperStretFunctionDecl;
96 FunctionDecl *MsgSendFpretFunctionDecl;
97 FunctionDecl *GetClassFunctionDecl;
98 FunctionDecl *GetMetaClassFunctionDecl;
99 FunctionDecl *GetSuperClassFunctionDecl;
100 FunctionDecl *SelGetUidFunctionDecl;
101 FunctionDecl *CFStringFunctionDecl;
102 FunctionDecl *SuperContructorFunctionDecl;
103 FunctionDecl *CurFunctionDef;
104 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000106 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
112 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000113 SmallVector<Stmt *, 32> Stmts;
114 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000115 // Remember all the @protocol(<expr>) expressions.
116 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000117
118 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000119
120 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000121 SmallVector<BlockExpr *, 32> Blocks;
122 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000123 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000124
John McCallf4b88a42012-03-10 09:33:50 +0000125 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Steve Naroff54055232008-10-27 17:20:55 +0000127 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000129 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000130 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000132 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000133 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000134 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
135
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
137
Steve Naroff4c3580e2008-12-04 23:50:32 +0000138 // This maps an original source AST to it's rewritten form. This allows
139 // us to avoid rewriting the same node twice (which is very uncommon).
140 // This is needed to support some of the exotic property rewriting.
141 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000142
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000143 // Needed for header files being rewritten
144 bool IsHeader;
145 bool SilenceRewriteMacroWarning;
146 bool objc_impl_method;
147
Steve Naroffb619d952008-12-09 12:56:34 +0000148 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000149 class DisableReplaceStmtScope {
150 RewriteObjC &R;
151 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000152
John McCall4b9c2d22011-11-06 09:01:30 +0000153 public:
154 DisableReplaceStmtScope(RewriteObjC &R)
155 : R(R), SavedValue(R.DisableReplaceStmt) {
156 R.DisableReplaceStmt = true;
157 }
158 ~DisableReplaceStmtScope() {
159 R.DisableReplaceStmt = SavedValue;
160 }
161 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000162 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner77cd2a02007-10-11 00:43:27 +0000164 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000167 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000168 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000169 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
170 if (!Class->isThisDeclarationADefinition()) {
171 RewriteForwardClassDecl(D);
172 break;
173 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000174 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000175
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000176 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
177 if (!Proto->isThisDeclarationADefinition()) {
178 RewriteForwardProtocolDecl(D);
179 break;
180 }
181 }
182
Chris Lattner682bf922009-03-29 16:50:03 +0000183 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000184 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000185 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000186 }
187 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000188 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000189 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000190 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000191 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000192
193 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000195 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000197 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000198 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Steve Naroff4c3580e2008-12-04 23:50:32 +0000200 if (ReplacingStmt)
201 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000202
Steve Naroffb619d952008-12-09 12:56:34 +0000203 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000204 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000205
Steve Naroff4c3580e2008-12-04 23:50:32 +0000206 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000207 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000208 ReplacedNodes[Old] = New;
209 return;
210 }
211 if (SilenceRewriteMacroWarning)
212 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000215 }
Steve Naroffb619d952008-12-09 12:56:34 +0000216
217 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000218 if (DisableReplaceStmt)
219 return;
220
Nick Lewycky7e749242010-10-31 21:07:24 +0000221 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000222 int Size = Rewrite.getRangeSize(SrcRange);
223 if (Size == -1) {
224 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
225 << Old->getSourceRange();
226 return;
227 }
228 // Get the new text.
229 std::string SStr;
230 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000231 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000232 const std::string &Str = S.str();
233
234 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000235 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000236 ReplacedNodes[Old] = New;
237 return;
238 }
239 if (SilenceRewriteMacroWarning)
240 return;
241 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
242 << Old->getSourceRange();
243 }
244
Chris Lattner5f9e2722011-07-23 10:55:15 +0000245 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000246 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000248 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000249 SilenceRewriteMacroWarning)
250 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000252 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattneraadaf782008-01-31 19:51:04 +0000255 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000256 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000257 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000258 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000259 SilenceRewriteMacroWarning)
260 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattneraadaf782008-01-31 19:51:04 +0000262 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattnerf04da132007-10-24 17:06:59 +0000265 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000266 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000267 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000268 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000269 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000270 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000271 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000272 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000273 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
274 ObjCImplementationDecl *IMD,
275 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000277 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000278 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
279 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000280 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
281 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000282 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000283 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000284 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
285 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000286 void RewriteForwardProtocolDecl(DeclGroupRef D);
287 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000288 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000289 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000290 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000291 void RewriteBlockPointerType(std::string& Str, QualType Type);
292 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000293 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000294 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000295 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000296 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000299 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000300 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000301 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000303 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000304 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000305 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000306 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000307 void RewriteTryReturnStmts(Stmt *S);
308 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000309 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000310 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000311 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000312 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
313 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000314 Stmt *RewriteBreakStmt(BreakStmt *S);
315 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000316 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000317
Steve Naroff54055232008-10-27 17:20:55 +0000318 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000319 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000320
Mike Stump1eb44332009-09-09 15:08:12 +0000321 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000322 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000323 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000324 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000325 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000326 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000327
328 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
329 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000330
331 virtual void Initialize(ASTContext &context) = 0;
332
333 // Metadata Rewriting.
334 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
335 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
336 StringRef prefix,
337 StringRef ClassName,
338 std::string &Result) = 0;
339 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
340 std::string &Result) = 0;
341 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
342 StringRef prefix,
343 StringRef ClassName,
344 std::string &Result) = 0;
345 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
346 std::string &Result) = 0;
347
348 // Rewriting ivar access
349 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
350 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
351 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000352
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000353 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000354 // rewriting routines on the new ASTs.
355 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
356 Expr **args, unsigned nargs,
357 SourceLocation StartLoc=SourceLocation(),
358 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000359 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
360 QualType msgSendType,
361 QualType returnType,
362 SmallVectorImpl<QualType> &ArgTypes,
363 SmallVectorImpl<Expr*> &MsgExprs,
364 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000365 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
366 SourceLocation StartLoc=SourceLocation(),
367 SourceLocation EndLoc=SourceLocation());
368
369 void SynthCountByEnumWithState(std::string &buf);
370 void SynthMsgSendFunctionDecl();
371 void SynthMsgSendSuperFunctionDecl();
372 void SynthMsgSendStretFunctionDecl();
373 void SynthMsgSendFpretFunctionDecl();
374 void SynthMsgSendSuperStretFunctionDecl();
375 void SynthGetClassFunctionDecl();
376 void SynthGetMetaClassFunctionDecl();
377 void SynthGetSuperClassFunctionDecl();
378 void SynthSelGetUidFunctionDecl();
379 void SynthSuperContructorFunctionDecl();
380
381 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000382 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000386 std::string SynthesizeBlockImpl(BlockExpr *CE,
387 std::string Tag, std::string Desc);
388 std::string SynthesizeBlockDescriptor(std::string DescTag,
389 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000391 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000392 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000393 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000395 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
396 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000397 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Fariborz Jahanian58457172011-12-05 18:43:13 +0000399 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000400 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000401 void WarnAboutReturnGotoStmts(Stmt *S);
402 void HasReturnStmts(Stmt *S, bool &hasReturns);
403 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
404 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
405 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
406
407 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000408 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000409 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000410 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000411 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000412 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 // We avoid calling Type::isBlockPointerType(), since it operates on the
415 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000416 bool isTopLevelBlockPointerType(QualType T) {
417 return isa<BlockPointerType>(T);
418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000420 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
421 /// to a function pointer type and upon success, returns true; false
422 /// otherwise.
423 bool convertBlockPointerToFunctionPointer(QualType &T) {
424 if (isTopLevelBlockPointerType(T)) {
425 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
426 T = Context->getPointerType(BPT->getPointeeType());
427 return true;
428 }
429 return false;
430 }
431
Fariborz Jahanian58457172011-12-05 18:43:13 +0000432 bool needToScanForQualifiers(QualType T);
433 QualType getSuperStructType();
434 QualType getConstantStringStructType();
435 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
436 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
437
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000438 void convertToUnqualifiedObjCType(QualType &T) {
439 if (T->isObjCQualifiedIdType())
440 T = Context->getObjCIdType();
441 else if (T->isObjCQualifiedClassType())
442 T = Context->getObjCClassType();
443 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000444 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
445 if (const ObjCObjectPointerType * OBJPT =
446 T->getAsObjCInterfacePointerType()) {
447 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
448 T = QualType(IFaceT, 0);
449 T = Context->getPointerType(T);
450 }
451 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000452 }
453
Steve Naroff54055232008-10-27 17:20:55 +0000454 // FIXME: This predicate seems like it would be useful to add to ASTContext.
455 bool isObjCType(QualType T) {
456 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff54055232008-10-27 17:20:55 +0000459 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff54055232008-10-27 17:20:55 +0000461 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
462 OCT == Context->getCanonicalType(Context->getObjCClassType()))
463 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Ted Kremenek6217b802009-07-29 21:53:49 +0000465 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000466 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000467 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000468 return true;
469 }
470 return false;
471 }
472 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000473 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000474 void GetExtentOfArgList(const char *Name, const char *&LParen,
475 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000476
Steve Naroff621edce2009-04-29 16:37:50 +0000477 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000478 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000479 if (From[i] == '"')
480 To += "\\\"";
481 else
482 To += From[i];
483 }
484 }
John McCalle23cf432010-12-14 08:05:40 +0000485
486 QualType getSimpleFunctionType(QualType result,
487 const QualType *args,
488 unsigned numArgs,
489 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000490 if (result == Context->getObjCInstanceType())
491 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000492 FunctionProtoType::ExtProtoInfo fpi;
493 fpi.Variadic = variadic;
494 return Context->getFunctionType(result, args, numArgs, fpi);
495 }
John McCall9d125032010-01-15 18:39:57 +0000496
Fariborz Jahanian58457172011-12-05 18:43:13 +0000497 // Helper function: create a CStyleCastExpr with trivial type source info.
498 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
499 CastKind Kind, Expr *E) {
500 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
501 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
502 SourceLocation(), SourceLocation());
503 }
504 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000505
506 class RewriteObjCFragileABI : public RewriteObjC {
507 public:
508
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512 D, LOpts,
513 silenceMacroWarn) {}
514
515 ~RewriteObjCFragileABI() {}
516 virtual void Initialize(ASTContext &context);
517
518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
526 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix,
528 StringRef ClassName,
529 std::string &Result);
530 virtual void RewriteObjCProtocolListMetaData(
531 const ObjCList<ObjCProtocolDecl> &Prots,
532 StringRef prefix, StringRef ClassName, std::string &Result);
533 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
534 std::string &Result);
535 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
536 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
537 std::string &Result);
538
539 // Rewriting ivar
540 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
541 std::string &Result);
542 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
543 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000544}
545
Mike Stump1eb44332009-09-09 15:08:12 +0000546void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000548 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000551 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000552 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000561 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000564}
565
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000569 if (DotPos == std::string::npos) {
570 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000571 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000578}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000579
Chris Lattner5f9e2722011-07-23 10:55:15 +0000580RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000581 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000585 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000587 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000588 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
589 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000590 "rewriter doesn't support user-specified control flow semantics "
591 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000592}
593
Eli Friedmanbce831b2009-05-18 22:29:17 +0000594ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000595 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000596 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000597 const LangOptions &LOpts,
598 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000599 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000600}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000601
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000602void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000603 Context = &context;
604 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000605 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000606 MsgSendFunctionDecl = 0;
607 MsgSendSuperFunctionDecl = 0;
608 MsgSendStretFunctionDecl = 0;
609 MsgSendSuperStretFunctionDecl = 0;
610 MsgSendFpretFunctionDecl = 0;
611 GetClassFunctionDecl = 0;
612 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000613 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000614 SelGetUidFunctionDecl = 0;
615 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000616 ConstantStringClassReference = 0;
617 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000618 CurMethodDef = 0;
619 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000620 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000621 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000622 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000623 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000624 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000625 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000626 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000627 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000628 PropParentMap = 0;
629 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000630 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000631 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000633 // Get the ID and start/end of the main file.
634 MainFileID = SM->getMainFileID();
635 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
636 MainFileStart = MainBuf->getBufferStart();
637 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000638
David Blaikie4e4d0842012-03-11 07:00:24 +0000639 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000640}
641
Chris Lattnerf04da132007-10-24 17:06:59 +0000642//===----------------------------------------------------------------------===//
643// Top Level Driver Code
644//===----------------------------------------------------------------------===//
645
Chris Lattner682bf922009-03-29 16:50:03 +0000646void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000647 if (Diags.hasErrorOccurred())
648 return;
649
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000650 // Two cases: either the decl could be in the main file, or it could be in a
651 // #included file. If the former, rewrite it now. If the later, check to see
652 // if we rewrote the #include/#import.
653 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000654 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000656 // If this is for a builtin, ignore it.
657 if (Loc.isInvalid()) return;
658
Steve Naroffebf2b562007-10-23 23:50:29 +0000659 // Look for built-in declarations that we need to refer during the rewrite.
660 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000661 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000662 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000663 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000664 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000665 ConstantStringClassReference = FVD;
666 return;
667 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000668 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
669 if (ID->isThisDeclarationADefinition())
670 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000671 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000672 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000674 if (PD->isThisDeclarationADefinition())
675 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000676 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
677 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000678 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
679 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000680 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000681 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
682 if (!IFace->isThisDeclarationADefinition()) {
683 SmallVector<Decl *, 8> DG;
684 SourceLocation StartLoc = IFace->getLocStart();
685 do {
686 if (isa<ObjCInterfaceDecl>(*DI) &&
687 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
688 StartLoc == (*DI)->getLocStart())
689 DG.push_back(*DI);
690 else
691 break;
692
Douglas Gregor7723fec2011-12-15 20:29:51 +0000693 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000694 } while (DI != DIEnd);
695 RewriteForwardClassDecl(DG);
696 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000697 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000698 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000699
700 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
701 if (!Proto->isThisDeclarationADefinition()) {
702 SmallVector<Decl *, 8> DG;
703 SourceLocation StartLoc = Proto->getLocStart();
704 do {
705 if (isa<ObjCProtocolDecl>(*DI) &&
706 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
707 StartLoc == (*DI)->getLocStart())
708 DG.push_back(*DI);
709 else
710 break;
711
712 ++DI;
713 } while (DI != DIEnd);
714 RewriteForwardProtocolDecl(DG);
715 continue;
716 }
717 }
718
Chris Lattner682bf922009-03-29 16:50:03 +0000719 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000720 ++DI;
721 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000722 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000726}
727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroffb29b4272008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000734 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000750 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffa0876e82008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000780 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000824 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000838 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000868 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000873 Setr += "0, ";
874 else
875 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000887}
Chris Lattner8a12c272007-10-11 18:38:32 +0000888
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000889static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
890 std::string &typedefString) {
891 typedefString += "#ifndef _REWRITER_typedef_";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
895 typedefString += ForwardDecl->getNameAsString();
896 typedefString += "\n";
897 typedefString += "typedef struct objc_object ";
898 typedefString += ForwardDecl->getNameAsString();
899 typedefString += ";\n#endif\n";
900}
901
Douglas Gregor375bb142011-12-27 22:43:10 +0000902void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000903 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000904 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000905 const char *startBuf = SM->getCharacterData(startLoc);
906 const char *semiPtr = strchr(startBuf, ';');
907 // Replace the @class with typedefs corresponding to the classes.
908 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
909}
910
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000911void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000912 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000913 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000914 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000915 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000916 // Translate to typedef's that forward reference structs with the same name
917 // as the class. As a convenience, we include the original declaration
918 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000919 typedefString += "// @class ";
920 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000921 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000922 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000923 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000924 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000925 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000926 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000927}
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000929void RewriteObjC::RewriteForwardClassDecl(
930 const llvm::SmallVector<Decl*, 8> &D) {
931 std::string typedefString;
932 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000933 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000934 if (i == 0) {
935 typedefString += "// @class ";
936 typedefString += ForwardDecl->getNameAsString();
937 typedefString += ";\n";
938 }
939 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000941 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000942}
943
Steve Naroffb29b4272008-04-14 22:03:09 +0000944void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000945 // When method is a synthesized one, such as a getter/setter there is
946 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000947 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000948 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000949 SourceLocation LocStart = Method->getLocStart();
950 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chandler Carruth64211622011-07-25 21:09:52 +0000952 if (SM->getExpansionLineNumber(LocEnd) >
953 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000954 InsertText(LocStart, "#if 0\n");
955 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000956 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000957 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000958 }
959}
960
Mike Stump1eb44332009-09-09 15:08:12 +0000961void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000962 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Benjamin Kramerd999b372010-02-14 14:14:16 +0000964 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000965 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000966}
967
Steve Naroffb29b4272008-04-14 22:03:09 +0000968void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000969 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Steve Naroff423cb562007-10-30 13:30:57 +0000971 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000972 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000974 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
975 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000976 RewriteProperty(*I);
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000977
Mike Stump1eb44332009-09-09 15:08:12 +0000978 for (ObjCCategoryDecl::instmeth_iterator
979 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000980 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000981 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000982 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000983 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000984 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000985 RewriteMethodDeclaration(*I);
986
Steve Naroff423cb562007-10-30 13:30:57 +0000987 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000988 ReplaceText(CatDecl->getAtEndRange().getBegin(),
989 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000990}
991
Steve Naroffb29b4272008-04-14 22:03:09 +0000992void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000993 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000994 assert(PDecl->isThisDeclarationADefinition());
995
Steve Naroff752d6ef2007-10-30 16:42:30 +0000996 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000997 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000998
999 for (ObjCProtocolDecl::instmeth_iterator
1000 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001001 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001002 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001003 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001004 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001005 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001006 RewriteMethodDeclaration(*I);
1007
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001008 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1009 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001010 RewriteProperty(*I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001011
Steve Naroff752d6ef2007-10-30 16:42:30 +00001012 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001013 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001014 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001015
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001016 // Must comment out @optional/@required
1017 const char *startBuf = SM->getCharacterData(LocStart);
1018 const char *endBuf = SM->getCharacterData(LocEnd);
1019 for (const char *p = startBuf; p < endBuf; p++) {
1020 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001021 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001022 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001024 }
1025 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001026 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001027 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001029 }
1030 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001031}
1032
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001033void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1034 SourceLocation LocStart = (*D.begin())->getLocStart();
1035 if (LocStart.isInvalid())
1036 llvm_unreachable("Invalid SourceLocation");
1037 // FIXME: handle forward protocol that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039}
1040
1041void
1042RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1043 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001044 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001045 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001046 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001047 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001048}
1049
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001050void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1051 const FunctionType *&FPRetType) {
1052 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001053 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001054 else if (T->isFunctionPointerType() ||
1055 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001056 // needs special handling, since pointer-to-functions have special
1057 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001058 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001059 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001061 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001062 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001063 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001064 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001065 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001066 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001067 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001068 }
1069 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001070 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001071}
1072
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001073void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1074 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001075 std::string &ResultStr) {
1076 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1077 const FunctionType *FPRetType = 0;
1078 ResultStr += "\nstatic ";
1079 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001080 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001082 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001083 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001085 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001086 NameStr += "_I_";
1087 else
1088 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001090 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001091 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001092
1093 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001094 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001095 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001096 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001099 {
1100 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 int len = selString.size();
1102 for (int i = 0; i < len; i++)
1103 if (selString[i] == ':')
1104 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001105 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001107 // Remember this name for metadata emission
1108 MethodInternalNames[OMD] = NameStr;
1109 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 // Rewrite arguments
1112 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001114 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001115 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001116 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001117 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001118 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001119 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001120 ResultStr += "struct ";
1121 }
1122 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001123 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001124 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001125 }
1126 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001127 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001128 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001131 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001134 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1136 E = OMD->param_end(); PI != E; ++PI) {
1137 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001138 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001139 if (PDecl->getType()->isObjCQualifiedIdType()) {
1140 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001141 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001142 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001143 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001144 QualType QT = PDecl->getType();
1145 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001146 (void)convertBlockPointerToFunctionPointer(QT);
1147 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001148 ResultStr += Name;
1149 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001151 if (OMD->isVariadic())
1152 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001153 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Steve Naroff76e429d2008-07-16 14:40:40 +00001155 if (FPRetType) {
1156 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Steve Naroff76e429d2008-07-16 14:40:40 +00001158 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001159 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001160 ResultStr += "(";
1161 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1162 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001163 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001164 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001165 ResultStr += ParamStr;
1166 }
1167 if (FT->isVariadic()) {
1168 if (FT->getNumArgs()) ResultStr += ", ";
1169 ResultStr += "...";
1170 }
1171 ResultStr += ")";
1172 } else {
1173 ResultStr += "()";
1174 }
1175 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001177void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001178 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1179 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001181 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001184 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1185 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001186 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001188 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001189 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001191 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001192
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001193 const char *startBuf = SM->getCharacterData(LocStart);
1194 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001195 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001199 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1200 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001201 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001202 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001204 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001206 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001208 const char *startBuf = SM->getCharacterData(LocStart);
1209 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001210 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001211 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001212 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001213 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001214 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001215 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001216 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001217 }
1218
Benjamin Kramerd999b372010-02-14 14:14:16 +00001219 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220}
1221
Steve Naroffb29b4272008-04-14 22:03:09 +00001222void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001223 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001224 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001225 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001226 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001227 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001228 ResultStr += "\n";
1229 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001230 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001231 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001232 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001233 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001234 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001235 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001236 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001237 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001238 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
1240 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001241 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001242 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001243 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001244 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001245 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001246 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001247 for (ObjCInterfaceDecl::classmeth_iterator
1248 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001249 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001250 RewriteMethodDeclaration(*I);
1251
Steve Naroff2feac5e2007-10-30 03:43:13 +00001252 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001253 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1254 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001255}
1256
John McCall4b9c2d22011-11-06 09:01:30 +00001257Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1258 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001259
John McCall4b9c2d22011-11-06 09:01:30 +00001260 // We just magically know some things about the structure of this
1261 // expression.
1262 ObjCMessageExpr *OldMsg =
1263 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1264 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001265
John McCall4b9c2d22011-11-06 09:01:30 +00001266 // Because the rewriter doesn't allow us to rewrite rewritten code,
1267 // we need to suppress rewriting the sub-statements.
1268 Expr *Base, *RHS;
1269 {
1270 DisableReplaceStmtScope S(*this);
1271
1272 // Rebuild the base expression if we have one.
1273 Base = 0;
1274 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1275 Base = OldMsg->getInstanceReceiver();
1276 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1277 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1278 }
1279
1280 // Rebuild the RHS.
1281 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1282 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1283 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1284 }
1285
1286 // TODO: avoid this copy.
1287 SmallVector<SourceLocation, 1> SelLocs;
1288 OldMsg->getSelectorLocs(SelLocs);
1289
Chad Rosier0774ba72012-01-06 20:05:14 +00001290 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001291 switch (OldMsg->getReceiverKind()) {
1292 case ObjCMessageExpr::Class:
1293 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1294 OldMsg->getValueKind(),
1295 OldMsg->getLeftLoc(),
1296 OldMsg->getClassReceiverTypeInfo(),
1297 OldMsg->getSelector(),
1298 SelLocs,
1299 OldMsg->getMethodDecl(),
1300 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001301 OldMsg->getRightLoc(),
1302 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001303 break;
1304
1305 case ObjCMessageExpr::Instance:
1306 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1307 OldMsg->getValueKind(),
1308 OldMsg->getLeftLoc(),
1309 Base,
1310 OldMsg->getSelector(),
1311 SelLocs,
1312 OldMsg->getMethodDecl(),
1313 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001314 OldMsg->getRightLoc(),
1315 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001316 break;
1317
1318 case ObjCMessageExpr::SuperClass:
1319 case ObjCMessageExpr::SuperInstance:
1320 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1321 OldMsg->getValueKind(),
1322 OldMsg->getLeftLoc(),
1323 OldMsg->getSuperLoc(),
1324 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1325 OldMsg->getSuperType(),
1326 OldMsg->getSelector(),
1327 SelLocs,
1328 OldMsg->getMethodDecl(),
1329 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001330 OldMsg->getRightLoc(),
1331 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001332 break;
1333 }
1334
1335 Stmt *Replacement = SynthMessageExpr(NewMsg);
1336 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1337 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001338}
1339
John McCall4b9c2d22011-11-06 09:01:30 +00001340Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1341 SourceRange OldRange = PseudoOp->getSourceRange();
1342
1343 // We just magically know some things about the structure of this
1344 // expression.
1345 ObjCMessageExpr *OldMsg =
1346 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1347
1348 // Because the rewriter doesn't allow us to rewrite rewritten code,
1349 // we need to suppress rewriting the sub-statements.
1350 Expr *Base = 0;
1351 {
1352 DisableReplaceStmtScope S(*this);
1353
1354 // Rebuild the base expression if we have one.
1355 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1356 Base = OldMsg->getInstanceReceiver();
1357 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1358 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001359 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001360 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001361
John McCall4b9c2d22011-11-06 09:01:30 +00001362 // Intentionally empty.
1363 SmallVector<SourceLocation, 1> SelLocs;
1364 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001365
Chad Rosier0774ba72012-01-06 20:05:14 +00001366 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001367 switch (OldMsg->getReceiverKind()) {
1368 case ObjCMessageExpr::Class:
1369 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1370 OldMsg->getValueKind(),
1371 OldMsg->getLeftLoc(),
1372 OldMsg->getClassReceiverTypeInfo(),
1373 OldMsg->getSelector(),
1374 SelLocs,
1375 OldMsg->getMethodDecl(),
1376 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001377 OldMsg->getRightLoc(),
1378 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001379 break;
1380
1381 case ObjCMessageExpr::Instance:
1382 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1383 OldMsg->getValueKind(),
1384 OldMsg->getLeftLoc(),
1385 Base,
1386 OldMsg->getSelector(),
1387 SelLocs,
1388 OldMsg->getMethodDecl(),
1389 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001390 OldMsg->getRightLoc(),
1391 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001392 break;
1393
1394 case ObjCMessageExpr::SuperClass:
1395 case ObjCMessageExpr::SuperInstance:
1396 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1397 OldMsg->getValueKind(),
1398 OldMsg->getLeftLoc(),
1399 OldMsg->getSuperLoc(),
1400 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1401 OldMsg->getSuperType(),
1402 OldMsg->getSelector(),
1403 SelLocs,
1404 OldMsg->getMethodDecl(),
1405 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001406 OldMsg->getRightLoc(),
1407 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001408 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001409 }
John McCall4b9c2d22011-11-06 09:01:30 +00001410
1411 Stmt *Replacement = SynthMessageExpr(NewMsg);
1412 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1413 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001414}
1415
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416/// SynthCountByEnumWithState - To print:
1417/// ((unsigned int (*)
1418/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001419/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001421/// "countByEnumeratingWithState:objects:count:"),
1422/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001423/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424///
Steve Naroffb29b4272008-04-14 22:03:09 +00001425void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001426 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1427 "id *, unsigned int))(void *)objc_msgSend)";
1428 buf += "\n\t\t";
1429 buf += "((id)l_collection,\n\t\t";
1430 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1431 buf += "\n\t\t";
1432 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001433 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001435
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1437/// statement to exit to its outer synthesized loop.
1438///
Steve Naroffb29b4272008-04-14 22:03:09 +00001439Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001440 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1441 return S;
1442 // replace break with goto __break_label
1443 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445 SourceLocation startLoc = S->getLocStart();
1446 buf = "goto __break_label_";
1447 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001448 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001449
1450 return 0;
1451}
1452
1453/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1454/// statement to continue with its inner synthesized loop.
1455///
Steve Naroffb29b4272008-04-14 22:03:09 +00001456Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001457 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1458 return S;
1459 // replace continue with goto __continue_label
1460 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001462 SourceLocation startLoc = S->getLocStart();
1463 buf = "goto __continue_label_";
1464 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001465 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001467 return 0;
1468}
1469
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001470/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001471/// It rewrites:
1472/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001474/// Into:
1475/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001477/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001478/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001480/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001481/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001482/// if (limit) {
1483/// unsigned long startMutations = *enumState.mutationsPtr;
1484/// do {
1485/// unsigned long counter = 0;
1486/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001487/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001489/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001490/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001492/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001493/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001494/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001496/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001497/// }
1498/// else
1499/// elem = nil;
1500/// }
1501///
Steve Naroffb29b4272008-04-14 22:03:09 +00001502Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001503 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001504 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001505 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001506 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001507 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001508 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001511 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001512 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001513 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514 std::string buf;
1515 buf = "\n{\n\t";
1516 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1517 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001518 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001519 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001520 if (ElementType->isObjCQualifiedIdType() ||
1521 ElementType->isObjCQualifiedInterfaceType())
1522 // Simply use 'id' for all qualified types.
1523 elementTypeAsString = "id";
1524 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001525 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001526 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001527 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001528 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001529 buf += elementName;
1530 buf += ";\n\t";
1531 }
Chris Lattner06767512008-04-08 05:52:18 +00001532 else {
1533 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001534 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001535 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1536 if (VD->getType()->isObjCQualifiedIdType() ||
1537 VD->getType()->isObjCQualifiedInterfaceType())
1538 // Simply use 'id' for all qualified types.
1539 elementTypeAsString = "id";
1540 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001541 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 // struct __objcFastEnumerationState enumState = { 0 };
1545 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001546 // id __rw_items[16];
1547 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001548 // id l_collection = (id)
1549 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001550 // Find start location of 'collection' the hard way!
1551 const char *startCollectionBuf = startBuf;
1552 startCollectionBuf += 3; // skip 'for'
1553 startCollectionBuf = strchr(startCollectionBuf, '(');
1554 startCollectionBuf++; // skip '('
1555 // find 'in' and skip it.
1556 while (*startCollectionBuf != ' ' ||
1557 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1558 (*(startCollectionBuf+3) != ' ' &&
1559 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1560 startCollectionBuf++;
1561 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
1563 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001564 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001566 SourceLocation rightParenLoc = S->getRParenLoc();
1567 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001568 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001572 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001574 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575 // ((unsigned int (*)
1576 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001577 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // "countByEnumeratingWithState:objects:count:"),
1580 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001581 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001582 buf += "unsigned long limit =\n\t\t";
1583 SynthCountByEnumWithState(buf);
1584 buf += ";\n\t";
1585 /// if (limit) {
1586 /// unsigned long startMutations = *enumState.mutationsPtr;
1587 /// do {
1588 /// unsigned long counter = 0;
1589 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001590 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001591 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001592 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 buf += "if (limit) {\n\t";
1594 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1595 buf += "do {\n\t\t";
1596 buf += "unsigned long counter = 0;\n\t\t";
1597 buf += "do {\n\t\t\t";
1598 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1599 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1600 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001601 buf += " = (";
1602 buf += elementTypeAsString;
1603 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001605 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001607 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001609 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001610 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001611 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001612 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 /// }
1614 /// else
1615 /// elem = nil;
1616 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001617 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001618 buf = ";\n\t";
1619 buf += "__continue_label_";
1620 buf += utostr(ObjCBcLabelNo.back());
1621 buf += ": ;";
1622 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623 buf += "} while (counter < limit);\n\t";
1624 buf += "} while (limit = ";
1625 SynthCountByEnumWithState(buf);
1626 buf += ");\n\t";
1627 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001628 buf += " = ((";
1629 buf += elementTypeAsString;
1630 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001631 buf += "__break_label_";
1632 buf += utostr(ObjCBcLabelNo.back());
1633 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 buf += "}\n\t";
1635 buf += "else\n\t\t";
1636 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001637 buf += " = ((";
1638 buf += elementTypeAsString;
1639 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001640 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001642 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001643 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001644 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001645 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001646 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001647 } else {
1648 /* Need to treat single statements specially. For example:
1649 *
1650 * for (A *a in b) if (stuff()) break;
1651 * for (A *a in b) xxxyy;
1652 *
1653 * The following code simply scans ahead to the semi to find the actual end.
1654 */
1655 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1656 const char *semiBuf = strchr(stmtBuf, ';');
1657 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001658 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001659 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001660 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001661 Stmts.pop_back();
1662 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001664}
1665
Mike Stump1eb44332009-09-09 15:08:12 +00001666/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001667/// This routine rewrites @synchronized(expr) stmt;
1668/// into:
1669/// objc_sync_enter(expr);
1670/// @try stmt @finally { objc_sync_exit(expr); }
1671///
Steve Naroffb29b4272008-04-14 22:03:09 +00001672Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001673 // Get the start location and compute the semi location.
1674 SourceLocation startLoc = S->getLocStart();
1675 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001677 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001678
1679 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001680 buf = "objc_sync_enter((id)";
1681 const char *lparenBuf = startBuf;
1682 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001683 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1685 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001686 // been rewritten! (which implies the SourceLocation's are invalid).
1687 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001688 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001689 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001690 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001691 buf = ");\n";
1692 // declare a new scope with two variables, _stack and _rethrow.
1693 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1694 buf += "int buf[18/*32-bit i386*/];\n";
1695 buf += "char *pointers[4];} _stack;\n";
1696 buf += "id volatile _rethrow = 0;\n";
1697 buf += "objc_exception_try_enter(&_stack);\n";
1698 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001699 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 startLoc = S->getSynchBody()->getLocEnd();
1701 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Steve Naroffc7089f12008-08-19 13:04:19 +00001703 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001704 SourceLocation lastCurlyLoc = startLoc;
1705 buf = "}\nelse {\n";
1706 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001707 buf += "}\n";
1708 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001709 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001710
1711 std::string syncBuf;
1712 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001713
1714 Expr *syncExpr = S->getSynchExpr();
1715 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1716 ? CK_BitCast :
1717 syncExpr->getType()->isBlockPointerType()
1718 ? CK_BlockPointerToObjCPointerCast
1719 : CK_CPointerToObjCPointerCast;
1720 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1721 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001722 std::string syncExprBufS;
1723 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00001724 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001725 syncBuf += syncExprBuf.str();
1726 syncBuf += ");";
1727
1728 buf += syncBuf;
1729 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001730 buf += "}\n";
1731 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Benjamin Kramerd999b372010-02-14 14:14:16 +00001733 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001734
1735 bool hasReturns = false;
1736 HasReturnStmts(S->getSynchBody(), hasReturns);
1737 if (hasReturns)
1738 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1739
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001740 return 0;
1741}
1742
Steve Naroffb85e77a2009-12-05 21:43:12 +00001743void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1744{
Steve Naroff8c565152008-12-05 17:03:39 +00001745 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001746 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001747 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001748 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001749
Steve Naroffb85e77a2009-12-05 21:43:12 +00001750 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001751 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001752 TryFinallyContainsReturnDiag);
1753 }
1754 return;
1755}
1756
Steve Naroffb85e77a2009-12-05 21:43:12 +00001757void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1758{
1759 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001760 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001761 if (*CI)
1762 HasReturnStmts(*CI, hasReturns);
1763
1764 if (isa<ReturnStmt>(S))
1765 hasReturns = true;
1766 return;
1767}
1768
1769void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1770 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001771 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001772 if (*CI) {
1773 RewriteTryReturnStmts(*CI);
1774 }
1775 if (isa<ReturnStmt>(S)) {
1776 SourceLocation startLoc = S->getLocStart();
1777 const char *startBuf = SM->getCharacterData(startLoc);
1778
1779 const char *semiBuf = strchr(startBuf, ';');
1780 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001781 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001782
1783 std::string buf;
1784 buf = "{ objc_exception_try_exit(&_stack); return";
1785
Benjamin Kramerd999b372010-02-14 14:14:16 +00001786 ReplaceText(startLoc, 6, buf);
1787 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001788 }
1789 return;
1790}
1791
1792void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1793 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001794 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001795 if (*CI) {
1796 RewriteSyncReturnStmts(*CI, syncExitBuf);
1797 }
1798 if (isa<ReturnStmt>(S)) {
1799 SourceLocation startLoc = S->getLocStart();
1800 const char *startBuf = SM->getCharacterData(startLoc);
1801
1802 const char *semiBuf = strchr(startBuf, ';');
1803 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001804 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001805
1806 std::string buf;
1807 buf = "{ objc_exception_try_exit(&_stack);";
1808 buf += syncExitBuf;
1809 buf += " return";
1810
Benjamin Kramerd999b372010-02-14 14:14:16 +00001811 ReplaceText(startLoc, 6, buf);
1812 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001813 }
1814 return;
1815}
1816
Steve Naroffb29b4272008-04-14 22:03:09 +00001817Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001818 // Get the start location and compute the semi location.
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Steve Naroff75730982007-11-07 04:08:17 +00001822 assert((*startBuf == '@') && "bogus @try location");
1823
1824 std::string buf;
1825 // declare a new scope with two variables, _stack and _rethrow.
1826 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1827 buf += "int buf[18/*32-bit i386*/];\n";
1828 buf += "char *pointers[4];} _stack;\n";
1829 buf += "id volatile _rethrow = 0;\n";
1830 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001831 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001832
Benjamin Kramerd999b372010-02-14 14:14:16 +00001833 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff75730982007-11-07 04:08:17 +00001835 startLoc = S->getTryBody()->getLocEnd();
1836 startBuf = SM->getCharacterData(startLoc);
1837
1838 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Steve Naroff75730982007-11-07 04:08:17 +00001840 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001841 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001842 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001843 buf = " /* @catch begin */ else {\n";
1844 buf += " id _caught = objc_exception_extract(&_stack);\n";
1845 buf += " objc_exception_try_enter (&_stack);\n";
1846 buf += " if (_setjmp(_stack.buf))\n";
1847 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1848 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001851 } else { /* no catch list */
1852 buf = "}\nelse {\n";
1853 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1854 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001855 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001856 }
Steve Naroff75730982007-11-07 04:08:17 +00001857 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001858 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1859 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001860 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001861
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001862 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001863 buf = "if ("; // we are generating code for the first catch clause
1864 else
1865 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001866 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001867 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Steve Naroff75730982007-11-07 04:08:17 +00001869 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Steve Naroff75730982007-11-07 04:08:17 +00001871 const char *lParenLoc = strchr(startBuf, '(');
1872
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001873 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001874 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001875 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001876 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1877 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001878 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001879 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001880 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Steve Naroffe12e6922008-02-01 20:02:07 +00001882 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001883 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001884 } else if (catchDecl) {
1885 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001886 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001887 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001888 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001889 } else if (const ObjCObjectPointerType *Ptr =
1890 t->getAs<ObjCObjectPointerType>()) {
1891 // Should be a pointer to a class.
1892 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1893 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001894 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001895 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001896 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001897 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001898 }
1899 }
1900 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001901 lastCatchBody = Catch->getCatchBody();
1902 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001903 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1904 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1905 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1906 assert((*rParenBuf == ')') && "bogus @catch paren location");
1907 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Mike Stump1eb44332009-09-09 15:08:12 +00001909 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001910 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001911 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001912 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001913 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001914 }
Steve Naroff75730982007-11-07 04:08:17 +00001915 }
1916 // Complete the catch list...
1917 if (lastCatchBody) {
1918 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001919 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1920 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Steve Naroff378f47a2008-09-11 15:29:03 +00001922 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001923 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001924 buf = "} /* last catch end */\n";
1925 buf += "else {\n";
1926 buf += " _rethrow = _caught;\n";
1927 buf += " objc_exception_try_exit(&_stack);\n";
1928 buf += "} } /* @catch end */\n";
1929 if (!S->getFinallyStmt())
1930 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Steve Naroff75730982007-11-07 04:08:17 +00001933 // Set lastCurlyLoc
1934 lastCurlyLoc = lastCatchBody->getLocEnd();
1935 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001937 startLoc = finalStmt->getLocStart();
1938 startBuf = SM->getCharacterData(startLoc);
1939 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Benjamin Kramerd999b372010-02-14 14:14:16 +00001941 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Steve Naroff75730982007-11-07 04:08:17 +00001943 Stmt *body = finalStmt->getFinallyBody();
1944 SourceLocation startLoc = body->getLocStart();
1945 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001946 assert(*SM->getCharacterData(startLoc) == '{' &&
1947 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001948 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001949 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001951 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001952 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001953 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001954 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff75730982007-11-07 04:08:17 +00001956 // Set lastCurlyLoc
1957 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroff8c565152008-12-05 17:03:39 +00001959 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001960 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001961 } else { /* no finally clause - make sure we synthesize an implicit one */
1962 buf = "{ /* implicit finally clause */\n";
1963 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1964 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1965 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001966 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001967
1968 // Now check for any return/continue/go statements within the @try.
1969 // The implicit finally clause won't called if the @try contains any
1970 // jump statements.
1971 bool hasReturns = false;
1972 HasReturnStmts(S->getTryBody(), hasReturns);
1973 if (hasReturns)
1974 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001975 }
1976 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001977 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001978 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001979 return 0;
1980}
1981
Mike Stump1eb44332009-09-09 15:08:12 +00001982// This can't be done with ReplaceStmt(S, ThrowExpr), since
1983// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001984// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001985Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001986 // Get the start location and compute the semi location.
1987 SourceLocation startLoc = S->getLocStart();
1988 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Steve Naroff2bd03922007-11-07 15:32:26 +00001990 assert((*startBuf == '@') && "bogus @throw location");
1991
1992 std::string buf;
1993 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001994 if (S->getThrowExpr())
1995 buf = "objc_exception_throw(";
1996 else // add an implicit argument
1997 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001999 // handle "@ throw" correctly.
2000 const char *wBuf = strchr(startBuf, 'w');
2001 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Steve Naroff2bd03922007-11-07 15:32:26 +00002004 const char *semiBuf = strchr(startBuf, ';');
2005 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002006 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002007 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002008 return 0;
2009}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002010
Steve Naroffb29b4272008-04-14 22:03:09 +00002011Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002012 // Create a new string expression.
2013 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002014 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002015 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002016 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002017 StringLiteral::Ascii, false,
2018 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002019 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner07506182007-11-30 22:53:43 +00002021 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002022 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002023 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002024}
2025
Steve Naroffb29b4272008-04-14 22:03:09 +00002026Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002027 if (!SelGetUidFunctionDecl)
2028 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002029 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2030 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002031 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002032 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002033 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002034 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002035 StringLiteral::Ascii, false,
2036 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002037 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2038 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002039 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002040 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002041 return SelExp;
2042}
2043
Steve Naroffb29b4272008-04-14 22:03:09 +00002044CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002045 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2046 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002047 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002048 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroffebf2b562007-10-23 23:50:29 +00002050 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002051 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2052 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroffebf2b562007-10-23 23:50:29 +00002054 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002055 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002056 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002057 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002058 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall183700f2009-09-21 23:43:11 +00002060 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002062 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002063 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCallf89e55a2010-11-18 06:31:45 +00002064 FT->getCallResultType(*Context),
2065 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002066 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002067}
2068
Steve Naroffd5255f52007-11-01 13:24:47 +00002069static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2070 const char *&startRef, const char *&endRef) {
2071 while (startBuf < endBuf) {
2072 if (*startBuf == '<')
2073 startRef = startBuf; // mark the start.
2074 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002075 if (startRef && *startRef == '<') {
2076 endRef = startBuf; // mark the end.
2077 return true;
2078 }
2079 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002080 }
2081 startBuf++;
2082 }
2083 return false;
2084}
2085
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002086static void scanToNextArgument(const char *&argRef) {
2087 int angle = 0;
2088 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2089 if (*argRef == '<')
2090 angle++;
2091 else if (*argRef == '>')
2092 angle--;
2093 argRef++;
2094 }
2095 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2096}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002097
Steve Naroffb29b4272008-04-14 22:03:09 +00002098bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002099 if (T->isObjCQualifiedIdType())
2100 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002101 if (const PointerType *PT = T->getAs<PointerType>()) {
2102 if (PT->getPointeeType()->isObjCQualifiedIdType())
2103 return true;
2104 }
2105 if (T->isObjCObjectPointerType()) {
2106 T = T->getPointeeType();
2107 return T->isObjCQualifiedInterfaceType();
2108 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002109 if (T->isArrayType()) {
2110 QualType ElemTy = Context->getBaseElementType(T);
2111 return needToScanForQualifiers(ElemTy);
2112 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002113 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002114}
2115
Steve Naroff4f95b752008-07-29 18:15:38 +00002116void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2117 QualType Type = E->getType();
2118 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002119 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Steve Naroffcda658e2008-11-19 21:15:47 +00002121 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2122 Loc = ECE->getLParenLoc();
2123 EndLoc = ECE->getRParenLoc();
2124 } else {
2125 Loc = E->getLocStart();
2126 EndLoc = E->getLocEnd();
2127 }
2128 // This will defend against trying to rewrite synthesized expressions.
2129 if (Loc.isInvalid() || EndLoc.isInvalid())
2130 return;
2131
Steve Naroff4f95b752008-07-29 18:15:38 +00002132 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002133 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002134 const char *startRef = 0, *endRef = 0;
2135 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2136 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002137 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2138 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002139 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002140 InsertText(LessLoc, "/*");
2141 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002142 }
2143 }
2144}
2145
Steve Naroffb29b4272008-04-14 22:03:09 +00002146void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002147 SourceLocation Loc;
2148 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002149 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002150 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2151 Loc = VD->getLocation();
2152 Type = VD->getType();
2153 }
2154 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2155 Loc = FD->getLocation();
2156 // Check for ObjC 'id' and class types that have been adorned with protocol
2157 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002158 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002159 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002160 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161 if (!proto)
2162 return;
2163 Type = proto->getResultType();
2164 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002165 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2166 Loc = FD->getLocation();
2167 Type = FD->getType();
2168 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002169 else
2170 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002172 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 const char *endBuf = SM->getCharacterData(Loc);
2176 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002177 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002178 startBuf--; // scan backward (from the decl location) for return type.
2179 const char *startRef = 0, *endRef = 0;
2180 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2181 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002182 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2183 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002184 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002185 InsertText(LessLoc, "/*");
2186 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002187 }
2188 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 if (!proto)
2190 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002191 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002192 const char *startBuf = SM->getCharacterData(Loc);
2193 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002194 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2195 if (needToScanForQualifiers(proto->getArgType(i))) {
2196 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Steve Naroffd5255f52007-11-01 13:24:47 +00002198 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002199 // scan forward (from the decl location) for argument types.
2200 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002201 const char *startRef = 0, *endRef = 0;
2202 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2203 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002204 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002205 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002206 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002207 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002209 InsertText(LessLoc, "/*");
2210 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002211 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002212 startBuf = ++endBuf;
2213 }
2214 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002215 // If the function name is derived from a macro expansion, then the
2216 // argument buffer will not follow the name. Need to speak with Chris.
2217 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002218 startBuf++; // scan forward (from the decl location) for argument types.
2219 startBuf++;
2220 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002221 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002222}
2223
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002224void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2225 QualType QT = ND->getType();
2226 const Type* TypePtr = QT->getAs<Type>();
2227 if (!isa<TypeOfExprType>(TypePtr))
2228 return;
2229 while (isa<TypeOfExprType>(TypePtr)) {
2230 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2231 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2232 TypePtr = QT->getAs<Type>();
2233 }
2234 // FIXME. This will not work for multiple declarators; as in:
2235 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002236 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002237 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2238 const char *startBuf = SM->getCharacterData(DeclLoc);
2239 if (ND->getInit()) {
2240 std::string Name(ND->getNameAsString());
2241 TypeAsString += " " + Name + " = ";
2242 Expr *E = ND->getInit();
2243 SourceLocation startLoc;
2244 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2245 startLoc = ECE->getLParenLoc();
2246 else
2247 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002248 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002249 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002250 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002251 }
2252 else {
2253 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002254 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002255 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002256 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002257 }
2258}
2259
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002260// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002261void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002262 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002263 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002264 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002265 QualType getFuncType =
2266 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002267 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002268 SourceLocation(),
2269 SourceLocation(),
2270 SelGetUidIdent, getFuncType, 0,
2271 SC_Extern, SC_None);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002272}
2273
Steve Naroffb29b4272008-04-14 22:03:09 +00002274void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002275 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002276 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002277 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002278 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002279 return;
2280 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002281 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002282}
2283
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002284void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002285 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002286 const char *argPtr = TypeString.c_str();
2287 if (!strchr(argPtr, '^')) {
2288 Str += TypeString;
2289 return;
2290 }
2291 while (*argPtr) {
2292 Str += (*argPtr == '^' ? '*' : *argPtr);
2293 argPtr++;
2294 }
2295}
2296
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002297// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002298void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2299 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002300 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002301 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002302 const char *argPtr = TypeString.c_str();
2303 int paren = 0;
2304 while (*argPtr) {
2305 switch (*argPtr) {
2306 case '(':
2307 Str += *argPtr;
2308 paren++;
2309 break;
2310 case ')':
2311 Str += *argPtr;
2312 paren--;
2313 break;
2314 case '^':
2315 Str += '*';
2316 if (paren == 1)
2317 Str += VD->getNameAsString();
2318 break;
2319 default:
2320 Str += *argPtr;
2321 break;
2322 }
2323 argPtr++;
2324 }
2325}
2326
2327
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002328void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2329 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2330 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2331 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2332 if (!proto)
2333 return;
2334 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002335 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002336 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002337 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002338 FdStr += "(";
2339 unsigned numArgs = proto->getNumArgs();
2340 for (unsigned i = 0; i < numArgs; i++) {
2341 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002342 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002343 if (i+1 < numArgs)
2344 FdStr += ", ";
2345 }
2346 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002347 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002348 CurFunctionDeclToDeclareForBlock = 0;
2349}
2350
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002352void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002353 if (SuperContructorFunctionDecl)
2354 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002355 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002356 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002357 QualType argT = Context->getObjCIdType();
2358 assert(!argT.isNull() && "Can't find 'id' type");
2359 ArgTys.push_back(argT);
2360 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002361 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2362 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002363 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002364 SourceLocation(),
2365 SourceLocation(),
2366 msgSendIdent, msgSendType,
2367 0, SC_Extern, SC_None);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002368}
2369
Steve Naroff09b266e2007-10-30 23:14:51 +00002370// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002371void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002372 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002373 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002375 assert(!argT.isNull() && "Can't find 'id' type");
2376 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002380 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2381 &ArgTys[0], ArgTys.size(),
2382 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002383 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002384 SourceLocation(),
2385 SourceLocation(),
2386 msgSendIdent, msgSendType, 0,
2387 SC_Extern, SC_None);
Steve Naroff09b266e2007-10-30 23:14:51 +00002388}
2389
Steve Naroff874e2322007-11-15 10:28:18 +00002390// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002391void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002392 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002393 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002394 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002395 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002396 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002397 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2398 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2399 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002401 assert(!argT.isNull() && "Can't find 'SEL' type");
2402 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002403 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2404 &ArgTys[0], ArgTys.size(),
2405 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002406 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002407 SourceLocation(),
2408 SourceLocation(),
2409 msgSendIdent, msgSendType, 0,
2410 SC_Extern, SC_None);
Steve Naroff874e2322007-11-15 10:28:18 +00002411}
2412
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002413// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002414void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002417 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418 assert(!argT.isNull() && "Can't find 'id' type");
2419 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002420 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002421 assert(!argT.isNull() && "Can't find 'SEL' type");
2422 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002423 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002424 &ArgTys[0], ArgTys.size(),
2425 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002426 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002427 SourceLocation(),
2428 SourceLocation(),
2429 msgSendIdent, msgSendType, 0,
2430 SC_Extern, SC_None);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002431}
2432
Mike Stump1eb44332009-09-09 15:08:12 +00002433// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002434// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002435void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002436 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002437 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002438 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002439 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002440 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002441 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2443 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2444 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002445 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002446 assert(!argT.isNull() && "Can't find 'SEL' type");
2447 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002449 &ArgTys[0], ArgTys.size(),
2450 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002451 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002452 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002453 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002454 msgSendIdent,
2455 msgSendType, 0,
2456 SC_Extern, SC_None);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457}
2458
Steve Naroff1284db82008-05-08 22:02:18 +00002459// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002460void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002461 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002462 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002463 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002464 assert(!argT.isNull() && "Can't find 'id' type");
2465 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002467 assert(!argT.isNull() && "Can't find 'SEL' type");
2468 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002469 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2470 &ArgTys[0], ArgTys.size(),
2471 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002472 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002473 SourceLocation(),
2474 SourceLocation(),
2475 msgSendIdent, msgSendType, 0,
2476 SC_Extern, SC_None);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002477}
2478
Steve Naroff09b266e2007-10-30 23:14:51 +00002479// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002480void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002481 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002482 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002483 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002484 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2485 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002486 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002487 SourceLocation(),
2488 SourceLocation(),
2489 getClassIdent, getClassType, 0,
2490 SC_Extern, SC_None);
Steve Naroff09b266e2007-10-30 23:14:51 +00002491}
2492
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002493// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2494void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2495 IdentifierInfo *getSuperClassIdent =
2496 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002497 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002498 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002499 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2500 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002501 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002502 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002503 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002504 getSuperClassIdent,
2505 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002506 SC_Extern, SC_None);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002507}
2508
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002509// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002510void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002511 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002512 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002513 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002514 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2515 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002516 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002517 SourceLocation(),
2518 SourceLocation(),
2519 getClassIdent, getClassType,
2520 0, SC_Extern, SC_None);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002521}
2522
Steve Naroffb29b4272008-04-14 22:03:09 +00002523Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002524 QualType strType = getConstantStringStructType();
2525
2526 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002527
2528 std::string tmpName = InFileName;
2529 unsigned i;
2530 for (i=0; i < tmpName.length(); i++) {
2531 char c = tmpName.at(i);
2532 // replace any non alphanumeric characters with '_'.
2533 if (!isalpha(c) && (c < '0' || c > '9'))
2534 tmpName[i] = '_';
2535 }
2536 S += tmpName;
2537 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002538 S += utostr(NumObjCStringLiterals++);
2539
Steve Naroffba92b2e2008-03-27 22:29:16 +00002540 Preamble += "static __NSConstantStringImpl " + S;
2541 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2542 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002543 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002544 std::string prettyBufS;
2545 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002546 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002547 Preamble += prettyBuf.str();
2548 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002549 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002550
2551 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002552 SourceLocation(), &Context->Idents.get(S),
2553 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002554 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002555 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002556 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002557 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002558 VK_RValue, OK_Ordinary,
2559 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002560 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002561 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002562 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002563 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002564 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002565 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002566}
2567
Steve Naroff874e2322007-11-15 10:28:18 +00002568// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002569QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002570 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002571 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002572 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002573 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002574 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Steve Naroff874e2322007-11-15 10:28:18 +00002576 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002577 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002578 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002579 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002580
Steve Naroff874e2322007-11-15 10:28:18 +00002581 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002582 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002583 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002584 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002585 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002586 FieldTypes[i], 0,
2587 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002588 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002589 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002590 }
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Douglas Gregor838db382010-02-11 01:19:42 +00002592 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002593 }
2594 return Context->getTagDeclType(SuperStructDecl);
2595}
2596
Steve Naroffb29b4272008-04-14 22:03:09 +00002597QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002598 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002599 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002600 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002601 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002602 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002604 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002605 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002606 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002607 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002608 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002609 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002611 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002612
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002613 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002614 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002615 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2616 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002617 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002618 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002619 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002620 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002621 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002622 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002623 }
2624
Douglas Gregor838db382010-02-11 01:19:42 +00002625 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002626 }
2627 return Context->getTagDeclType(ConstantStringDecl);
2628}
2629
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002630CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2631 QualType msgSendType,
2632 QualType returnType,
2633 SmallVectorImpl<QualType> &ArgTypes,
2634 SmallVectorImpl<Expr*> &MsgExprs,
2635 ObjCMethodDecl *Method) {
2636 // Create a reference to the objc_msgSend_stret() declaration.
2637 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2638 false, msgSendType,
2639 VK_LValue, SourceLocation());
2640 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2641 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2642 Context->getPointerType(Context->VoidTy),
2643 CK_BitCast, STDRE);
2644 // Now do the "normal" pointer to function cast.
2645 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2646 Method ? Method->isVariadic() : false);
2647 castType = Context->getPointerType(castType);
2648 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2649 cast);
2650
2651 // Don't forget the parens to enforce the proper binding.
2652 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2653
2654 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002655 CallExpr *STCE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002656 FT->getResultType(), VK_RValue,
2657 SourceLocation());
2658 return STCE;
2659
2660}
2661
2662
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002663Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2664 SourceLocation StartLoc,
2665 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002666 if (!SelGetUidFunctionDecl)
2667 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002668 if (!MsgSendFunctionDecl)
2669 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002670 if (!MsgSendSuperFunctionDecl)
2671 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002672 if (!MsgSendStretFunctionDecl)
2673 SynthMsgSendStretFunctionDecl();
2674 if (!MsgSendSuperStretFunctionDecl)
2675 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002676 if (!MsgSendFpretFunctionDecl)
2677 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002678 if (!GetClassFunctionDecl)
2679 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002680 if (!GetSuperClassFunctionDecl)
2681 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002682 if (!GetMetaClassFunctionDecl)
2683 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Steve Naroff874e2322007-11-15 10:28:18 +00002685 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002686 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2687 // May need to use objc_msgSend_stret() as well.
2688 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002689 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2690 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002691 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002692 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002693 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002694 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Steve Naroff934f2762007-10-24 22:48:43 +00002697 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002698 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002699 switch (Exp->getReceiverKind()) {
2700 case ObjCMessageExpr::SuperClass: {
2701 MsgSendFlavor = MsgSendSuperFunctionDecl;
2702 if (MsgSendStretFlavor)
2703 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2704 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Douglas Gregor04badcf2010-04-21 00:45:42 +00002706 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Chris Lattner5f9e2722011-07-23 10:55:15 +00002708 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002709
Douglas Gregor04badcf2010-04-21 00:45:42 +00002710 // set the receiver to self, the first argument to all methods.
2711 InitExprs.push_back(
2712 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002713 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002714 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002715 false,
John McCallf89e55a2010-11-18 06:31:45 +00002716 Context->getObjCIdType(),
2717 VK_RValue,
2718 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002719 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Douglas Gregor04badcf2010-04-21 00:45:42 +00002721 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002722 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002723 QualType argType = Context->getPointerType(Context->CharTy);
2724 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002725 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002726 StringLiteral::Ascii, false,
2727 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002728 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2729 &ClsExprs[0],
2730 ClsExprs.size(),
2731 StartLoc,
2732 EndLoc);
2733 // (Class)objc_getClass("CurrentClass")
2734 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2735 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002736 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002737 ClsExprs.clear();
2738 ClsExprs.push_back(ArgExpr);
2739 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2740 &ClsExprs[0], ClsExprs.size(),
2741 StartLoc, EndLoc);
2742
2743 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2744 // To turn off a warning, type-cast to 'id'
2745 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2746 NoTypeInfoCStyleCastExpr(Context,
2747 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002748 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002749 // struct objc_super
2750 QualType superType = getSuperStructType();
2751 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002752
Francois Pichet62ec1f22011-09-17 17:15:52 +00002753 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002754 SynthSuperContructorFunctionDecl();
2755 // Simulate a contructor call...
2756 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002757 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002758 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002759 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002760 superType, VK_LValue,
2761 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 // The code for super is a little tricky to prevent collision with
2763 // the structure definition in the header. The rewriter has it's own
2764 // internal definition (__rw_objc_super) that is uses. This is why
2765 // we need the cast below. For example:
2766 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2767 //
John McCall2de56d12010-08-25 11:45:40 +00002768 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002770 VK_RValue, OK_Ordinary,
2771 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002772 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2773 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002774 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002775 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776 // (struct objc_super) { <exprs from above> }
2777 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002778 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002779 SourceLocation());
2780 TypeSourceInfo *superTInfo
2781 = Context->getTrivialTypeSourceInfo(superType);
2782 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002783 superType, VK_LValue,
2784 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002785 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002786 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002787 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002788 VK_RValue, OK_Ordinary,
2789 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002790 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002791 MsgExprs.push_back(SuperRep);
2792 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002793 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002794
2795 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002796 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797 QualType argType = Context->getPointerType(Context->CharTy);
2798 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002799 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 IdentifierInfo *clsName = Class->getIdentifier();
2801 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002802 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002803 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002804 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2806 &ClsExprs[0],
2807 ClsExprs.size(),
2808 StartLoc, EndLoc);
2809 MsgExprs.push_back(Cls);
2810 break;
2811 }
2812
2813 case ObjCMessageExpr::SuperInstance:{
2814 MsgSendFlavor = MsgSendSuperFunctionDecl;
2815 if (MsgSendStretFlavor)
2816 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2817 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2818 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002819 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820
2821 InitExprs.push_back(
2822 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002823 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002825 false,
John McCallf89e55a2010-11-18 06:31:45 +00002826 Context->getObjCIdType(),
2827 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 ); // set the 'receiver'.
2829
2830 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002831 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 QualType argType = Context->getPointerType(Context->CharTy);
2833 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002834 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002835 StringLiteral::Ascii, false, argType,
2836 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2838 &ClsExprs[0],
2839 ClsExprs.size(),
2840 StartLoc, EndLoc);
2841 // (Class)objc_getClass("CurrentClass")
2842 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2843 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002844 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 ClsExprs.clear();
2846 ClsExprs.push_back(ArgExpr);
2847 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2848 &ClsExprs[0], ClsExprs.size(),
2849 StartLoc, EndLoc);
2850
2851 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2852 // To turn off a warning, type-cast to 'id'
2853 InitExprs.push_back(
2854 // set 'super class', using class_getSuperclass().
2855 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002856 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 // struct objc_super
2858 QualType superType = getSuperStructType();
2859 Expr *SuperRep;
2860
Francois Pichet62ec1f22011-09-17 17:15:52 +00002861 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002862 SynthSuperContructorFunctionDecl();
2863 // Simulate a contructor call...
2864 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002865 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002866 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002867 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002868 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002869 // The code for super is a little tricky to prevent collision with
2870 // the structure definition in the header. The rewriter has it's own
2871 // internal definition (__rw_objc_super) that is uses. This is why
2872 // we need the cast below. For example:
2873 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2874 //
John McCall2de56d12010-08-25 11:45:40 +00002875 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002877 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002878 SourceLocation());
2879 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2880 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002881 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002882 } else {
2883 // (struct objc_super) { <exprs from above> }
2884 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002885 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 SourceLocation());
2887 TypeSourceInfo *superTInfo
2888 = Context->getTrivialTypeSourceInfo(superType);
2889 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002890 superType, VK_RValue, ILE,
2891 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 }
2893 MsgExprs.push_back(SuperRep);
2894 break;
2895 }
2896
2897 case ObjCMessageExpr::Instance: {
2898 // Remove all type-casts because it may contain objc-style types; e.g.
2899 // Foo<Proto> *.
2900 Expr *recExpr = Exp->getInstanceReceiver();
2901 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2902 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002903 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2904 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2905 ? CK_BlockPointerToObjCPointerCast
2906 : CK_CPointerToObjCPointerCast;
2907
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002909 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002910 MsgExprs.push_back(recExpr);
2911 break;
2912 }
2913 }
2914
Steve Naroffbeaf2992007-11-03 11:27:19 +00002915 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002916 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002917 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002918 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002919 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002920 StringLiteral::Ascii, false,
2921 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002922 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002923 &SelExprs[0], SelExprs.size(),
2924 StartLoc,
2925 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002926 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Steve Naroff934f2762007-10-24 22:48:43 +00002928 // Now push any user supplied arguments.
2929 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002930 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002931 // Make all implicit casts explicit...ICE comes in handy:-)
2932 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2933 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002934 QualType type = ICE->getType();
2935 if (needToScanForQualifiers(type))
2936 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002937 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002938 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002939 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002940 CastKind CK;
2941 if (SubExpr->getType()->isIntegralType(*Context) &&
2942 type->isBooleanType()) {
2943 CK = CK_IntegralToBoolean;
2944 } else if (type->isObjCObjectPointerType()) {
2945 if (SubExpr->getType()->isBlockPointerType()) {
2946 CK = CK_BlockPointerToObjCPointerCast;
2947 } else if (SubExpr->getType()->isPointerType()) {
2948 CK = CK_CPointerToObjCPointerCast;
2949 } else {
2950 CK = CK_BitCast;
2951 }
2952 } else {
2953 CK = CK_BitCast;
2954 }
2955
2956 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002957 }
2958 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002959 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002960 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002961 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002962 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002963 CastKind CK;
2964 if (userExpr->getType()->isIntegralType(*Context)) {
2965 CK = CK_IntegralToPointer;
2966 } else if (userExpr->getType()->isBlockPointerType()) {
2967 CK = CK_BlockPointerToObjCPointerCast;
2968 } else if (userExpr->getType()->isPointerType()) {
2969 CK = CK_CPointerToObjCPointerCast;
2970 } else {
2971 CK = CK_BitCast;
2972 }
John McCall9d125032010-01-15 18:39:57 +00002973 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002974 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002975 }
Mike Stump1eb44332009-09-09 15:08:12 +00002976 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002977 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002978 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2979 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002980 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002981 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002982 }
Steve Naroffab972d32007-11-04 22:37:50 +00002983 // Generate the funky cast.
2984 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002985 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002986 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Steve Naroffab972d32007-11-04 22:37:50 +00002988 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002989 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2990 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2991 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002992 ArgTypes.push_back(Context->getObjCIdType());
2993 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002994 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002995 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002996 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2997 E = OMD->param_end(); PI != E; ++PI) {
2998 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002999 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003000 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003001 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003002 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003003 ArgTypes.push_back(t);
3004 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003005 returnType = Exp->getType();
3006 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003007 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003008 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003010 }
3011 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003012 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Steve Naroffab972d32007-11-04 22:37:50 +00003014 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003015 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003016 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003017
Mike Stump1eb44332009-09-09 15:08:12 +00003018 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003019 // If we don't do this cast, we get the following bizarre warning/note:
3020 // xx.m:13: warning: function called through a non-compatible type
3021 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003022 cast = NoTypeInfoCStyleCastExpr(Context,
3023 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003024 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Steve Naroffab972d32007-11-04 22:37:50 +00003026 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003027 QualType castType =
3028 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3029 // If we don't have a method decl, force a variadic cast.
3030 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003031 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003032 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003033 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003034
3035 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003036 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003037
John McCall183700f2009-09-21 23:43:11 +00003038 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003039 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003040 FT->getResultType(), VK_RValue,
3041 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003042 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003043 if (MsgSendStretFlavor) {
3044 // We have the method which returns a struct/union. Must also generate
3045 // call to objc_msgSend_stret and hang both varieties on a conditional
3046 // expression which dictate which one to envoke depending on size of
3047 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00003048
3049 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3050 msgSendType, returnType,
3051 ArgTypes, MsgExprs,
3052 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003053
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003054 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003055 UnaryExprOrTypeTraitExpr *sizeofExpr =
3056 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3057 Context->getTrivialTypeSourceInfo(returnType),
3058 Context->getSizeType(), SourceLocation(),
3059 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003060 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3061 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3062 // For X86 it is more complicated and some kind of target specific routine
3063 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003064 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003065 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003066 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3067 llvm::APInt(IntSize, 8),
3068 Context->IntTy,
3069 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003070 BinaryOperator *lessThanExpr =
3071 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003072 VK_RValue, OK_Ordinary, SourceLocation(),
3073 false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003074 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003075 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003076 new (Context) ConditionalOperator(lessThanExpr,
3077 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003078 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003079 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003080 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3081 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003082 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003083 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003084 return ReplacingStmt;
3085}
3086
Steve Naroffb29b4272008-04-14 22:03:09 +00003087Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003088 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3089 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Steve Naroff934f2762007-10-24 22:48:43 +00003091 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003092 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003094 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003095 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003096}
3097
Steve Naroff621edce2009-04-29 16:37:50 +00003098// typedef struct objc_object Protocol;
3099QualType RewriteObjC::getProtocolType() {
3100 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003101 TypeSourceInfo *TInfo
3102 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003103 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003104 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003105 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003106 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003107 }
3108 return Context->getTypeDeclType(ProtocolTypeDecl);
3109}
3110
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003111/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003112/// a synthesized/forward data reference (to the protocol's metadata).
3113/// The forward references (and metadata) are generated in
3114/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003115Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003116 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3117 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003118 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003119 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003120 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003121 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3122 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003123 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003124 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003125 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003126 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003127 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003128 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003129 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003130 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003131 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003132 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003134}
3135
Mike Stump1eb44332009-09-09 15:08:12 +00003136bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003137 const char *endBuf) {
3138 while (startBuf < endBuf) {
3139 if (*startBuf == '#') {
3140 // Skip whitespace.
3141 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3142 ;
3143 if (!strncmp(startBuf, "if", strlen("if")) ||
3144 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3145 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3146 !strncmp(startBuf, "define", strlen("define")) ||
3147 !strncmp(startBuf, "undef", strlen("undef")) ||
3148 !strncmp(startBuf, "else", strlen("else")) ||
3149 !strncmp(startBuf, "elif", strlen("elif")) ||
3150 !strncmp(startBuf, "endif", strlen("endif")) ||
3151 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3152 !strncmp(startBuf, "include", strlen("include")) ||
3153 !strncmp(startBuf, "import", strlen("import")) ||
3154 !strncmp(startBuf, "include_next", strlen("include_next")))
3155 return true;
3156 }
3157 startBuf++;
3158 }
3159 return false;
3160}
3161
Fariborz Jahanian58457172011-12-05 18:43:13 +00003162/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003163/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003164void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003165 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003167 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003168 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003169 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003171 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003172 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003173 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003174 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003175 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Steve Narofffea763e82007-11-14 19:25:57 +00003177 const char *startBuf = SM->getCharacterData(LocStart);
3178 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003180 // If no ivars and no root or if its root, directly or indirectly,
3181 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003182 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003183 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003184 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003185 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003186 return;
3187 }
Mike Stump1eb44332009-09-09 15:08:12 +00003188
3189 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003190 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003191 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003193 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003194 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003195
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003196 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003197 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003198 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003199 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003200 // If the buffer contains preprocessor directives, we do more fine-grained
3201 // rewrites. This is intended to fix code that looks like (which occurs in
3202 // NSURL.h, for example):
3203 //
3204 // #ifdef XYZ
3205 // @interface Foo : NSObject
3206 // #else
3207 // @interface FooBar : NSObject
3208 // #endif
3209 // {
3210 // int i;
3211 // }
3212 // @end
3213 //
3214 // This clause is segregated to avoid breaking the common case.
3215 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003216 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003217 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003218 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003219 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003220
Chris Lattnercafeb352009-02-20 18:18:36 +00003221 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003222 // advance to the end of the referenced protocols.
3223 while (endHeader < cursor && *endHeader != '>') endHeader++;
3224 endHeader++;
3225 }
3226 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003227 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003228 } else {
3229 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003230 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003231 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003232 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003233 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003235 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003237 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Steve Narofffea763e82007-11-14 19:25:57 +00003239 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003240 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003241 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003242 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003243 }
3244 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Steve Narofffea763e82007-11-14 19:25:57 +00003246 // Now comment out any visibility specifiers.
3247 while (cursor < endBuf) {
3248 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003249 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003250 // Skip whitespace.
3251 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3252 /*scan*/;
3253
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003254 // FIXME: presence of @public, etc. inside comment results in
3255 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003256 if (!strncmp(cursor, "public", strlen("public")) ||
3257 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003258 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003259 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003260 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003261 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003262 // FIXME: If there are cases where '<' is used in ivar declaration part
3263 // of user code, then scan the ivar list and use needToScanForQualifiers
3264 // for type checking.
3265 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003266 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003267 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003268 cursor = strchr(cursor, '>');
3269 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003270 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003271 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003272 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003273 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003274 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003275 }
Steve Narofffea763e82007-11-14 19:25:57 +00003276 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003277 }
Steve Narofffea763e82007-11-14 19:25:57 +00003278 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003279 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003280 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003281 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003282 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003283 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003284 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003286 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003287 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003288 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003289 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003290 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003291 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003292}
3293
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003294//===----------------------------------------------------------------------===//
3295// Meta Data Emission
3296//===----------------------------------------------------------------------===//
3297
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003298
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003299/// RewriteImplementations - This routine rewrites all method implementations
3300/// and emits meta-data.
3301
Steve Narofface66252008-11-13 20:07:04 +00003302void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003303 int ClsDefCount = ClassImplementation.size();
3304 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003306 // Rewrite implemented methods
3307 for (int i = 0; i < ClsDefCount; i++)
3308 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003310 for (int i = 0; i < CatDefCount; i++)
3311 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003312}
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003314void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3315 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003316 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003317 assert(BlockByRefDeclNo.count(VD) &&
3318 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003319 if (def)
3320 ResultStr += "struct ";
3321 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003322 "_" + utostr(BlockByRefDeclNo[VD]) ;
3323}
3324
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003325static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3326 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3327 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3328 return false;
3329}
3330
Steve Naroff54055232008-10-27 17:20:55 +00003331std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003332 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003333 std::string Tag) {
3334 const FunctionType *AFT = CE->getFunctionType();
3335 QualType RT = AFT->getResultType();
3336 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003337 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003338 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003339
Steve Naroff54055232008-10-27 17:20:55 +00003340 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Douglas Gregor72564e72009-02-26 23:50:07 +00003342 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003343 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003344 // block (to reference imported block decl refs).
3345 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003346 } else if (BD->param_empty()) {
3347 S += "(" + StructRef + " *__cself)";
3348 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003349 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003350 assert(FT && "SynthesizeBlockFunc: No function proto");
3351 S += '(';
3352 // first add the implicit argument.
3353 S += StructRef + " *__cself, ";
3354 std::string ParamStr;
3355 for (BlockDecl::param_iterator AI = BD->param_begin(),
3356 E = BD->param_end(); AI != E; ++AI) {
3357 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003358 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003359 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003360 (void)convertBlockPointerToFunctionPointer(QT);
3361 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003362 S += ParamStr;
3363 }
3364 if (FT->isVariadic()) {
3365 if (!BD->param_empty()) S += ", ";
3366 S += "...";
3367 }
3368 S += ')';
3369 }
3370 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Steve Naroff54055232008-10-27 17:20:55 +00003372 // Create local declarations to avoid rewriting all closure decl ref exprs.
3373 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003374 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003375 E = BlockByRefDecls.end(); I != E; ++I) {
3376 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003378 std::string TypeString;
3379 RewriteByRefString(TypeString, Name, (*I));
3380 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003381 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003382 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003383 }
Steve Naroff54055232008-10-27 17:20:55 +00003384 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003385 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003386 E = BlockByCopyDecls.end(); I != E; ++I) {
3387 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003388 // Handle nested closure invocation. For example:
3389 //
3390 // void (^myImportedClosure)(void);
3391 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003392 //
Steve Naroff54055232008-10-27 17:20:55 +00003393 // void (^anotherClosure)(void);
3394 // anotherClosure = ^(void) {
3395 // myImportedClosure(); // import and invoke the closure
3396 // };
3397 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003398 if (isTopLevelBlockPointerType((*I)->getType())) {
3399 RewriteBlockPointerTypeVariable(S, (*I));
3400 S += " = (";
3401 RewriteBlockPointerType(S, (*I)->getType());
3402 S += ")";
3403 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3404 }
3405 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003406 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003407 QualType QT = (*I)->getType();
3408 if (HasLocalVariableExternalStorage(*I))
3409 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003410 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003411 S += Name + " = __cself->" +
3412 (*I)->getNameAsString() + "; // bound by copy\n";
3413 }
Steve Naroff54055232008-10-27 17:20:55 +00003414 }
3415 std::string RewrittenStr = RewrittenBlockExprs[CE];
3416 const char *cstr = RewrittenStr.c_str();
3417 while (*cstr++ != '{') ;
3418 S += cstr;
3419 S += "\n";
3420 return S;
3421}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003422
Steve Naroff54055232008-10-27 17:20:55 +00003423std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003424 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003425 std::string Tag) {
3426 std::string StructRef = "struct " + Tag;
3427 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Steve Naroff54055232008-10-27 17:20:55 +00003429 S += funcName;
3430 S += "_block_copy_" + utostr(i);
3431 S += "(" + StructRef;
3432 S += "*dst, " + StructRef;
3433 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003434 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003435 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003436 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003437 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003438 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003439 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003440 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003441 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003442 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003443 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003444 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003445 else
3446 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003447 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003448 S += "}\n";
3449
Steve Naroff54055232008-10-27 17:20:55 +00003450 S += "\nstatic void __";
3451 S += funcName;
3452 S += "_block_dispose_" + utostr(i);
3453 S += "(" + StructRef;
3454 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003455 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003456 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003457 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003458 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003459 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003460 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003461 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003462 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003463 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003464 else
3465 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003468 return S;
3469}
3470
Steve Naroff01aec112009-12-06 21:14:13 +00003471std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3472 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003473 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003474 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Steve Naroff54055232008-10-27 17:20:55 +00003476 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003477 S += " struct " + Desc;
3478 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Steve Naroff01aec112009-12-06 21:14:13 +00003480 Constructor += "(void *fp, "; // Invoke function pointer.
3481 Constructor += "struct " + Desc; // Descriptor pointer.
3482 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Steve Naroff54055232008-10-27 17:20:55 +00003484 if (BlockDeclRefs.size()) {
3485 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003486 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003487 E = BlockByCopyDecls.end(); I != E; ++I) {
3488 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003489 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003490 std::string ArgName = "_" + FieldName;
3491 // Handle nested closure invocation. For example:
3492 //
3493 // void (^myImportedBlock)(void);
3494 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003495 //
Steve Naroff54055232008-10-27 17:20:55 +00003496 // void (^anotherBlock)(void);
3497 // anotherBlock = ^(void) {
3498 // myImportedBlock(); // import and invoke the closure
3499 // };
3500 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003501 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003502 S += "struct __block_impl *";
3503 Constructor += ", void *" + ArgName;
3504 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003505 QualType QT = (*I)->getType();
3506 if (HasLocalVariableExternalStorage(*I))
3507 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003508 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3509 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003510 Constructor += ", " + ArgName;
3511 }
3512 S += FieldName + ";\n";
3513 }
3514 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003515 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003516 E = BlockByRefDecls.end(); I != E; ++I) {
3517 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003518 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003519 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003520 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003521 std::string TypeString;
3522 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003523 TypeString += " *";
3524 FieldName = TypeString + FieldName;
3525 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003526 Constructor += ", " + ArgName;
3527 }
3528 S += FieldName + "; // by ref\n";
3529 }
3530 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003531 Constructor += ", int flags=0)";
3532 // Initialize all "by copy" arguments.
3533 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003534 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003535 E = BlockByCopyDecls.end(); I != E; ++I) {
3536 std::string Name = (*I)->getNameAsString();
3537 if (firsTime) {
3538 Constructor += " : ";
3539 firsTime = false;
3540 }
3541 else
3542 Constructor += ", ";
3543 if (isTopLevelBlockPointerType((*I)->getType()))
3544 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3545 else
3546 Constructor += Name + "(_" + Name + ")";
3547 }
3548 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003549 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003550 E = BlockByRefDecls.end(); I != E; ++I) {
3551 std::string Name = (*I)->getNameAsString();
3552 if (firsTime) {
3553 Constructor += " : ";
3554 firsTime = false;
3555 }
3556 else
3557 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003558 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003559 }
3560
3561 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003562 if (GlobalVarDecl)
3563 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3564 else
3565 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003566 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Steve Naroff01aec112009-12-06 21:14:13 +00003568 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003569 } else {
3570 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003571 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003572 if (GlobalVarDecl)
3573 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3574 else
3575 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003576 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3577 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003578 }
3579 Constructor += " ";
3580 Constructor += "}\n";
3581 S += Constructor;
3582 S += "};\n";
3583 return S;
3584}
3585
Steve Naroff01aec112009-12-06 21:14:13 +00003586std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3587 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003588 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003589 unsigned hasCopy) {
3590 std::string S = "\nstatic struct " + DescTag;
3591
3592 S += " {\n unsigned long reserved;\n";
3593 S += " unsigned long Block_size;\n";
3594 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003595 S += " void (*copy)(struct ";
3596 S += ImplTag; S += "*, struct ";
3597 S += ImplTag; S += "*);\n";
3598
3599 S += " void (*dispose)(struct ";
3600 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003601 }
3602 S += "} ";
3603
3604 S += DescTag + "_DATA = { 0, sizeof(struct ";
3605 S += ImplTag + ")";
3606 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003607 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3608 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003609 }
3610 S += "};\n";
3611 return S;
3612}
3613
Steve Naroff54055232008-10-27 17:20:55 +00003614void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003615 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003616 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003617 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003618 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003619 bool RewriteSC = (GlobalVarDecl &&
3620 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003621 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003622 GlobalVarDecl->getType().getCVRQualifiers());
3623 if (RewriteSC) {
3624 std::string SC(" void __");
3625 SC += GlobalVarDecl->getNameAsString();
3626 SC += "() {}";
3627 InsertText(FunLocStart, SC);
3628 }
3629
Steve Naroff54055232008-10-27 17:20:55 +00003630 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003631 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3632 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003633 // Need to copy-in the inner copied-in variables not actually used in this
3634 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003635 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003636 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003637 ValueDecl *VD = Exp->getDecl();
3638 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003639 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003640 BlockByCopyDeclsPtrSet.insert(VD);
3641 BlockByCopyDecls.push_back(VD);
3642 }
John McCallf4b88a42012-03-10 09:33:50 +00003643 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003644 BlockByRefDeclsPtrSet.insert(VD);
3645 BlockByRefDecls.push_back(VD);
3646 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003647 // imported objects in the inner blocks not used in the outer
3648 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003649 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003650 VD->getType()->isObjCObjectPointerType() ||
3651 VD->getType()->isBlockPointerType())
3652 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003653 }
Steve Naroff54055232008-10-27 17:20:55 +00003654
Daniel Dunbar4087f272010-08-17 22:39:59 +00003655 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3656 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Steve Naroff01aec112009-12-06 21:14:13 +00003658 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003659
Benjamin Kramerd999b372010-02-14 14:14:16 +00003660 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003661
Steve Naroff01aec112009-12-06 21:14:13 +00003662 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Benjamin Kramerd999b372010-02-14 14:14:16 +00003664 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003665
3666 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003667 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003668 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003669 }
Steve Naroff01aec112009-12-06 21:14:13 +00003670 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3671 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003672 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Steve Naroff54055232008-10-27 17:20:55 +00003674 BlockDeclRefs.clear();
3675 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003676 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003677 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003678 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003679 ImportedBlockDecls.clear();
3680 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003681 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003682 // Must insert any 'const/volatile/static here. Since it has been
3683 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003684 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003685 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003686 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003687 if (GlobalVarDecl->getType().isConstQualified())
3688 SC += "const ";
3689 if (GlobalVarDecl->getType().isVolatileQualified())
3690 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003691 if (GlobalVarDecl->getType().isRestrictQualified())
3692 SC += "restrict ";
3693 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003694 }
3695
Steve Naroff54055232008-10-27 17:20:55 +00003696 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003697 InnerDeclRefsCount.clear();
3698 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003699 RewrittenBlockExprs.clear();
3700}
3701
3702void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3703 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003704 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Steve Naroff54055232008-10-27 17:20:55 +00003706 SynthesizeBlockLiterals(FunLocStart, FuncName);
3707}
3708
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003709static void BuildUniqueMethodName(std::string &Name,
3710 ObjCMethodDecl *MD) {
3711 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003712 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003713 Name += "__" + MD->getSelector().getAsString();
3714 // Convert colons to underscores.
3715 std::string::size_type loc = 0;
3716 while ((loc = Name.find(":", loc)) != std::string::npos)
3717 Name.replace(loc, 1, "_");
3718}
3719
Steve Naroff54055232008-10-27 17:20:55 +00003720void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003721 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3722 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003723 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003724 std::string FuncName;
3725 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003726 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003727}
3728
3729void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003730 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003731 if (*CI) {
3732 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3733 GetBlockDeclRefExprs(CBE->getBody());
3734 else
3735 GetBlockDeclRefExprs(*CI);
3736 }
3737 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3739 if (DRE->refersToEnclosingLocal()) {
3740 // FIXME: Handle enums.
3741 if (!isa<FunctionDecl>(DRE->getDecl()))
3742 BlockDeclRefs.push_back(DRE);
3743 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3744 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003745 }
John McCallf4b88a42012-03-10 09:33:50 +00003746 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003747
Steve Naroff54055232008-10-27 17:20:55 +00003748 return;
3749}
3750
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003751void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003752 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003753 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003754 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003755 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003756 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3757 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003758 GetInnerBlockDeclRefExprs(CBE->getBody(),
3759 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003760 InnerContexts);
3761 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003762 else
3763 GetInnerBlockDeclRefExprs(*CI,
3764 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003765 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003766
3767 }
3768 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003769 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3770 if (DRE->refersToEnclosingLocal()) {
3771 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3772 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3773 InnerBlockDeclRefs.push_back(DRE);
3774 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3775 if (Var->isFunctionOrMethodVarDecl())
3776 ImportedLocalExternalDecls.insert(Var);
3777 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003778 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003779
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003780 return;
3781}
3782
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003783/// convertFunctionTypeOfBlocks - This routine converts a function type
3784/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003785/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003786/// all block pointers to function pointers.
3787QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3788 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3789 // FTP will be null for closures that don't take arguments.
3790 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003791 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003792 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003793 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003794
3795 if (FTP) {
3796 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3797 E = FTP->arg_type_end(); I && (I != E); ++I) {
3798 QualType t = *I;
3799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003800 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003801 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003802 ArgTypes.push_back(t);
3803 }
3804 }
3805 QualType FuncType;
3806 // FIXME. Does this work if block takes no argument but has a return type
3807 // which is of block type?
3808 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003809 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003810 else FuncType = QualType(FT, 0);
3811 return FuncType;
3812}
3813
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003814Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003815 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003816 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003818 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003819 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003820 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003821 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003822 }
3823 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3824 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3825 }
3826 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3827 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3828 else if (const ConditionalOperator *CEXPR =
3829 dyn_cast<ConditionalOperator>(BlockExp)) {
3830 Expr *LHSExp = CEXPR->getLHS();
3831 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3832 Expr *RHSExp = CEXPR->getRHS();
3833 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3834 Expr *CONDExp = CEXPR->getCond();
3835 ConditionalOperator *CondExpr =
3836 new (Context) ConditionalOperator(CONDExp,
3837 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003838 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003839 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003840 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003841 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3842 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003843 } else if (const PseudoObjectExpr *POE
3844 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3845 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003846 } else {
3847 assert(1 && "RewriteBlockClass: Bad type");
3848 }
3849 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003850 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003851 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003852 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003853 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003855 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003856 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003857 &Context->Idents.get("__block_impl"));
3858 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003859
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003860 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003861 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003863 // Push the block argument type.
3864 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003865 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003866 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003867 E = FTP->arg_type_end(); I && (I != E); ++I) {
3868 QualType t = *I;
3869 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003870 if (!convertBlockPointerToFunctionPointer(t))
3871 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003872 ArgTypes.push_back(t);
3873 }
Steve Naroff54055232008-10-27 17:20:55 +00003874 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003876 QualType PtrToFuncCastType
3877 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003879 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003880
John McCall9d125032010-01-15 18:39:57 +00003881 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003882 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003883 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003884 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003885 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3886 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003887 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Douglas Gregor44b43212008-12-11 16:49:14 +00003889 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003890 SourceLocation(),
3891 &Context->Idents.get("FuncPtr"),
3892 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003893 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003894 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003895 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003896 FD->getType(), VK_LValue,
3897 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003899
John McCall9d125032010-01-15 18:39:57 +00003900 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003901 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003902 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Chris Lattner5f9e2722011-07-23 10:55:15 +00003904 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003905 // Add the implicit argument.
3906 BlkExprs.push_back(BlkCast);
3907 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003908 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003909 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003910 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003911 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003912 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003913 Exp->getType(), VK_RValue,
3914 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003915 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003916}
3917
Steve Naroff621edce2009-04-29 16:37:50 +00003918// We need to return the rewritten expression to handle cases where the
3919// BlockDeclRefExpr is embedded in another expression being rewritten.
3920// For example:
3921//
3922// int main() {
3923// __block Foo *f;
3924// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003925//
Steve Naroff621edce2009-04-29 16:37:50 +00003926// void (^myblock)() = ^() {
3927// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3928// i = 77;
3929// };
3930//}
John McCallf4b88a42012-03-10 09:33:50 +00003931Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003932 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003933 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003934 ValueDecl *VD = DeclRefExp->getDecl();
3935 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003936
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003937 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003938 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003939 &Context->Idents.get("__forwarding"),
3940 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003941 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003942 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003943 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3944 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003945 FD->getType(), VK_LValue,
3946 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003947
Chris Lattner5f9e2722011-07-23 10:55:15 +00003948 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003949 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003950 &Context->Idents.get(Name),
3951 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003952 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003953 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003954 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003955 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003956
3957
3958
Steve Naroffdf8570d2009-02-02 17:19:26 +00003959 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003960 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3961 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003962 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003963 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003964 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003965}
3966
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003967// Rewrites the imported local variable V with external storage
3968// (static, extern, etc.) as *V
3969//
3970Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3971 ValueDecl *VD = DRE->getDecl();
3972 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3973 if (!ImportedLocalExternalDecls.count(Var))
3974 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003975 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3976 VK_LValue, OK_Ordinary,
3977 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003978 // Need parens to enforce precedence.
3979 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3980 Exp);
3981 ReplaceStmt(DRE, PE);
3982 return PE;
3983}
3984
Steve Naroffb2f9e512008-11-03 23:29:32 +00003985void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3986 SourceLocation LocStart = CE->getLParenLoc();
3987 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003988
3989 // Need to avoid trying to rewrite synthesized casts.
3990 if (LocStart.isInvalid())
3991 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003992 // Need to avoid trying to rewrite casts contained in macros.
3993 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3994 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Steve Naroff54055232008-10-27 17:20:55 +00003996 const char *startBuf = SM->getCharacterData(LocStart);
3997 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003998 QualType QT = CE->getType();
3999 const Type* TypePtr = QT->getAs<Type>();
4000 if (isa<TypeOfExprType>(TypePtr)) {
4001 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4002 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4003 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004004 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004005 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004006 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004007 return;
4008 }
Steve Naroff54055232008-10-27 17:20:55 +00004009 // advance the location to startArgList.
4010 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Steve Naroff54055232008-10-27 17:20:55 +00004012 while (*argPtr++ && (argPtr < endBuf)) {
4013 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004014 case '^':
4015 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004016 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004017 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004018 break;
Steve Naroff54055232008-10-27 17:20:55 +00004019 }
4020 }
4021 return;
4022}
4023
4024void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4025 SourceLocation DeclLoc = FD->getLocation();
4026 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004027
Steve Naroff54055232008-10-27 17:20:55 +00004028 // We have 1 or more arguments that have closure pointers.
4029 const char *startBuf = SM->getCharacterData(DeclLoc);
4030 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Steve Naroff54055232008-10-27 17:20:55 +00004032 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Steve Naroff54055232008-10-27 17:20:55 +00004034 parenCount++;
4035 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004036 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004037 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Steve Naroff54055232008-10-27 17:20:55 +00004039 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Steve Naroff54055232008-10-27 17:20:55 +00004041 while (*argPtr++ && parenCount) {
4042 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004043 case '^':
4044 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004045 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004046 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004047 break;
4048 case '(':
4049 parenCount++;
4050 break;
4051 case ')':
4052 parenCount--;
4053 break;
Steve Naroff54055232008-10-27 17:20:55 +00004054 }
4055 }
4056 return;
4057}
4058
4059bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004060 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004061 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004062 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004063 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004064 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004065 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004066 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004067 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004068 }
4069 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004070 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004071 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004072 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004073 return true;
4074 }
4075 return false;
4076}
4077
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004078bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4079 const FunctionProtoType *FTP;
4080 const PointerType *PT = QT->getAs<PointerType>();
4081 if (PT) {
4082 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4083 } else {
4084 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4085 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4086 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4087 }
4088 if (FTP) {
4089 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004090 E = FTP->arg_type_end(); I != E; ++I) {
4091 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004092 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004093 if ((*I)->isObjCObjectPointerType() &&
4094 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4095 return true;
4096 }
4097
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004098 }
4099 return false;
4100}
4101
Ted Kremenek8189cde2009-02-07 01:47:29 +00004102void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4103 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004104 const char *argPtr = strchr(Name, '(');
4105 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Steve Naroff54055232008-10-27 17:20:55 +00004107 LParen = argPtr; // output the start.
4108 argPtr++; // skip past the left paren.
4109 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Steve Naroff54055232008-10-27 17:20:55 +00004111 while (*argPtr && parenCount) {
4112 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004113 case '(': parenCount++; break;
4114 case ')': parenCount--; break;
4115 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004116 }
4117 if (parenCount) argPtr++;
4118 }
4119 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4120 RParen = argPtr; // output the end
4121}
4122
4123void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4124 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4125 RewriteBlockPointerFunctionArgs(FD);
4126 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004127 }
Steve Naroff54055232008-10-27 17:20:55 +00004128 // Handle Variables and Typedefs.
4129 SourceLocation DeclLoc = ND->getLocation();
4130 QualType DeclT;
4131 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4132 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004133 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004134 DeclT = TDD->getUnderlyingType();
4135 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4136 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004137 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004138 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Steve Naroff54055232008-10-27 17:20:55 +00004140 const char *startBuf = SM->getCharacterData(DeclLoc);
4141 const char *endBuf = startBuf;
4142 // scan backward (from the decl location) for the end of the previous decl.
4143 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4144 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004145 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004146 std::string buf;
4147 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004148 // *startBuf != '^' if we are dealing with a pointer to function that
4149 // may take block argument types (which will be handled below).
4150 if (*startBuf == '^') {
4151 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004152 buf = '*';
4153 startBuf++;
4154 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004155 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004156 while (*startBuf != ')') {
4157 buf += *startBuf;
4158 startBuf++;
4159 OrigLength++;
4160 }
4161 buf += ')';
4162 OrigLength++;
4163
4164 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4165 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004166 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004167 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004168 DeclLoc = ND->getLocation();
4169 startBuf = SM->getCharacterData(DeclLoc);
4170 const char *argListBegin, *argListEnd;
4171 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4172 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004173 if (*argListBegin == '^')
4174 buf += '*';
4175 else if (*argListBegin == '<') {
4176 buf += "/*";
4177 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004178 OrigLength++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004179 while (*argListBegin != '>') {
4180 buf += *argListBegin++;
4181 OrigLength++;
4182 }
4183 buf += *argListBegin;
4184 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004185 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004186 else
4187 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004188 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004189 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004190 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004191 buf += ')';
4192 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004193 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004194 ReplaceText(Start, OrigLength, buf);
4195
Steve Naroff54055232008-10-27 17:20:55 +00004196 return;
4197}
4198
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004199
4200/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4201/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4202/// struct Block_byref_id_object *src) {
4203/// _Block_object_assign (&_dest->object, _src->object,
4204/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4205/// [|BLOCK_FIELD_IS_WEAK]) // object
4206/// _Block_object_assign(&_dest->object, _src->object,
4207/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4208/// [|BLOCK_FIELD_IS_WEAK]) // block
4209/// }
4210/// And:
4211/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4212/// _Block_object_dispose(_src->object,
4213/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4214/// [|BLOCK_FIELD_IS_WEAK]) // object
4215/// _Block_object_dispose(_src->object,
4216/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4217/// [|BLOCK_FIELD_IS_WEAK]) // block
4218/// }
4219
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004220std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4221 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004222 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004223 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004224 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004225 CopyDestroyCache.insert(flag);
4226 S = "static void __Block_byref_id_object_copy_";
4227 S += utostr(flag);
4228 S += "(void *dst, void *src) {\n";
4229
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004230 // offset into the object pointer is computed as:
4231 // void * + void* + int + int + void* + void *
4232 unsigned IntSize =
4233 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4234 unsigned VoidPtrSize =
4235 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4236
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004237 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004238 S += " _Block_object_assign((char*)dst + ";
4239 S += utostr(offset);
4240 S += ", *(void * *) ((char*)src + ";
4241 S += utostr(offset);
4242 S += "), ";
4243 S += utostr(flag);
4244 S += ");\n}\n";
4245
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004246 S += "static void __Block_byref_id_object_dispose_";
4247 S += utostr(flag);
4248 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004249 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4250 S += utostr(offset);
4251 S += "), ";
4252 S += utostr(flag);
4253 S += ");\n}\n";
4254 return S;
4255}
4256
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004257/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4258/// the declaration into:
4259/// struct __Block_byref_ND {
4260/// void *__isa; // NULL for everything except __weak pointers
4261/// struct __Block_byref_ND *__forwarding;
4262/// int32_t __flags;
4263/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004264/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4265/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004266/// typex ND;
4267/// };
4268///
4269/// It then replaces declaration of ND variable with:
4270/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4271/// __size=sizeof(struct __Block_byref_ND),
4272/// ND=initializer-if-any};
4273///
4274///
4275void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004276 // Insert declaration for the function in which block literal is
4277 // used.
4278 if (CurFunctionDeclToDeclareForBlock)
4279 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004280 int flag = 0;
4281 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004282 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004283 if (DeclLoc.isInvalid())
4284 // If type location is missing, it is because of missing type (a warning).
4285 // Use variable's location which is good for this case.
4286 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004287 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004288 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004289 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004290 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004291 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004292 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004293 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004294 ByrefType += " {\n";
4295 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004296 RewriteByRefString(ByrefType, Name, ND);
4297 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004298 ByrefType += " int __flags;\n";
4299 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004300 // Add void *__Block_byref_id_object_copy;
4301 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004302 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004303 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004304 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004305 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4306 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004307 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004308
4309 QualType T = Ty;
4310 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004311 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004312
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004313 ByrefType += " " + Name + ";\n";
4314 ByrefType += "};\n";
4315 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004316 SourceLocation FunLocStart;
4317 if (CurFunctionDef)
4318 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4319 else {
4320 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4321 FunLocStart = CurMethodDef->getLocStart();
4322 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004323 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004324 if (Ty.isObjCGCWeak()) {
4325 flag |= BLOCK_FIELD_IS_WEAK;
4326 isa = 1;
4327 }
4328
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004329 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004330 flag = BLOCK_BYREF_CALLER;
4331 QualType Ty = ND->getType();
4332 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4333 if (Ty->isBlockPointerType())
4334 flag |= BLOCK_FIELD_IS_BLOCK;
4335 else
4336 flag |= BLOCK_FIELD_IS_OBJECT;
4337 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004338 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004339 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004340 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004341
4342 // struct __Block_byref_ND ND =
4343 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4344 // initializer-if-any};
4345 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004346 unsigned flags = 0;
4347 if (HasCopyAndDispose)
4348 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004349 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004350 ByrefType.clear();
4351 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004352 std::string ForwardingCastType("(");
4353 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004354 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004355 ByrefType += " " + Name + " = {(void*)";
4356 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004357 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004358 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004359 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004360 ByrefType += "sizeof(";
4361 RewriteByRefString(ByrefType, Name, ND);
4362 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004363 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004364 ByrefType += ", __Block_byref_id_object_copy_";
4365 ByrefType += utostr(flag);
4366 ByrefType += ", __Block_byref_id_object_dispose_";
4367 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004368 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004369 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004370 unsigned nameSize = Name.size();
4371 // for block or function pointer declaration. Name is aleady
4372 // part of the declaration.
4373 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4374 nameSize = 1;
4375 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004376 }
4377 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004378 SourceLocation startLoc;
4379 Expr *E = ND->getInit();
4380 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4381 startLoc = ECE->getLParenLoc();
4382 else
4383 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004384 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004385 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004386 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004387 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004388 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004389 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004390 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004391 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004392 ByrefType += "sizeof(";
4393 RewriteByRefString(ByrefType, Name, ND);
4394 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004395 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004396 ByrefType += "__Block_byref_id_object_copy_";
4397 ByrefType += utostr(flag);
4398 ByrefType += ", __Block_byref_id_object_dispose_";
4399 ByrefType += utostr(flag);
4400 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004401 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004402 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004403
4404 // Complete the newly synthesized compound expression by inserting a right
4405 // curly brace before the end of the declaration.
4406 // FIXME: This approach avoids rewriting the initializer expression. It
4407 // also assumes there is only one declarator. For example, the following
4408 // isn't currently supported by this routine (in general):
4409 //
4410 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4411 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004412 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4413 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004414 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4415 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004416 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004417
Benjamin Kramerd999b372010-02-14 14:14:16 +00004418 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004419 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004420 return;
4421}
4422
Mike Stump1eb44332009-09-09 15:08:12 +00004423void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004424 // Add initializers for any closure decl refs.
4425 GetBlockDeclRefExprs(Exp->getBody());
4426 if (BlockDeclRefs.size()) {
4427 // Unique all "by copy" declarations.
4428 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004429 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004430 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4431 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4432 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4433 }
4434 }
Steve Naroff54055232008-10-27 17:20:55 +00004435 // Unique all "by ref" declarations.
4436 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004437 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004438 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4439 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4440 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4441 }
Steve Naroff54055232008-10-27 17:20:55 +00004442 }
4443 // Find any imported blocks...they will need special attention.
4444 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004445 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004446 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004447 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004448 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004449 }
4450}
4451
Chris Lattner5f9e2722011-07-23 10:55:15 +00004452FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004453 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004454 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004455 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4456 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004457 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004458}
4459
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004460Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004461 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004462 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004463 Blocks.push_back(Exp);
4464
4465 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004466
4467 // Add inner imported variables now used in current block.
4468 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004469 if (!InnerBlockDeclRefs.empty()) {
4470 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004471 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004472 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004473 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004474 // We need to save the copied-in variables in nested
4475 // blocks because it is needed at the end for some of the API generations.
4476 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004477 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4478 BlockDeclRefs.push_back(Exp);
4479 BlockByCopyDeclsPtrSet.insert(VD);
4480 BlockByCopyDecls.push_back(VD);
4481 }
John McCallf4b88a42012-03-10 09:33:50 +00004482 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004483 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4484 BlockDeclRefs.push_back(Exp);
4485 BlockByRefDeclsPtrSet.insert(VD);
4486 BlockByRefDecls.push_back(VD);
4487 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004488 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004489 // Find any imported blocks...they will need special attention.
4490 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004491 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004492 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4493 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4494 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004495 }
4496 InnerDeclRefsCount.push_back(countOfInnerDecls);
4497
Steve Narofffa15fd92008-10-28 20:29:00 +00004498 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Steve Narofffa15fd92008-10-28 20:29:00 +00004500 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004501 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004502 else if (CurMethodDef)
4503 BuildUniqueMethodName(FuncName, CurMethodDef);
4504 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004505 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004506
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Steve Narofffa15fd92008-10-28 20:29:00 +00004509 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4510 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004511
Steve Narofffa15fd92008-10-28 20:29:00 +00004512 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004513 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4514 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004515
4516 FunctionDecl *FD;
4517 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Steve Narofffa15fd92008-10-28 20:29:00 +00004519 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004520 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004521 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004522 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Chris Lattner5f9e2722011-07-23 10:55:15 +00004524 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Steve Narofffdc03722008-10-29 21:23:59 +00004526 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004527 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004528 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4529 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004530 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004531 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004532 InitExprs.push_back(castExpr);
4533
Steve Naroff01aec112009-12-06 21:14:13 +00004534 // Initialize the block descriptor.
4535 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004537 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4538 SourceLocation(), SourceLocation(),
4539 &Context->Idents.get(DescData.c_str()),
4540 Context->VoidPtrTy, 0,
4541 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004542 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004543 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004544 Context->VoidPtrTy,
4545 VK_LValue,
4546 SourceLocation()),
4547 UO_AddrOf,
4548 Context->getPointerType(Context->VoidPtrTy),
4549 VK_RValue, OK_Ordinary,
4550 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004551 InitExprs.push_back(DescRefExpr);
4552
Steve Narofffa15fd92008-10-28 20:29:00 +00004553 // Add initializers for any closure decl refs.
4554 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004555 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004556 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004557 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004558 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004559 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004560 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004561 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004562 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004563 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004564 if (HasLocalVariableExternalStorage(*I)) {
4565 QualType QT = (*I)->getType();
4566 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004567 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4568 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004569 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004570 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004571 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004572 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004573 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004574 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004575 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004576 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004577 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004578 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004579 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004580 if (HasLocalVariableExternalStorage(*I)) {
4581 QualType QT = (*I)->getType();
4582 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004583 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4584 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004585 }
4586
Steve Narofffa15fd92008-10-28 20:29:00 +00004587 }
Mike Stump1eb44332009-09-09 15:08:12 +00004588 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004589 }
4590 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004591 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004592 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004593 ValueDecl *ND = (*I);
4594 std::string Name(ND->getNameAsString());
4595 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004596 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004597 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4598 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004599 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004600 SourceLocation(), SourceLocation(),
4601 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004602 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4603 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4604
Daniel Dunbar4087f272010-08-17 22:39:59 +00004605 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004606 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004607 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004608 bool isNestedCapturedVar = false;
4609 if (block)
4610 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4611 ce = block->capture_end(); ci != ce; ++ci) {
4612 const VarDecl *variable = ci->getVariable();
4613 if (variable == ND && ci->isNested()) {
4614 assert (ci->isByRef() &&
4615 "SynthBlockInitExpr - captured block variable is not byref");
4616 isNestedCapturedVar = true;
4617 break;
4618 }
4619 }
4620 // captured nested byref variable has its address passed. Do not take
4621 // its address again.
4622 if (!isNestedCapturedVar)
4623 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004624 Context->getPointerType(Exp->getType()),
4625 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004626 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004627 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004628 }
4629 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004630 if (ImportedBlockDecls.size()) {
4631 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4632 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004633 unsigned IntSize =
4634 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004635 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4636 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004637 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004638 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004639 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00004640 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004641 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004642 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004643 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004644 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004645 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004646 BlockDeclRefs.clear();
4647 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004648 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004649 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004650 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004651 ImportedBlockDecls.clear();
4652 return NewRep;
4653}
4654
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004655bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4656 if (const ObjCForCollectionStmt * CS =
4657 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4658 return CS->getElement() == DS;
4659 return false;
4660}
4661
Steve Narofffa15fd92008-10-28 20:29:00 +00004662//===----------------------------------------------------------------------===//
4663// Function Body / Expression rewriting
4664//===----------------------------------------------------------------------===//
4665
4666Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004667 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004668 isa<DoStmt>(S) || isa<ForStmt>(S))
4669 Stmts.push_back(S);
4670 else if (isa<ObjCForCollectionStmt>(S)) {
4671 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004672 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 }
Mike Stump1eb44332009-09-09 15:08:12 +00004674
John McCall4b9c2d22011-11-06 09:01:30 +00004675 // Pseudo-object operations and ivar references need special
4676 // treatment because we're going to recursively rewrite them.
4677 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4678 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4679 return RewritePropertyOrImplicitSetter(PseudoOp);
4680 } else {
4681 return RewritePropertyOrImplicitGetter(PseudoOp);
4682 }
4683 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4684 return RewriteObjCIvarRefExpr(IvarRefExpr);
4685 }
4686
Steve Narofffa15fd92008-10-28 20:29:00 +00004687 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004690 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004692 Stmt *childStmt = (*CI);
4693 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004694 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004695 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004696 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004697 }
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004700 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004701 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4702 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004703 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004704 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004705 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004706 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004707 Stmt *SaveCurrentBody = CurrentBody;
4708 CurrentBody = BE->getBody();
4709 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004710 // block literal on rhs of a property-dot-sytax assignment
4711 // must be replaced by its synthesize ast so getRewrittenText
4712 // works as expected. In this case, what actually ends up on RHS
4713 // is the blockTranscribed which is the helper function for the
4714 // block literal; as in: self.c = ^() {[ace ARR];};
4715 bool saveDisableReplaceStmt = DisableReplaceStmt;
4716 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004717 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004718 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004719 CurrentBody = SaveCurrentBody;
4720 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004721 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004722 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004723 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004724 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004726 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4727
Steve Narofffa15fd92008-10-28 20:29:00 +00004728 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004729 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004730 return blockTranscribed;
4731 }
4732 // Handle specific things.
4733 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4734 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Steve Narofffa15fd92008-10-28 20:29:00 +00004736 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4737 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4740 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Steve Narofffa15fd92008-10-28 20:29:00 +00004742 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004743#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004744 // Before we rewrite it, put the original message expression in a comment.
4745 SourceLocation startLoc = MessExpr->getLocStart();
4746 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 const char *startBuf = SM->getCharacterData(startLoc);
4749 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 std::string messString;
4752 messString += "// ";
4753 messString.append(startBuf, endBuf-startBuf+1);
4754 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004755
4756 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004757 // InsertText(clang::SourceLocation, char const*, unsigned int).
4758 // InsertText(startLoc, messString.c_str(), messString.size());
4759 // Tried this, but it didn't work either...
4760 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004761#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004762 return RewriteMessageExpr(MessExpr);
4763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Steve Narofffa15fd92008-10-28 20:29:00 +00004765 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4766 return RewriteObjCTryStmt(StmtTry);
4767
4768 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4769 return RewriteObjCSynchronizedStmt(StmtTry);
4770
4771 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4772 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4775 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004776
4777 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004779 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004780 OrigStmtRange.getEnd());
4781 if (BreakStmt *StmtBreakStmt =
4782 dyn_cast<BreakStmt>(S))
4783 return RewriteBreakStmt(StmtBreakStmt);
4784 if (ContinueStmt *StmtContinueStmt =
4785 dyn_cast<ContinueStmt>(S))
4786 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004787
4788 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004789 // and cast exprs.
4790 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4791 // FIXME: What we're doing here is modifying the type-specifier that
4792 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004793 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004794 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4795 // the context of an ObjCForCollectionStmt. For example:
4796 // NSArray *someArray;
4797 // for (id <FooProtocol> index in someArray) ;
4798 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4799 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004800 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004801 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Steve Narofffa15fd92008-10-28 20:29:00 +00004803 // Blocks rewrite rules.
4804 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4805 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004806 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004807 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004808 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004809 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004810 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004811 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004812 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004813 if (VD->hasAttr<BlocksAttr>()) {
4814 static unsigned uniqueByrefDeclCount = 0;
4815 assert(!BlockByRefDeclNo.count(ND) &&
4816 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4817 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004818 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004819 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004820 else
4821 RewriteTypeOfDecl(VD);
4822 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004823 }
Richard Smith162e1c12011-04-15 14:24:37 +00004824 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004825 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004826 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004827 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004828 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4829 }
4830 }
4831 }
Mike Stump1eb44332009-09-09 15:08:12 +00004832
Steve Narofffa15fd92008-10-28 20:29:00 +00004833 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4834 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004835
4836 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004837 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4838 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004839 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4840 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004841 && "Statement stack mismatch");
4842 Stmts.pop_back();
4843 }
4844 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004845 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4846 ValueDecl *VD = DRE->getDecl();
4847 if (VD->hasAttr<BlocksAttr>())
4848 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004849 if (HasLocalVariableExternalStorage(VD))
4850 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004851 }
4852
Steve Narofffa15fd92008-10-28 20:29:00 +00004853 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004854 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004855 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004856 ReplaceStmt(S, BlockCall);
4857 return BlockCall;
4858 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004860 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004861 RewriteCastExpr(CE);
4862 }
4863#if 0
4864 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004865 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4866 ICE->getSubExpr(),
4867 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 // Get the new text.
4869 std::string SStr;
4870 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004871 Replacement->printPretty(Buf);
Steve Narofffa15fd92008-10-28 20:29:00 +00004872 const std::string &Str = Buf.str();
4873
4874 printf("CAST = %s\n", &Str[0]);
4875 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4876 delete S;
4877 return Replacement;
4878 }
4879#endif
4880 // Return this stmt unmodified.
4881 return S;
4882}
4883
Steve Naroff3d7e7862009-12-05 15:55:59 +00004884void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4885 for (RecordDecl::field_iterator i = RD->field_begin(),
4886 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004887 FieldDecl *FD = *i;
Steve Naroff3d7e7862009-12-05 15:55:59 +00004888 if (isTopLevelBlockPointerType(FD->getType()))
4889 RewriteBlockPointerDecl(FD);
4890 if (FD->getType()->isObjCQualifiedIdType() ||
4891 FD->getType()->isObjCQualifiedInterfaceType())
4892 RewriteObjCQualifiedInterfaceTypes(FD);
4893 }
4894}
4895
Steve Narofffa15fd92008-10-28 20:29:00 +00004896/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4897/// main file of the input.
4898void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004899 switch (D->getKind()) {
4900 case Decl::Function: {
4901 FunctionDecl *FD = cast<FunctionDecl>(D);
4902 if (FD->isOverloadedOperator())
4903 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004905 // Since function prototypes don't have ParmDecl's, we check the function
4906 // prototype. This enables us to rewrite function declarations and
4907 // definitions using the same code.
4908 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004909
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004910 if (!FD->isThisDeclarationADefinition())
4911 break;
4912
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004913 // FIXME: If this should support Obj-C++, support CXXTryStmt
4914 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4915 CurFunctionDef = FD;
4916 CurFunctionDeclToDeclareForBlock = FD;
4917 CurrentBody = Body;
4918 Body =
4919 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4920 FD->setBody(Body);
4921 CurrentBody = 0;
4922 if (PropParentMap) {
4923 delete PropParentMap;
4924 PropParentMap = 0;
4925 }
4926 // This synthesizes and inserts the block "impl" struct, invoke function,
4927 // and any copy/dispose helper functions.
4928 InsertBlockLiteralsWithinFunction(FD);
4929 CurFunctionDef = 0;
4930 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004931 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004932 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004933 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004934 case Decl::ObjCMethod: {
4935 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4936 if (CompoundStmt *Body = MD->getCompoundBody()) {
4937 CurMethodDef = MD;
4938 CurrentBody = Body;
4939 Body =
4940 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4941 MD->setBody(Body);
4942 CurrentBody = 0;
4943 if (PropParentMap) {
4944 delete PropParentMap;
4945 PropParentMap = 0;
4946 }
4947 InsertBlockLiteralsWithinMethod(MD);
4948 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004949 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004950 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004951 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004952 case Decl::ObjCImplementation: {
4953 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4954 ClassImplementation.push_back(CI);
4955 break;
4956 }
4957 case Decl::ObjCCategoryImpl: {
4958 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4959 CategoryImplementation.push_back(CI);
4960 break;
4961 }
4962 case Decl::Var: {
4963 VarDecl *VD = cast<VarDecl>(D);
4964 RewriteObjCQualifiedInterfaceTypes(VD);
4965 if (isTopLevelBlockPointerType(VD->getType()))
4966 RewriteBlockPointerDecl(VD);
4967 else if (VD->getType()->isFunctionPointerType()) {
4968 CheckFunctionPointerDecl(VD->getType(), VD);
4969 if (VD->getInit()) {
4970 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4971 RewriteCastExpr(CE);
4972 }
4973 }
4974 } else if (VD->getType()->isRecordType()) {
4975 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4976 if (RD->isCompleteDefinition())
4977 RewriteRecordBody(RD);
4978 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004979 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004980 GlobalVarDecl = VD;
4981 CurrentBody = VD->getInit();
4982 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4983 CurrentBody = 0;
4984 if (PropParentMap) {
4985 delete PropParentMap;
4986 PropParentMap = 0;
4987 }
4988 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4989 GlobalVarDecl = 0;
4990
4991 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004992 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004993 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004994 }
4995 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004996 break;
4997 }
4998 case Decl::TypeAlias:
4999 case Decl::Typedef: {
5000 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5001 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5002 RewriteBlockPointerDecl(TD);
5003 else if (TD->getUnderlyingType()->isFunctionPointerType())
5004 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5005 }
5006 break;
5007 }
5008 case Decl::CXXRecord:
5009 case Decl::Record: {
5010 RecordDecl *RD = cast<RecordDecl>(D);
5011 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005012 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005013 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005014 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005015 default:
5016 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005017 }
5018 // Nothing yet.
5019}
5020
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005021void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005022 if (Diags.hasErrorOccurred())
5023 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Steve Narofffa15fd92008-10-28 20:29:00 +00005025 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005026
Steve Naroff621edce2009-04-29 16:37:50 +00005027 // Here's a great place to add any extra declarations that may be needed.
5028 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005029 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005030 E = ProtocolExprDecls.end(); I != E; ++I)
5031 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5032
Benjamin Kramerd999b372010-02-14 14:14:16 +00005033 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005034 if (ClassImplementation.size() || CategoryImplementation.size())
5035 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005036
Steve Narofffa15fd92008-10-28 20:29:00 +00005037 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5038 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005039 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005040 Rewrite.getRewriteBufferFor(MainFileID)) {
5041 //printf("Changed:\n");
5042 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5043 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005044 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005045 }
Steve Narofface66252008-11-13 20:07:04 +00005046
Steve Naroff621edce2009-04-29 16:37:50 +00005047 if (ClassImplementation.size() || CategoryImplementation.size() ||
5048 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005049 // Rewrite Objective-c meta data*
5050 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005051 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005052 // Emit metadata.
5053 *OutFile << ResultStr;
5054 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005055 OutFile->flush();
5056}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005057
5058void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5059 InitializeCommon(context);
5060
5061 // declaring objc_selector outside the parameter list removes a silly
5062 // scope related warning...
5063 if (IsHeader)
5064 Preamble = "#pragma once\n";
5065 Preamble += "struct objc_selector; struct objc_class;\n";
5066 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5067 Preamble += "struct objc_object *superClass; ";
5068 if (LangOpts.MicrosoftExt) {
5069 // Add a constructor for creating temporary objects.
5070 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5071 ": ";
5072 Preamble += "object(o), superClass(s) {} ";
5073 }
5074 Preamble += "};\n";
5075 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5076 Preamble += "typedef struct objc_object Protocol;\n";
5077 Preamble += "#define _REWRITER_typedef_Protocol\n";
5078 Preamble += "#endif\n";
5079 if (LangOpts.MicrosoftExt) {
5080 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5081 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5082 } else
5083 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5085 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5087 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5089 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5091 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5093 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5095 Preamble += "(const char *);\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5097 Preamble += "(struct objc_class *);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5099 Preamble += "(const char *);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5105 Preamble += "(struct objc_class *, struct objc_object *);\n";
5106 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005107 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005109 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5110 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5111 Preamble += "struct __objcFastEnumerationState {\n\t";
5112 Preamble += "unsigned long state;\n\t";
5113 Preamble += "void **itemsPtr;\n\t";
5114 Preamble += "unsigned long *mutationsPtr;\n\t";
5115 Preamble += "unsigned long extra[5];\n};\n";
5116 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5117 Preamble += "#define __FASTENUMERATIONSTATE\n";
5118 Preamble += "#endif\n";
5119 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5120 Preamble += "struct __NSConstantStringImpl {\n";
5121 Preamble += " int *isa;\n";
5122 Preamble += " int flags;\n";
5123 Preamble += " char *str;\n";
5124 Preamble += " long length;\n";
5125 Preamble += "};\n";
5126 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5127 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5128 Preamble += "#else\n";
5129 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5130 Preamble += "#endif\n";
5131 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5132 Preamble += "#endif\n";
5133 // Blocks preamble.
5134 Preamble += "#ifndef BLOCK_IMPL\n";
5135 Preamble += "#define BLOCK_IMPL\n";
5136 Preamble += "struct __block_impl {\n";
5137 Preamble += " void *isa;\n";
5138 Preamble += " int Flags;\n";
5139 Preamble += " int Reserved;\n";
5140 Preamble += " void *FuncPtr;\n";
5141 Preamble += "};\n";
5142 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5143 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5144 Preamble += "extern \"C\" __declspec(dllexport) "
5145 "void _Block_object_assign(void *, const void *, const int);\n";
5146 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5147 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5148 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5149 Preamble += "#else\n";
5150 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5152 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5153 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5154 Preamble += "#endif\n";
5155 Preamble += "#endif\n";
5156 if (LangOpts.MicrosoftExt) {
5157 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5158 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5159 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5160 Preamble += "#define __attribute__(X)\n";
5161 Preamble += "#endif\n";
5162 Preamble += "#define __weak\n";
5163 }
5164 else {
5165 Preamble += "#define __block\n";
5166 Preamble += "#define __weak\n";
5167 }
5168 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5169 // as this avoids warning in any 64bit/32bit compilation model.
5170 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5171}
5172
5173/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5174/// ivar offset.
5175void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5176 std::string &Result) {
5177 if (ivar->isBitField()) {
5178 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5179 // place all bitfields at offset 0.
5180 Result += "0";
5181 } else {
5182 Result += "__OFFSETOFIVAR__(struct ";
5183 Result += ivar->getContainingInterface()->getNameAsString();
5184 if (LangOpts.MicrosoftExt)
5185 Result += "_IMPL";
5186 Result += ", ";
5187 Result += ivar->getNameAsString();
5188 Result += ")";
5189 }
5190}
5191
5192/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5193void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5194 ObjCProtocolDecl *PDecl, StringRef prefix,
5195 StringRef ClassName, std::string &Result) {
5196 static bool objc_protocol_methods = false;
5197
5198 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005199 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005200 /* struct protocol_methods {
5201 SEL _cmd;
5202 char *method_types;
5203 }
5204 */
5205 Result += "\nstruct _protocol_methods {\n";
5206 Result += "\tstruct objc_selector *_cmd;\n";
5207 Result += "\tchar *method_types;\n";
5208 Result += "};\n";
5209
5210 objc_protocol_methods = true;
5211 }
5212 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005213 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005214 return;
5215
Douglas Gregor61cc2962012-01-02 02:00:30 +00005216 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5217 PDecl = Def;
5218
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005219 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5220 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5221 PDecl->instmeth_end());
5222 /* struct _objc_protocol_method_list {
5223 int protocol_method_count;
5224 struct protocol_methods protocols[];
5225 }
5226 */
5227 Result += "\nstatic struct {\n";
5228 Result += "\tint protocol_method_count;\n";
5229 Result += "\tstruct _protocol_methods protocol_methods[";
5230 Result += utostr(NumMethods);
5231 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5232 Result += PDecl->getNameAsString();
5233 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5234 "{\n\t" + utostr(NumMethods) + "\n";
5235
5236 // Output instance methods declared in this protocol.
5237 for (ObjCProtocolDecl::instmeth_iterator
5238 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5239 I != E; ++I) {
5240 if (I == PDecl->instmeth_begin())
5241 Result += "\t ,{{(struct objc_selector *)\"";
5242 else
5243 Result += "\t ,{(struct objc_selector *)\"";
5244 Result += (*I)->getSelector().getAsString();
5245 std::string MethodTypeString;
5246 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5247 Result += "\", \"";
5248 Result += MethodTypeString;
5249 Result += "\"}\n";
5250 }
5251 Result += "\t }\n};\n";
5252 }
5253
5254 // Output class methods declared in this protocol.
5255 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5256 PDecl->classmeth_end());
5257 if (NumMethods > 0) {
5258 /* struct _objc_protocol_method_list {
5259 int protocol_method_count;
5260 struct protocol_methods protocols[];
5261 }
5262 */
5263 Result += "\nstatic struct {\n";
5264 Result += "\tint protocol_method_count;\n";
5265 Result += "\tstruct _protocol_methods protocol_methods[";
5266 Result += utostr(NumMethods);
5267 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5268 Result += PDecl->getNameAsString();
5269 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5270 "{\n\t";
5271 Result += utostr(NumMethods);
5272 Result += "\n";
5273
5274 // Output instance methods declared in this protocol.
5275 for (ObjCProtocolDecl::classmeth_iterator
5276 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5277 I != E; ++I) {
5278 if (I == PDecl->classmeth_begin())
5279 Result += "\t ,{{(struct objc_selector *)\"";
5280 else
5281 Result += "\t ,{(struct objc_selector *)\"";
5282 Result += (*I)->getSelector().getAsString();
5283 std::string MethodTypeString;
5284 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5285 Result += "\", \"";
5286 Result += MethodTypeString;
5287 Result += "\"}\n";
5288 }
5289 Result += "\t }\n};\n";
5290 }
5291
5292 // Output:
5293 /* struct _objc_protocol {
5294 // Objective-C 1.0 extensions
5295 struct _objc_protocol_extension *isa;
5296 char *protocol_name;
5297 struct _objc_protocol **protocol_list;
5298 struct _objc_protocol_method_list *instance_methods;
5299 struct _objc_protocol_method_list *class_methods;
5300 };
5301 */
5302 static bool objc_protocol = false;
5303 if (!objc_protocol) {
5304 Result += "\nstruct _objc_protocol {\n";
5305 Result += "\tstruct _objc_protocol_extension *isa;\n";
5306 Result += "\tchar *protocol_name;\n";
5307 Result += "\tstruct _objc_protocol **protocol_list;\n";
5308 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5309 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5310 Result += "};\n";
5311
5312 objc_protocol = true;
5313 }
5314
5315 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5316 Result += PDecl->getNameAsString();
5317 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5318 "{\n\t0, \"";
5319 Result += PDecl->getNameAsString();
5320 Result += "\", 0, ";
5321 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5322 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5323 Result += PDecl->getNameAsString();
5324 Result += ", ";
5325 }
5326 else
5327 Result += "0, ";
5328 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5329 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5330 Result += PDecl->getNameAsString();
5331 Result += "\n";
5332 }
5333 else
5334 Result += "0\n";
5335 Result += "};\n";
5336
5337 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005338 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005339 llvm_unreachable("protocol already synthesized");
5340
5341}
5342
5343void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5344 const ObjCList<ObjCProtocolDecl> &Protocols,
5345 StringRef prefix, StringRef ClassName,
5346 std::string &Result) {
5347 if (Protocols.empty()) return;
5348
5349 for (unsigned i = 0; i != Protocols.size(); i++)
5350 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5351
5352 // Output the top lovel protocol meta-data for the class.
5353 /* struct _objc_protocol_list {
5354 struct _objc_protocol_list *next;
5355 int protocol_count;
5356 struct _objc_protocol *class_protocols[];
5357 }
5358 */
5359 Result += "\nstatic struct {\n";
5360 Result += "\tstruct _objc_protocol_list *next;\n";
5361 Result += "\tint protocol_count;\n";
5362 Result += "\tstruct _objc_protocol *class_protocols[";
5363 Result += utostr(Protocols.size());
5364 Result += "];\n} _OBJC_";
5365 Result += prefix;
5366 Result += "_PROTOCOLS_";
5367 Result += ClassName;
5368 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5369 "{\n\t0, ";
5370 Result += utostr(Protocols.size());
5371 Result += "\n";
5372
5373 Result += "\t,{&_OBJC_PROTOCOL_";
5374 Result += Protocols[0]->getNameAsString();
5375 Result += " \n";
5376
5377 for (unsigned i = 1; i != Protocols.size(); i++) {
5378 Result += "\t ,&_OBJC_PROTOCOL_";
5379 Result += Protocols[i]->getNameAsString();
5380 Result += "\n";
5381 }
5382 Result += "\t }\n};\n";
5383}
5384
5385void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5386 std::string &Result) {
5387 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5388
5389 // Explicitly declared @interface's are already synthesized.
5390 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005391 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005392 // produce correct synthesis as yet.
5393 RewriteObjCInternalStruct(CDecl, Result);
5394 }
5395
5396 // Build _objc_ivar_list metadata for classes ivars if needed
5397 unsigned NumIvars = !IDecl->ivar_empty()
5398 ? IDecl->ivar_size()
5399 : (CDecl ? CDecl->ivar_size() : 0);
5400 if (NumIvars > 0) {
5401 static bool objc_ivar = false;
5402 if (!objc_ivar) {
5403 /* struct _objc_ivar {
5404 char *ivar_name;
5405 char *ivar_type;
5406 int ivar_offset;
5407 };
5408 */
5409 Result += "\nstruct _objc_ivar {\n";
5410 Result += "\tchar *ivar_name;\n";
5411 Result += "\tchar *ivar_type;\n";
5412 Result += "\tint ivar_offset;\n";
5413 Result += "};\n";
5414
5415 objc_ivar = true;
5416 }
5417
5418 /* struct {
5419 int ivar_count;
5420 struct _objc_ivar ivar_list[nIvars];
5421 };
5422 */
5423 Result += "\nstatic struct {\n";
5424 Result += "\tint ivar_count;\n";
5425 Result += "\tstruct _objc_ivar ivar_list[";
5426 Result += utostr(NumIvars);
5427 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5428 Result += IDecl->getNameAsString();
5429 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5430 "{\n\t";
5431 Result += utostr(NumIvars);
5432 Result += "\n";
5433
5434 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5435 SmallVector<ObjCIvarDecl *, 8> IVars;
5436 if (!IDecl->ivar_empty()) {
5437 for (ObjCInterfaceDecl::ivar_iterator
5438 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5439 IV != IVEnd; ++IV)
David Blaikie581deb32012-06-06 20:45:41 +00005440 IVars.push_back(*IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005441 IVI = IDecl->ivar_begin();
5442 IVE = IDecl->ivar_end();
5443 } else {
5444 IVI = CDecl->ivar_begin();
5445 IVE = CDecl->ivar_end();
5446 }
5447 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005448 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005449 Result += "\", \"";
5450 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005451 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005452 QuoteDoublequotes(TmpString, StrEncoding);
5453 Result += StrEncoding;
5454 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005455 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005456 Result += "}\n";
5457 for (++IVI; IVI != IVE; ++IVI) {
5458 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005459 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005460 Result += "\", \"";
5461 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005462 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005463 QuoteDoublequotes(TmpString, StrEncoding);
5464 Result += StrEncoding;
5465 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005466 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005467 Result += "}\n";
5468 }
5469
5470 Result += "\t }\n};\n";
5471 }
5472
5473 // Build _objc_method_list for class's instance methods if needed
5474 SmallVector<ObjCMethodDecl *, 32>
5475 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5476
5477 // If any of our property implementations have associated getters or
5478 // setters, produce metadata for them as well.
5479 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5480 PropEnd = IDecl->propimpl_end();
5481 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005482 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005483 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005484 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005485 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005486 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005487 if (!PD)
5488 continue;
5489 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5490 if (!Getter->isDefined())
5491 InstanceMethods.push_back(Getter);
5492 if (PD->isReadOnly())
5493 continue;
5494 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5495 if (!Setter->isDefined())
5496 InstanceMethods.push_back(Setter);
5497 }
5498 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5499 true, "", IDecl->getName(), Result);
5500
5501 // Build _objc_method_list for class's class methods if needed
5502 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5503 false, "", IDecl->getName(), Result);
5504
5505 // Protocols referenced in class declaration?
5506 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5507 "CLASS", CDecl->getName(), Result);
5508
5509 // Declaration of class/meta-class metadata
5510 /* struct _objc_class {
5511 struct _objc_class *isa; // or const char *root_class_name when metadata
5512 const char *super_class_name;
5513 char *name;
5514 long version;
5515 long info;
5516 long instance_size;
5517 struct _objc_ivar_list *ivars;
5518 struct _objc_method_list *methods;
5519 struct objc_cache *cache;
5520 struct objc_protocol_list *protocols;
5521 const char *ivar_layout;
5522 struct _objc_class_ext *ext;
5523 };
5524 */
5525 static bool objc_class = false;
5526 if (!objc_class) {
5527 Result += "\nstruct _objc_class {\n";
5528 Result += "\tstruct _objc_class *isa;\n";
5529 Result += "\tconst char *super_class_name;\n";
5530 Result += "\tchar *name;\n";
5531 Result += "\tlong version;\n";
5532 Result += "\tlong info;\n";
5533 Result += "\tlong instance_size;\n";
5534 Result += "\tstruct _objc_ivar_list *ivars;\n";
5535 Result += "\tstruct _objc_method_list *methods;\n";
5536 Result += "\tstruct objc_cache *cache;\n";
5537 Result += "\tstruct _objc_protocol_list *protocols;\n";
5538 Result += "\tconst char *ivar_layout;\n";
5539 Result += "\tstruct _objc_class_ext *ext;\n";
5540 Result += "};\n";
5541 objc_class = true;
5542 }
5543
5544 // Meta-class metadata generation.
5545 ObjCInterfaceDecl *RootClass = 0;
5546 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5547 while (SuperClass) {
5548 RootClass = SuperClass;
5549 SuperClass = SuperClass->getSuperClass();
5550 }
5551 SuperClass = CDecl->getSuperClass();
5552
5553 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5554 Result += CDecl->getNameAsString();
5555 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5556 "{\n\t(struct _objc_class *)\"";
5557 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5558 Result += "\"";
5559
5560 if (SuperClass) {
5561 Result += ", \"";
5562 Result += SuperClass->getNameAsString();
5563 Result += "\", \"";
5564 Result += CDecl->getNameAsString();
5565 Result += "\"";
5566 }
5567 else {
5568 Result += ", 0, \"";
5569 Result += CDecl->getNameAsString();
5570 Result += "\"";
5571 }
5572 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5573 // 'info' field is initialized to CLS_META(2) for metaclass
5574 Result += ", 0,2, sizeof(struct _objc_class), 0";
5575 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5576 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5577 Result += IDecl->getNameAsString();
5578 Result += "\n";
5579 }
5580 else
5581 Result += ", 0\n";
5582 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5583 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5584 Result += CDecl->getNameAsString();
5585 Result += ",0,0\n";
5586 }
5587 else
5588 Result += "\t,0,0,0,0\n";
5589 Result += "};\n";
5590
5591 // class metadata generation.
5592 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5593 Result += CDecl->getNameAsString();
5594 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5595 "{\n\t&_OBJC_METACLASS_";
5596 Result += CDecl->getNameAsString();
5597 if (SuperClass) {
5598 Result += ", \"";
5599 Result += SuperClass->getNameAsString();
5600 Result += "\", \"";
5601 Result += CDecl->getNameAsString();
5602 Result += "\"";
5603 }
5604 else {
5605 Result += ", 0, \"";
5606 Result += CDecl->getNameAsString();
5607 Result += "\"";
5608 }
5609 // 'info' field is initialized to CLS_CLASS(1) for class
5610 Result += ", 0,1";
5611 if (!ObjCSynthesizedStructs.count(CDecl))
5612 Result += ",0";
5613 else {
5614 // class has size. Must synthesize its size.
5615 Result += ",sizeof(struct ";
5616 Result += CDecl->getNameAsString();
5617 if (LangOpts.MicrosoftExt)
5618 Result += "_IMPL";
5619 Result += ")";
5620 }
5621 if (NumIvars > 0) {
5622 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5623 Result += CDecl->getNameAsString();
5624 Result += "\n\t";
5625 }
5626 else
5627 Result += ",0";
5628 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5629 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5630 Result += CDecl->getNameAsString();
5631 Result += ", 0\n\t";
5632 }
5633 else
5634 Result += ",0,0";
5635 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5636 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5637 Result += CDecl->getNameAsString();
5638 Result += ", 0,0\n";
5639 }
5640 else
5641 Result += ",0,0,0\n";
5642 Result += "};\n";
5643}
5644
5645void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5646 int ClsDefCount = ClassImplementation.size();
5647 int CatDefCount = CategoryImplementation.size();
5648
5649 // For each implemented class, write out all its meta data.
5650 for (int i = 0; i < ClsDefCount; i++)
5651 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5652
5653 // For each implemented category, write out all its meta data.
5654 for (int i = 0; i < CatDefCount; i++)
5655 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5656
5657 // Write objc_symtab metadata
5658 /*
5659 struct _objc_symtab
5660 {
5661 long sel_ref_cnt;
5662 SEL *refs;
5663 short cls_def_cnt;
5664 short cat_def_cnt;
5665 void *defs[cls_def_cnt + cat_def_cnt];
5666 };
5667 */
5668
5669 Result += "\nstruct _objc_symtab {\n";
5670 Result += "\tlong sel_ref_cnt;\n";
5671 Result += "\tSEL *refs;\n";
5672 Result += "\tshort cls_def_cnt;\n";
5673 Result += "\tshort cat_def_cnt;\n";
5674 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5675 Result += "};\n\n";
5676
5677 Result += "static struct _objc_symtab "
5678 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5679 Result += "\t0, 0, " + utostr(ClsDefCount)
5680 + ", " + utostr(CatDefCount) + "\n";
5681 for (int i = 0; i < ClsDefCount; i++) {
5682 Result += "\t,&_OBJC_CLASS_";
5683 Result += ClassImplementation[i]->getNameAsString();
5684 Result += "\n";
5685 }
5686
5687 for (int i = 0; i < CatDefCount; i++) {
5688 Result += "\t,&_OBJC_CATEGORY_";
5689 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5690 Result += "_";
5691 Result += CategoryImplementation[i]->getNameAsString();
5692 Result += "\n";
5693 }
5694
5695 Result += "};\n\n";
5696
5697 // Write objc_module metadata
5698
5699 /*
5700 struct _objc_module {
5701 long version;
5702 long size;
5703 const char *name;
5704 struct _objc_symtab *symtab;
5705 }
5706 */
5707
5708 Result += "\nstruct _objc_module {\n";
5709 Result += "\tlong version;\n";
5710 Result += "\tlong size;\n";
5711 Result += "\tconst char *name;\n";
5712 Result += "\tstruct _objc_symtab *symtab;\n";
5713 Result += "};\n\n";
5714 Result += "static struct _objc_module "
5715 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5716 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5717 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5718 Result += "};\n\n";
5719
5720 if (LangOpts.MicrosoftExt) {
5721 if (ProtocolExprDecls.size()) {
5722 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5723 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5724 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5725 E = ProtocolExprDecls.end(); I != E; ++I) {
5726 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5727 Result += (*I)->getNameAsString();
5728 Result += " = &_OBJC_PROTOCOL_";
5729 Result += (*I)->getNameAsString();
5730 Result += ";\n";
5731 }
5732 Result += "#pragma data_seg(pop)\n\n";
5733 }
5734 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5735 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5736 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5737 Result += "&_OBJC_MODULES;\n";
5738 Result += "#pragma data_seg(pop)\n\n";
5739 }
5740}
5741
5742/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5743/// implementation.
5744void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5745 std::string &Result) {
5746 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5747 // Find category declaration for this implementation.
5748 ObjCCategoryDecl *CDecl;
5749 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5750 CDecl = CDecl->getNextClassCategory())
5751 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5752 break;
5753
5754 std::string FullCategoryName = ClassDecl->getNameAsString();
5755 FullCategoryName += '_';
5756 FullCategoryName += IDecl->getNameAsString();
5757
5758 // Build _objc_method_list for class's instance methods if needed
5759 SmallVector<ObjCMethodDecl *, 32>
5760 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5761
5762 // If any of our property implementations have associated getters or
5763 // setters, produce metadata for them as well.
5764 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5765 PropEnd = IDecl->propimpl_end();
5766 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005767 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005768 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005769 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005770 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005771 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005772 if (!PD)
5773 continue;
5774 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5775 InstanceMethods.push_back(Getter);
5776 if (PD->isReadOnly())
5777 continue;
5778 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5779 InstanceMethods.push_back(Setter);
5780 }
5781 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5782 true, "CATEGORY_", FullCategoryName.c_str(),
5783 Result);
5784
5785 // Build _objc_method_list for class's class methods if needed
5786 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5787 false, "CATEGORY_", FullCategoryName.c_str(),
5788 Result);
5789
5790 // Protocols referenced in class declaration?
5791 // Null CDecl is case of a category implementation with no category interface
5792 if (CDecl)
5793 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5794 FullCategoryName, Result);
5795 /* struct _objc_category {
5796 char *category_name;
5797 char *class_name;
5798 struct _objc_method_list *instance_methods;
5799 struct _objc_method_list *class_methods;
5800 struct _objc_protocol_list *protocols;
5801 // Objective-C 1.0 extensions
5802 uint32_t size; // sizeof (struct _objc_category)
5803 struct _objc_property_list *instance_properties; // category's own
5804 // @property decl.
5805 };
5806 */
5807
5808 static bool objc_category = false;
5809 if (!objc_category) {
5810 Result += "\nstruct _objc_category {\n";
5811 Result += "\tchar *category_name;\n";
5812 Result += "\tchar *class_name;\n";
5813 Result += "\tstruct _objc_method_list *instance_methods;\n";
5814 Result += "\tstruct _objc_method_list *class_methods;\n";
5815 Result += "\tstruct _objc_protocol_list *protocols;\n";
5816 Result += "\tunsigned int size;\n";
5817 Result += "\tstruct _objc_property_list *instance_properties;\n";
5818 Result += "};\n";
5819 objc_category = true;
5820 }
5821 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5822 Result += FullCategoryName;
5823 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5824 Result += IDecl->getNameAsString();
5825 Result += "\"\n\t, \"";
5826 Result += ClassDecl->getNameAsString();
5827 Result += "\"\n";
5828
5829 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5830 Result += "\t, (struct _objc_method_list *)"
5831 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5832 Result += FullCategoryName;
5833 Result += "\n";
5834 }
5835 else
5836 Result += "\t, 0\n";
5837 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5838 Result += "\t, (struct _objc_method_list *)"
5839 "&_OBJC_CATEGORY_CLASS_METHODS_";
5840 Result += FullCategoryName;
5841 Result += "\n";
5842 }
5843 else
5844 Result += "\t, 0\n";
5845
5846 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5847 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5848 Result += FullCategoryName;
5849 Result += "\n";
5850 }
5851 else
5852 Result += "\t, 0\n";
5853 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5854}
5855
5856// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5857/// class methods.
5858template<typename MethodIterator>
5859void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5860 MethodIterator MethodEnd,
5861 bool IsInstanceMethod,
5862 StringRef prefix,
5863 StringRef ClassName,
5864 std::string &Result) {
5865 if (MethodBegin == MethodEnd) return;
5866
5867 if (!objc_impl_method) {
5868 /* struct _objc_method {
5869 SEL _cmd;
5870 char *method_types;
5871 void *_imp;
5872 }
5873 */
5874 Result += "\nstruct _objc_method {\n";
5875 Result += "\tSEL _cmd;\n";
5876 Result += "\tchar *method_types;\n";
5877 Result += "\tvoid *_imp;\n";
5878 Result += "};\n";
5879
5880 objc_impl_method = true;
5881 }
5882
5883 // Build _objc_method_list for class's methods if needed
5884
5885 /* struct {
5886 struct _objc_method_list *next_method;
5887 int method_count;
5888 struct _objc_method method_list[];
5889 }
5890 */
5891 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5892 Result += "\nstatic struct {\n";
5893 Result += "\tstruct _objc_method_list *next_method;\n";
5894 Result += "\tint method_count;\n";
5895 Result += "\tstruct _objc_method method_list[";
5896 Result += utostr(NumMethods);
5897 Result += "];\n} _OBJC_";
5898 Result += prefix;
5899 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5900 Result += "_METHODS_";
5901 Result += ClassName;
5902 Result += " __attribute__ ((used, section (\"__OBJC, __";
5903 Result += IsInstanceMethod ? "inst" : "cls";
5904 Result += "_meth\")))= ";
5905 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5906
5907 Result += "\t,{{(SEL)\"";
5908 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5909 std::string MethodTypeString;
5910 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5911 Result += "\", \"";
5912 Result += MethodTypeString;
5913 Result += "\", (void *)";
5914 Result += MethodInternalNames[*MethodBegin];
5915 Result += "}\n";
5916 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5917 Result += "\t ,{(SEL)\"";
5918 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5919 std::string MethodTypeString;
5920 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5921 Result += "\", \"";
5922 Result += MethodTypeString;
5923 Result += "\", (void *)";
5924 Result += MethodInternalNames[*MethodBegin];
5925 Result += "}\n";
5926 }
5927 Result += "\t }\n};\n";
5928}
5929
5930Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5931 SourceRange OldRange = IV->getSourceRange();
5932 Expr *BaseExpr = IV->getBase();
5933
5934 // Rewrite the base, but without actually doing replaces.
5935 {
5936 DisableReplaceStmtScope S(*this);
5937 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5938 IV->setBase(BaseExpr);
5939 }
5940
5941 ObjCIvarDecl *D = IV->getDecl();
5942
5943 Expr *Replacement = IV;
5944 if (CurMethodDef) {
5945 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5946 const ObjCInterfaceType *iFaceDecl =
5947 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5948 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5949 // lookup which class implements the instance variable.
5950 ObjCInterfaceDecl *clsDeclared = 0;
5951 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5952 clsDeclared);
5953 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5954
5955 // Synthesize an explicit cast to gain access to the ivar.
5956 std::string RecName = clsDeclared->getIdentifier()->getName();
5957 RecName += "_IMPL";
5958 IdentifierInfo *II = &Context->Idents.get(RecName);
5959 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5960 SourceLocation(), SourceLocation(),
5961 II);
5962 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5963 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5964 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5965 CK_BitCast,
5966 IV->getBase());
5967 // Don't forget the parens to enforce the proper binding.
5968 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5969 OldRange.getEnd(),
5970 castExpr);
5971 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005972 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005973 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5974 IV->getLocation(),
5975 D->getType(),
5976 VK_LValue, OK_Ordinary);
5977 Replacement = ME;
5978 } else {
5979 IV->setBase(PE);
5980 }
5981 }
5982 } else { // we are outside a method.
5983 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5984
5985 // Explicit ivar refs need to have a cast inserted.
5986 // FIXME: consider sharing some of this code with the code above.
5987 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5988 const ObjCInterfaceType *iFaceDecl =
5989 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5990 // lookup which class implements the instance variable.
5991 ObjCInterfaceDecl *clsDeclared = 0;
5992 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5993 clsDeclared);
5994 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5995
5996 // Synthesize an explicit cast to gain access to the ivar.
5997 std::string RecName = clsDeclared->getIdentifier()->getName();
5998 RecName += "_IMPL";
5999 IdentifierInfo *II = &Context->Idents.get(RecName);
6000 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6001 SourceLocation(), SourceLocation(),
6002 II);
6003 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6004 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6005 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6006 CK_BitCast,
6007 IV->getBase());
6008 // Don't forget the parens to enforce the proper binding.
6009 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6010 IV->getBase()->getLocEnd(), castExpr);
6011 // Cannot delete IV->getBase(), since PE points to it.
6012 // Replace the old base with the cast. This is important when doing
6013 // embedded rewrites. For example, [newInv->_container addObject:0].
6014 IV->setBase(PE);
6015 }
6016 }
6017
6018 ReplaceStmtWithRange(IV, Replacement, OldRange);
6019 return Replacement;
6020}