blob: 80d6cc6c33cf0b6bf9f705349944fe95a018809e [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"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#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"
Stephen Hines651f13c2014-04-23 16:59:28 -070030#include <memory>
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Chris Lattner77cd2a02007-10-11 00:43:27 +000035namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000036 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000037 protected:
38
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000040 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000041 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000047 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000048 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000060 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000061
Chris Lattner2c64b7b2007-10-16 21:07:07 +000062 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000063 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000064 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000065 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000066 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000067 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000068 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000069 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000070 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000072 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
78 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000083
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000084 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000087 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000088 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramere5753592013-09-09 14:48:42 +0000103 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000107 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
113 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVector<Stmt *, 32> Stmts;
115 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000116 // Remember all the @protocol(<expr>) expressions.
117 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000118
119 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000122 SmallVector<BlockExpr *, 32> Blocks;
123 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125
John McCallf4b88a42012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Steve Naroff54055232008-10-27 17:20:55 +0000128 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000133 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000135 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
136
Steve Naroff54055232008-10-27 17:20:55 +0000137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff4c3580e2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000143
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000144 // Needed for header files being rewritten
145 bool IsHeader;
146 bool SilenceRewriteMacroWarning;
147 bool objc_impl_method;
148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000150 class DisableReplaceStmtScope {
151 RewriteObjC &R;
152 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000153
John McCall4b9c2d22011-11-06 09:01:30 +0000154 public:
155 DisableReplaceStmtScope(RewriteObjC &R)
156 : R(R), SavedValue(R.DisableReplaceStmt) {
157 R.DisableReplaceStmt = true;
158 }
159 ~DisableReplaceStmtScope() {
160 R.DisableReplaceStmt = SavedValue;
161 }
162 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000163 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner77cd2a02007-10-11 00:43:27 +0000165 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Top Level Driver code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700168 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000169 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000170 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
171 if (!Class->isThisDeclarationADefinition()) {
172 RewriteForwardClassDecl(D);
173 break;
174 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000175 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000176
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000177 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
178 if (!Proto->isThisDeclarationADefinition()) {
179 RewriteForwardProtocolDecl(D);
180 break;
181 }
182 }
183
Chris Lattner682bf922009-03-29 16:50:03 +0000184 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000185 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000186 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000187 }
188 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000189 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000190 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000191 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000192 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000193
194 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Stephen Hines651f13c2014-04-23 16:59:28 -0700196 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000198 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Steve Naroff4c3580e2008-12-04 23:50:32 +0000201 if (ReplacingStmt)
202 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000203
Steve Naroffb619d952008-12-09 12:56:34 +0000204 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000205 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000206
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000208 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000209 ReplacedNodes[Old] = New;
210 return;
211 }
212 if (SilenceRewriteMacroWarning)
213 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000214 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
215 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000216 }
Steve Naroffb619d952008-12-09 12:56:34 +0000217
218 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000219 if (DisableReplaceStmt)
220 return;
221
Nick Lewycky7e749242010-10-31 21:07:24 +0000222 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000223 int Size = Rewrite.getRangeSize(SrcRange);
224 if (Size == -1) {
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 return;
228 }
229 // Get the new text.
230 std::string SStr;
231 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000232 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000233 const std::string &Str = S.str();
234
235 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000236 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000237 ReplacedNodes[Old] = New;
238 return;
239 }
240 if (SilenceRewriteMacroWarning)
241 return;
242 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
243 << Old->getSourceRange();
244 }
245
Chris Lattner5f9e2722011-07-23 10:55:15 +0000246 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000247 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000248 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000249 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000250 SilenceRewriteMacroWarning)
251 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000253 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
254 }
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Chris Lattneraadaf782008-01-31 19:51:04 +0000256 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000257 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000259 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000260 SilenceRewriteMacroWarning)
261 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattneraadaf782008-01-31 19:51:04 +0000263 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
264 }
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chris Lattnerf04da132007-10-24 17:06:59 +0000266 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000267 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000268 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000269 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000270 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000271 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000272 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000273 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000274 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
275 ObjCImplementationDecl *IMD,
276 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000277 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000278 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000279 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
280 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000281 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
282 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000283 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000284 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
286 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000287 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000288 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000290 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000291 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000292 void RewriteBlockPointerType(std::string& Str, QualType Type);
293 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000294 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000296 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000297 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000298
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000300 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000301 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000302 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
303 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000304 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000305 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000306 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000307 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000308 void RewriteTryReturnStmts(Stmt *S);
309 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000311 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000312 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000313 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
314 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000315 Stmt *RewriteBreakStmt(BreakStmt *S);
316 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000317 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000318
Steve Naroff54055232008-10-27 17:20:55 +0000319 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000320 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000321
Mike Stump1eb44332009-09-09 15:08:12 +0000322 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000323 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000324 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000325 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000326 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000327 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000328
329 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
330 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700331
332 virtual void Initialize(ASTContext &context) override = 0;
333
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000334 // Metadata Rewriting.
335 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
336 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
337 StringRef prefix,
338 StringRef ClassName,
339 std::string &Result) = 0;
340 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
341 std::string &Result) = 0;
342 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
343 StringRef prefix,
344 StringRef ClassName,
345 std::string &Result) = 0;
346 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
347 std::string &Result) = 0;
348
349 // Rewriting ivar access
350 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
351 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
352 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000353
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000354 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000355 // rewriting routines on the new ASTs.
356 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
357 Expr **args, unsigned nargs,
358 SourceLocation StartLoc=SourceLocation(),
359 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000360 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
361 QualType msgSendType,
362 QualType returnType,
363 SmallVectorImpl<QualType> &ArgTypes,
364 SmallVectorImpl<Expr*> &MsgExprs,
365 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000366 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
367 SourceLocation StartLoc=SourceLocation(),
368 SourceLocation EndLoc=SourceLocation());
369
370 void SynthCountByEnumWithState(std::string &buf);
371 void SynthMsgSendFunctionDecl();
372 void SynthMsgSendSuperFunctionDecl();
373 void SynthMsgSendStretFunctionDecl();
374 void SynthMsgSendFpretFunctionDecl();
375 void SynthMsgSendSuperStretFunctionDecl();
376 void SynthGetClassFunctionDecl();
377 void SynthGetMetaClassFunctionDecl();
378 void SynthGetSuperClassFunctionDecl();
379 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000380 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000381
382 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000383 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000387 std::string SynthesizeBlockImpl(BlockExpr *CE,
388 std::string Tag, std::string Desc);
389 std::string SynthesizeBlockDescriptor(std::string DescTag,
390 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000391 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000392 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000393 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000395 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000396 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
397 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000398 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Fariborz Jahanian58457172011-12-05 18:43:13 +0000400 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000401 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000402 void WarnAboutReturnGotoStmts(Stmt *S);
403 void HasReturnStmts(Stmt *S, bool &hasReturns);
404 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
405 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
406 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
407
408 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000409 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000410 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000411 void GetInnerBlockDeclRefExprs(Stmt *S,
412 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000413 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Steve Naroff54055232008-10-27 17:20:55 +0000415 // We avoid calling Type::isBlockPointerType(), since it operates on the
416 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000417 bool isTopLevelBlockPointerType(QualType T) {
418 return isa<BlockPointerType>(T);
419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000421 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
422 /// to a function pointer type and upon success, returns true; false
423 /// otherwise.
424 bool convertBlockPointerToFunctionPointer(QualType &T) {
425 if (isTopLevelBlockPointerType(T)) {
426 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
427 T = Context->getPointerType(BPT->getPointeeType());
428 return true;
429 }
430 return false;
431 }
432
Fariborz Jahanian58457172011-12-05 18:43:13 +0000433 bool needToScanForQualifiers(QualType T);
434 QualType getSuperStructType();
435 QualType getConstantStringStructType();
436 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
437 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
438
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000439 void convertToUnqualifiedObjCType(QualType &T) {
440 if (T->isObjCQualifiedIdType())
441 T = Context->getObjCIdType();
442 else if (T->isObjCQualifiedClassType())
443 T = Context->getObjCClassType();
444 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000445 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
446 if (const ObjCObjectPointerType * OBJPT =
447 T->getAsObjCInterfacePointerType()) {
448 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
449 T = QualType(IFaceT, 0);
450 T = Context->getPointerType(T);
451 }
452 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000453 }
454
Steve Naroff54055232008-10-27 17:20:55 +0000455 // FIXME: This predicate seems like it would be useful to add to ASTContext.
456 bool isObjCType(QualType T) {
457 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
458 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Steve Naroff54055232008-10-27 17:20:55 +0000460 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Steve Naroff54055232008-10-27 17:20:55 +0000462 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
463 OCT == Context->getCanonicalType(Context->getObjCClassType()))
464 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Ted Kremenek6217b802009-07-29 21:53:49 +0000466 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000467 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000468 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000469 return true;
470 }
471 return false;
472 }
473 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000474 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000475 void GetExtentOfArgList(const char *Name, const char *&LParen,
476 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000477
Steve Naroff621edce2009-04-29 16:37:50 +0000478 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000479 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000480 if (From[i] == '"')
481 To += "\\\"";
482 else
483 To += From[i];
484 }
485 }
John McCalle23cf432010-12-14 08:05:40 +0000486
487 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000488 ArrayRef<QualType> args,
John McCalle23cf432010-12-14 08:05:40 +0000489 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;
Jordan Rosebea522f2013-03-08 21:51:21 +0000494 return Context->getFunctionType(result, args, fpi);
John McCalle23cf432010-12-14 08:05:40 +0000495 }
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 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700504
505 StringLiteral *getStringLiteral(StringRef Str) {
506 QualType StrType = Context->getConstantArrayType(
507 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
508 0);
509 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
510 /*Pascal=*/false, StrType, SourceLocation());
511 }
Fariborz Jahanian58457172011-12-05 18:43:13 +0000512 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000513
514 class RewriteObjCFragileABI : public RewriteObjC {
515 public:
516
517 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
518 DiagnosticsEngine &D, const LangOptions &LOpts,
519 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
520 D, LOpts,
521 silenceMacroWarn) {}
522
523 ~RewriteObjCFragileABI() {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700524 virtual void Initialize(ASTContext &context) override;
525
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000526 // Rewriting metadata
527 template<typename MethodIterator>
528 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
529 MethodIterator MethodEnd,
530 bool IsInstanceMethod,
531 StringRef prefix,
532 StringRef ClassName,
533 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700534 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
535 StringRef prefix, StringRef ClassName,
536 std::string &Result) override;
537 void RewriteObjCProtocolListMetaData(
538 const ObjCList<ObjCProtocolDecl> &Prots,
539 StringRef prefix, StringRef ClassName, std::string &Result) override;
540 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
541 std::string &Result) override;
542 void RewriteMetaDataIntoBuffer(std::string &Result) override;
543 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
544 std::string &Result) override;
545
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000546 // Rewriting ivar
Stephen Hines651f13c2014-04-23 16:59:28 -0700547 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
548 std::string &Result) override;
549 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000550 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000551}
552
Mike Stump1eb44332009-09-09 15:08:12 +0000553void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
554 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000555 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000556 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700557 for (const auto &I : fproto->param_types())
558 if (isTopLevelBlockPointerType(I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000559 // All the args are checked/rewritten. Don't call twice!
560 RewriteBlockPointerDecl(D);
561 break;
562 }
563 }
564}
565
566void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000567 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000568 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000569 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000570}
571
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000572static bool IsHeaderFile(const std::string &Filename) {
573 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000575 if (DotPos == std::string::npos) {
576 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000577 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000580 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
581 // C header: .h
582 // C++ header: .hh or .H;
583 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000584}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000585
Chris Lattner5f9e2722011-07-23 10:55:15 +0000586RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000587 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000588 bool silenceMacroWarn)
589 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
590 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000591 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000592 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000593 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000594 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
595 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000596 "rewriter doesn't support user-specified control flow semantics "
597 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000598}
599
Eli Friedmanbce831b2009-05-18 22:29:17 +0000600ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000602 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000603 const LangOptions &LOpts,
604 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000605 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000606}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000607
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000608void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000609 Context = &context;
610 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000611 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000612 MsgSendFunctionDecl = 0;
613 MsgSendSuperFunctionDecl = 0;
614 MsgSendStretFunctionDecl = 0;
615 MsgSendSuperStretFunctionDecl = 0;
616 MsgSendFpretFunctionDecl = 0;
617 GetClassFunctionDecl = 0;
618 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000619 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000620 SelGetUidFunctionDecl = 0;
621 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000622 ConstantStringClassReference = 0;
623 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000624 CurMethodDef = 0;
625 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000626 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000627 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000628 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000629 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000630 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000631 BcLabelCount = 0;
Benjamin Kramere5753592013-09-09 14:48:42 +0000632 SuperConstructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000633 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000634 PropParentMap = 0;
635 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000636 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000637 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000639 // Get the ID and start/end of the main file.
640 MainFileID = SM->getMainFileID();
641 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
642 MainFileStart = MainBuf->getBufferStart();
643 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000644
David Blaikie4e4d0842012-03-11 07:00:24 +0000645 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000646}
647
Chris Lattnerf04da132007-10-24 17:06:59 +0000648//===----------------------------------------------------------------------===//
649// Top Level Driver Code
650//===----------------------------------------------------------------------===//
651
Chris Lattner682bf922009-03-29 16:50:03 +0000652void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000653 if (Diags.hasErrorOccurred())
654 return;
655
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000656 // Two cases: either the decl could be in the main file, or it could be in a
657 // #included file. If the former, rewrite it now. If the later, check to see
658 // if we rewrote the #include/#import.
659 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000660 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000662 // If this is for a builtin, ignore it.
663 if (Loc.isInvalid()) return;
664
Steve Naroffebf2b562007-10-23 23:50:29 +0000665 // Look for built-in declarations that we need to refer during the rewrite.
666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000667 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000668 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000669 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000670 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000671 ConstantStringClassReference = FVD;
672 return;
673 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000674 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
675 if (ID->isThisDeclarationADefinition())
676 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000678 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000679 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000680 if (PD->isThisDeclarationADefinition())
681 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000682 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
683 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000684 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
685 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000686 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000687 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
688 if (!IFace->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = IFace->getLocStart();
691 do {
692 if (isa<ObjCInterfaceDecl>(*DI) &&
693 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
Douglas Gregor7723fec2011-12-15 20:29:51 +0000699 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000700 } while (DI != DIEnd);
701 RewriteForwardClassDecl(DG);
702 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000703 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000704 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000705
706 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
707 if (!Proto->isThisDeclarationADefinition()) {
708 SmallVector<Decl *, 8> DG;
709 SourceLocation StartLoc = Proto->getLocStart();
710 do {
711 if (isa<ObjCProtocolDecl>(*DI) &&
712 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
713 StartLoc == (*DI)->getLocStart())
714 DG.push_back(*DI);
715 else
716 break;
717
718 ++DI;
719 } while (DI != DIEnd);
720 RewriteForwardProtocolDecl(DG);
721 continue;
722 }
723 }
724
Chris Lattner682bf922009-03-29 16:50:03 +0000725 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000726 ++DI;
727 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000728 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000729 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000730 if (SM->isWrittenInMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000731 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000732}
733
Chris Lattnerf04da132007-10-24 17:06:59 +0000734//===----------------------------------------------------------------------===//
735// Syntactic (non-AST) Rewriting Code
736//===----------------------------------------------------------------------===//
737
Steve Naroffb29b4272008-04-14 22:03:09 +0000738void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000739 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000740 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000741 const char *MainBufStart = MainBuf.begin();
742 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000743 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000745 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000746 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
747 if (*BufPtr == '#') {
748 if (++BufPtr == MainBufEnd)
749 return;
750 while (*BufPtr == ' ' || *BufPtr == '\t')
751 if (++BufPtr == MainBufEnd)
752 return;
753 if (!strncmp(BufPtr, "import", ImportLen)) {
754 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000755 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000756 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000757 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000758 BufPtr += ImportLen;
759 }
760 }
761 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000762}
763
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000764static std::string getIvarAccessString(ObjCIvarDecl *OID) {
765 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000766 std::string S;
767 S = "((struct ";
768 S += ClassDecl->getIdentifier()->getName();
769 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000770 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000771 return S;
772}
773
Steve Naroffa0876e82008-12-02 17:36:43 +0000774void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
775 ObjCImplementationDecl *IMD,
776 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000777 static bool objcGetPropertyDefined = false;
778 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000779 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000780 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 const char *startBuf = SM->getCharacterData(startLoc);
782 assert((*startBuf == '@') && "bogus @synthesize location");
783 const char *semiBuf = strchr(startBuf, ';');
784 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000785 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000786 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787
788 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
789 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Steve Naroffeb0646c2008-12-02 15:48:25 +0000791 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000795 if (!OID)
796 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000797 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000798 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000799 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
800 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000801 ObjCPropertyDecl::OBJC_PR_copy));
802 std::string Getr;
803 if (GenGetProperty && !objcGetPropertyDefined) {
804 objcGetPropertyDefined = true;
805 // FIXME. Is this attribute correct in all cases?
806 Getr = "\nextern \"C\" __declspec(dllimport) "
807 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000808 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000809 RewriteObjCMethodDecl(OID->getContainingInterface(),
810 PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
813 // See objc-act.c:objc_synthesize_new_getter() for details.
814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
826 Getr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -0700827 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000828 if (i) Getr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -0700829 std::string ParamStr =
830 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000831 Getr += ParamStr;
832 }
833 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700834 if (FT->getNumParams())
835 Getr += ", ";
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000836 Getr += "...";
837 }
838 Getr += ")";
839 } else
840 Getr += "()";
841 }
842 Getr += ";\n";
843 Getr += "return (_TYPE)";
844 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000845 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846 Getr += ", 1)";
847 }
848 else
849 Getr += "return " + getIvarAccessString(OID);
850 Getr += "; }";
851 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000852 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000853
854 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000855 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Steve Naroffeb0646c2008-12-02 15:48:25 +0000857 // Generate the 'setter' function.
858 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000859 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000860 ObjCPropertyDecl::OBJC_PR_copy);
861 if (GenSetProperty && !objcSetPropertyDefined) {
862 objcSetPropertyDefined = true;
863 // FIXME. Is this attribute correct in all cases?
864 Setr = "\nextern \"C\" __declspec(dllimport) "
865 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
866 }
867
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000868 RewriteObjCMethodDecl(OID->getContainingInterface(),
869 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000870 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000871 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000872 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000873 if (GenSetProperty) {
874 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000875 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000876 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000877 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000879 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000880 Setr += "0, ";
881 else
882 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000883 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 Setr += "1)";
885 else
886 Setr += "0)";
887 }
888 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000889 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000890 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000891 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000892 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000893 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000894}
Chris Lattner8a12c272007-10-11 18:38:32 +0000895
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000896static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
897 std::string &typedefString) {
898 typedefString += "#ifndef _REWRITER_typedef_";
899 typedefString += ForwardDecl->getNameAsString();
900 typedefString += "\n";
901 typedefString += "#define _REWRITER_typedef_";
902 typedefString += ForwardDecl->getNameAsString();
903 typedefString += "\n";
904 typedefString += "typedef struct objc_object ";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += ";\n#endif\n";
907}
908
Douglas Gregor375bb142011-12-27 22:43:10 +0000909void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000910 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000911 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000912 const char *startBuf = SM->getCharacterData(startLoc);
913 const char *semiPtr = strchr(startBuf, ';');
914 // Replace the @class with typedefs corresponding to the classes.
915 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
916}
917
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000918void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000919 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000920 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000921 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000922 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000923 // Translate to typedef's that forward reference structs with the same name
924 // as the class. As a convenience, we include the original declaration
925 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000926 typedefString += "// @class ";
927 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000928 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000929 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000930 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000931 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000932 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000933 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000934}
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Craig Topper6b9240e2013-07-05 19:34:19 +0000936void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000937 std::string typedefString;
938 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000939 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000940 if (i == 0) {
941 typedefString += "// @class ";
942 typedefString += ForwardDecl->getNameAsString();
943 typedefString += ";\n";
944 }
945 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
946 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000947 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000948}
949
Steve Naroffb29b4272008-04-14 22:03:09 +0000950void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000951 // When method is a synthesized one, such as a getter/setter there is
952 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000953 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000954 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 SourceLocation LocStart = Method->getLocStart();
956 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chandler Carruth64211622011-07-25 21:09:52 +0000958 if (SM->getExpansionLineNumber(LocEnd) >
959 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000960 InsertText(LocStart, "#if 0\n");
961 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000962 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000963 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000964 }
965}
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000968 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Benjamin Kramerd999b372010-02-14 14:14:16 +0000970 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000971 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000972}
973
Steve Naroffb29b4272008-04-14 22:03:09 +0000974void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000975 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Steve Naroff423cb562007-10-30 13:30:57 +0000977 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000978 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Stephen Hines651f13c2014-04-23 16:59:28 -0700980 for (auto *I : CatDecl->properties())
981 RewriteProperty(I);
982 for (auto *I : CatDecl->instance_methods())
983 RewriteMethodDeclaration(I);
984 for (auto *I : CatDecl->class_methods())
985 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986
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
Stephen Hines651f13c2014-04-23 16:59:28 -0700999 for (auto *I : PDecl->instance_methods())
1000 RewriteMethodDeclaration(I);
1001 for (auto *I : PDecl->class_methods())
1002 RewriteMethodDeclaration(I);
1003 for (auto *I : PDecl->properties())
1004 RewriteProperty(I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001005
Steve Naroff752d6ef2007-10-30 16:42:30 +00001006 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001007 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001008 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 // Must comment out @optional/@required
1011 const char *startBuf = SM->getCharacterData(LocStart);
1012 const char *endBuf = SM->getCharacterData(LocEnd);
1013 for (const char *p = startBuf; p < endBuf; p++) {
1014 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001015 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001016 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001018 }
1019 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001020 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001023 }
1024 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001025}
1026
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001027void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1028 SourceLocation LocStart = (*D.begin())->getLocStart();
1029 if (LocStart.isInvalid())
1030 llvm_unreachable("Invalid SourceLocation");
1031 // FIXME: handle forward protocol that are declared across multiple lines.
1032 ReplaceText(LocStart, 0, "// ");
1033}
1034
1035void
Craig Topper6b9240e2013-07-05 19:34:19 +00001036RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001037 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001038 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001039 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001040 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001041 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001042}
1043
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001044void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1045 const FunctionType *&FPRetType) {
1046 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001047 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048 else if (T->isFunctionPointerType() ||
1049 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001050 // needs special handling, since pointer-to-functions have special
1051 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001052 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001053 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001054 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001055 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001057 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001058 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001059 ResultStr +=
1060 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001061 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001062 }
1063 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001064 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001065}
1066
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001067void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1068 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001069 std::string &ResultStr) {
1070 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1071 const FunctionType *FPRetType = 0;
1072 ResultStr += "\nstatic ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001073 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001074 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001076 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001077 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001079 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001080 NameStr += "_I_";
1081 else
1082 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001084 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001085 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001086
1087 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001088 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001090 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001093 {
1094 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 int len = selString.size();
1096 for (int i = 0; i < len; i++)
1097 if (selString[i] == ':')
1098 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001099 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001101 // Remember this name for metadata emission
1102 MethodInternalNames[OMD] = NameStr;
1103 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 // Rewrite arguments
1106 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001109 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001110 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001112 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001113 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001114 ResultStr += "struct ";
1115 }
1116 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001117 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001118 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 }
1120 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001121 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001122 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001125 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 // Method arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07001129 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001131 if (PDecl->getType()->isObjCQualifiedIdType()) {
1132 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001133 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001134 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001135 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001136 QualType QT = PDecl->getType();
1137 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001138 (void)convertBlockPointerToFunctionPointer(QT);
1139 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001140 ResultStr += Name;
1141 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001143 if (OMD->isVariadic())
1144 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001145 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Steve Naroff76e429d2008-07-16 14:40:40 +00001147 if (FPRetType) {
1148 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Steve Naroff76e429d2008-07-16 14:40:40 +00001150 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001151 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001152 ResultStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07001153 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 if (i) ResultStr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001155 std::string ParamStr =
1156 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001157 ResultStr += ParamStr;
1158 }
1159 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001160 if (FT->getNumParams())
1161 ResultStr += ", ";
Steve Naroff76e429d2008-07-16 14:40:40 +00001162 ResultStr += "...";
1163 }
1164 ResultStr += ")";
1165 } else {
1166 ResultStr += "()";
1167 }
1168 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001170void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001171 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1172 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001174 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Stephen Hines651f13c2014-04-23 16:59:28 -07001176 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 std::string ResultStr;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001178 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001180 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001181
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Stephen Hines651f13c2014-04-23 16:59:28 -07001187 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001188 std::string ResultStr;
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();
Mike Stump1eb44332009-09-09 15:08:12 +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 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001197 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1198 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001199
Benjamin Kramerd999b372010-02-14 14:14:16 +00001200 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001201}
1202
Steve Naroffb29b4272008-04-14 22:03:09 +00001203void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001204 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001205 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001206 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001207 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001208 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001209 ResultStr += "\n";
1210 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001211 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001212 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001213 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001214 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001215 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001216 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001217 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001218 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001219 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Stephen Hines651f13c2014-04-23 16:59:28 -07001221 for (auto *I : ClassDecl->properties())
1222 RewriteProperty(I);
1223 for (auto *I : ClassDecl->instance_methods())
1224 RewriteMethodDeclaration(I);
1225 for (auto *I : ClassDecl->class_methods())
1226 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001227
Steve Naroff2feac5e2007-10-30 03:43:13 +00001228 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001229 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001231}
1232
John McCall4b9c2d22011-11-06 09:01:30 +00001233Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1234 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001235
John McCall4b9c2d22011-11-06 09:01:30 +00001236 // We just magically know some things about the structure of this
1237 // expression.
1238 ObjCMessageExpr *OldMsg =
1239 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1240 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001241
John McCall4b9c2d22011-11-06 09:01:30 +00001242 // Because the rewriter doesn't allow us to rewrite rewritten code,
1243 // we need to suppress rewriting the sub-statements.
1244 Expr *Base, *RHS;
1245 {
1246 DisableReplaceStmtScope S(*this);
1247
1248 // Rebuild the base expression if we have one.
1249 Base = 0;
1250 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1251 Base = OldMsg->getInstanceReceiver();
1252 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1253 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1254 }
1255
1256 // Rebuild the RHS.
1257 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1258 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1259 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1260 }
1261
1262 // TODO: avoid this copy.
1263 SmallVector<SourceLocation, 1> SelLocs;
1264 OldMsg->getSelectorLocs(SelLocs);
1265
Chad Rosier0774ba72012-01-06 20:05:14 +00001266 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001267 switch (OldMsg->getReceiverKind()) {
1268 case ObjCMessageExpr::Class:
1269 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1270 OldMsg->getValueKind(),
1271 OldMsg->getLeftLoc(),
1272 OldMsg->getClassReceiverTypeInfo(),
1273 OldMsg->getSelector(),
1274 SelLocs,
1275 OldMsg->getMethodDecl(),
1276 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001277 OldMsg->getRightLoc(),
1278 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001279 break;
1280
1281 case ObjCMessageExpr::Instance:
1282 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1283 OldMsg->getValueKind(),
1284 OldMsg->getLeftLoc(),
1285 Base,
1286 OldMsg->getSelector(),
1287 SelLocs,
1288 OldMsg->getMethodDecl(),
1289 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001290 OldMsg->getRightLoc(),
1291 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001292 break;
1293
1294 case ObjCMessageExpr::SuperClass:
1295 case ObjCMessageExpr::SuperInstance:
1296 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1297 OldMsg->getValueKind(),
1298 OldMsg->getLeftLoc(),
1299 OldMsg->getSuperLoc(),
1300 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1301 OldMsg->getSuperType(),
1302 OldMsg->getSelector(),
1303 SelLocs,
1304 OldMsg->getMethodDecl(),
1305 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001306 OldMsg->getRightLoc(),
1307 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001308 break;
1309 }
1310
1311 Stmt *Replacement = SynthMessageExpr(NewMsg);
1312 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1313 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001314}
1315
John McCall4b9c2d22011-11-06 09:01:30 +00001316Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1317 SourceRange OldRange = PseudoOp->getSourceRange();
1318
1319 // We just magically know some things about the structure of this
1320 // expression.
1321 ObjCMessageExpr *OldMsg =
1322 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1323
1324 // Because the rewriter doesn't allow us to rewrite rewritten code,
1325 // we need to suppress rewriting the sub-statements.
1326 Expr *Base = 0;
1327 {
1328 DisableReplaceStmtScope S(*this);
1329
1330 // Rebuild the base expression if we have one.
1331 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1332 Base = OldMsg->getInstanceReceiver();
1333 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1334 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001335 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001336 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001337
John McCall4b9c2d22011-11-06 09:01:30 +00001338 // Intentionally empty.
1339 SmallVector<SourceLocation, 1> SelLocs;
1340 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001341
Chad Rosier0774ba72012-01-06 20:05:14 +00001342 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001343 switch (OldMsg->getReceiverKind()) {
1344 case ObjCMessageExpr::Class:
1345 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1346 OldMsg->getValueKind(),
1347 OldMsg->getLeftLoc(),
1348 OldMsg->getClassReceiverTypeInfo(),
1349 OldMsg->getSelector(),
1350 SelLocs,
1351 OldMsg->getMethodDecl(),
1352 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001353 OldMsg->getRightLoc(),
1354 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001355 break;
1356
1357 case ObjCMessageExpr::Instance:
1358 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1359 OldMsg->getValueKind(),
1360 OldMsg->getLeftLoc(),
1361 Base,
1362 OldMsg->getSelector(),
1363 SelLocs,
1364 OldMsg->getMethodDecl(),
1365 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001366 OldMsg->getRightLoc(),
1367 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001368 break;
1369
1370 case ObjCMessageExpr::SuperClass:
1371 case ObjCMessageExpr::SuperInstance:
1372 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1373 OldMsg->getValueKind(),
1374 OldMsg->getLeftLoc(),
1375 OldMsg->getSuperLoc(),
1376 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1377 OldMsg->getSuperType(),
1378 OldMsg->getSelector(),
1379 SelLocs,
1380 OldMsg->getMethodDecl(),
1381 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001382 OldMsg->getRightLoc(),
1383 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001384 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001385 }
John McCall4b9c2d22011-11-06 09:01:30 +00001386
1387 Stmt *Replacement = SynthMessageExpr(NewMsg);
1388 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1389 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001390}
1391
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392/// SynthCountByEnumWithState - To print:
1393/// ((unsigned int (*)
1394/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001395/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001397/// "countByEnumeratingWithState:objects:count:"),
1398/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001399/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001400///
Steve Naroffb29b4272008-04-14 22:03:09 +00001401void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001402 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1403 "id *, unsigned int))(void *)objc_msgSend)";
1404 buf += "\n\t\t";
1405 buf += "((id)l_collection,\n\t\t";
1406 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1407 buf += "\n\t\t";
1408 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001409 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001411
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001412/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1413/// statement to exit to its outer synthesized loop.
1414///
Steve Naroffb29b4272008-04-14 22:03:09 +00001415Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001416 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1417 return S;
1418 // replace break with goto __break_label
1419 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001421 SourceLocation startLoc = S->getLocStart();
1422 buf = "goto __break_label_";
1423 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001424 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001425
1426 return 0;
1427}
1428
1429/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1430/// statement to continue with its inner synthesized loop.
1431///
Steve Naroffb29b4272008-04-14 22:03:09 +00001432Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001433 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1434 return S;
1435 // replace continue with goto __continue_label
1436 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001438 SourceLocation startLoc = S->getLocStart();
1439 buf = "goto __continue_label_";
1440 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001441 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001443 return 0;
1444}
1445
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001446/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001447/// It rewrites:
1448/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001450/// Into:
1451/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001453/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001454/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001455/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001456/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001457/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001458/// if (limit) {
1459/// unsigned long startMutations = *enumState.mutationsPtr;
1460/// do {
1461/// unsigned long counter = 0;
1462/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001463/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001465/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001466/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001467/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001468/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001469/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001470/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001472/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001473/// }
1474/// else
1475/// elem = nil;
1476/// }
1477///
Steve Naroffb29b4272008-04-14 22:03:09 +00001478Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001479 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001480 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001481 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001482 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001483 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001484 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001486 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001488 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001489 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490 std::string buf;
1491 buf = "\n{\n\t";
1492 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1493 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001494 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001495 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001496 if (ElementType->isObjCQualifiedIdType() ||
1497 ElementType->isObjCQualifiedInterfaceType())
1498 // Simply use 'id' for all qualified types.
1499 elementTypeAsString = "id";
1500 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001501 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001502 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001504 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 buf += elementName;
1506 buf += ";\n\t";
1507 }
Chris Lattner06767512008-04-08 05:52:18 +00001508 else {
1509 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001510 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001511 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1512 if (VD->getType()->isObjCQualifiedIdType() ||
1513 VD->getType()->isObjCQualifiedInterfaceType())
1514 // Simply use 'id' for all qualified types.
1515 elementTypeAsString = "id";
1516 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001517 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001520 // struct __objcFastEnumerationState enumState = { 0 };
1521 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001522 // id __rw_items[16];
1523 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 // id l_collection = (id)
1525 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001526 // Find start location of 'collection' the hard way!
1527 const char *startCollectionBuf = startBuf;
1528 startCollectionBuf += 3; // skip 'for'
1529 startCollectionBuf = strchr(startCollectionBuf, '(');
1530 startCollectionBuf++; // skip '('
1531 // find 'in' and skip it.
1532 while (*startCollectionBuf != ' ' ||
1533 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1534 (*(startCollectionBuf+3) != ' ' &&
1535 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1536 startCollectionBuf++;
1537 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001538
1539 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001540 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001541 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001542 SourceLocation rightParenLoc = S->getRParenLoc();
1543 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001544 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001545 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001547 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001548 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001549 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001550 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001551 // ((unsigned int (*)
1552 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001553 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001554 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001555 // "countByEnumeratingWithState:objects:count:"),
1556 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001557 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001558 buf += "unsigned long limit =\n\t\t";
1559 SynthCountByEnumWithState(buf);
1560 buf += ";\n\t";
1561 /// if (limit) {
1562 /// unsigned long startMutations = *enumState.mutationsPtr;
1563 /// do {
1564 /// unsigned long counter = 0;
1565 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001566 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001568 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 buf += "if (limit) {\n\t";
1570 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1571 buf += "do {\n\t\t";
1572 buf += "unsigned long counter = 0;\n\t\t";
1573 buf += "do {\n\t\t\t";
1574 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1575 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1576 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001577 buf += " = (";
1578 buf += elementTypeAsString;
1579 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001580 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001581 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001583 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001584 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001585 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001586 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001588 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 /// }
1590 /// else
1591 /// elem = nil;
1592 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001593 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001594 buf = ";\n\t";
1595 buf += "__continue_label_";
1596 buf += utostr(ObjCBcLabelNo.back());
1597 buf += ": ;";
1598 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 buf += "} while (counter < limit);\n\t";
1600 buf += "} while (limit = ";
1601 SynthCountByEnumWithState(buf);
1602 buf += ");\n\t";
1603 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001604 buf += " = ((";
1605 buf += elementTypeAsString;
1606 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001607 buf += "__break_label_";
1608 buf += utostr(ObjCBcLabelNo.back());
1609 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 buf += "}\n\t";
1611 buf += "else\n\t\t";
1612 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001613 buf += " = ((";
1614 buf += elementTypeAsString;
1615 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001616 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001618 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001619 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001620 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001621 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001622 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001623 } else {
1624 /* Need to treat single statements specially. For example:
1625 *
1626 * for (A *a in b) if (stuff()) break;
1627 * for (A *a in b) xxxyy;
1628 *
1629 * The following code simply scans ahead to the semi to find the actual end.
1630 */
1631 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1632 const char *semiBuf = strchr(stmtBuf, ';');
1633 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001634 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001635 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001636 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001637 Stmts.pop_back();
1638 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001640}
1641
Mike Stump1eb44332009-09-09 15:08:12 +00001642/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001643/// This routine rewrites @synchronized(expr) stmt;
1644/// into:
1645/// objc_sync_enter(expr);
1646/// @try stmt @finally { objc_sync_exit(expr); }
1647///
Steve Naroffb29b4272008-04-14 22:03:09 +00001648Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001649 // Get the start location and compute the semi location.
1650 SourceLocation startLoc = S->getLocStart();
1651 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001653 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001654
1655 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001656 buf = "objc_sync_enter((id)";
1657 const char *lparenBuf = startBuf;
1658 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001659 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001660 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1661 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001662 // been rewritten! (which implies the SourceLocation's are invalid).
1663 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001664 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001665 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001666 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001667 buf = ");\n";
1668 // declare a new scope with two variables, _stack and _rethrow.
1669 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1670 buf += "int buf[18/*32-bit i386*/];\n";
1671 buf += "char *pointers[4];} _stack;\n";
1672 buf += "id volatile _rethrow = 0;\n";
1673 buf += "objc_exception_try_enter(&_stack);\n";
1674 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001675 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001676 startLoc = S->getSynchBody()->getLocEnd();
1677 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Steve Naroffc7089f12008-08-19 13:04:19 +00001679 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001680 SourceLocation lastCurlyLoc = startLoc;
1681 buf = "}\nelse {\n";
1682 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001683 buf += "}\n";
1684 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001685 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001686
1687 std::string syncBuf;
1688 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001689
1690 Expr *syncExpr = S->getSynchExpr();
1691 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1692 ? CK_BitCast :
1693 syncExpr->getType()->isBlockPointerType()
1694 ? CK_BlockPointerToObjCPointerCast
1695 : CK_CPointerToObjCPointerCast;
1696 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1697 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001698 std::string syncExprBufS;
1699 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00001700 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001701 syncBuf += syncExprBuf.str();
1702 syncBuf += ");";
1703
1704 buf += syncBuf;
1705 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001706 buf += "}\n";
1707 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Benjamin Kramerd999b372010-02-14 14:14:16 +00001709 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001710
1711 bool hasReturns = false;
1712 HasReturnStmts(S->getSynchBody(), hasReturns);
1713 if (hasReturns)
1714 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1715
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001716 return 0;
1717}
1718
Steve Naroffb85e77a2009-12-05 21:43:12 +00001719void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1720{
Steve Naroff8c565152008-12-05 17:03:39 +00001721 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001722 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001723 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001724 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001725
Steve Naroffb85e77a2009-12-05 21:43:12 +00001726 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001727 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001728 TryFinallyContainsReturnDiag);
1729 }
1730 return;
1731}
1732
Steve Naroffb85e77a2009-12-05 21:43:12 +00001733void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1734{
1735 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001736 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001737 if (*CI)
1738 HasReturnStmts(*CI, hasReturns);
1739
1740 if (isa<ReturnStmt>(S))
1741 hasReturns = true;
1742 return;
1743}
1744
1745void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1746 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001747 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001748 if (*CI) {
1749 RewriteTryReturnStmts(*CI);
1750 }
1751 if (isa<ReturnStmt>(S)) {
1752 SourceLocation startLoc = S->getLocStart();
1753 const char *startBuf = SM->getCharacterData(startLoc);
1754
1755 const char *semiBuf = strchr(startBuf, ';');
1756 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001757 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001758
1759 std::string buf;
1760 buf = "{ objc_exception_try_exit(&_stack); return";
1761
Benjamin Kramerd999b372010-02-14 14:14:16 +00001762 ReplaceText(startLoc, 6, buf);
1763 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001764 }
1765 return;
1766}
1767
1768void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1769 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001770 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001771 if (*CI) {
1772 RewriteSyncReturnStmts(*CI, syncExitBuf);
1773 }
1774 if (isa<ReturnStmt>(S)) {
1775 SourceLocation startLoc = S->getLocStart();
1776 const char *startBuf = SM->getCharacterData(startLoc);
1777
1778 const char *semiBuf = strchr(startBuf, ';');
1779 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001780 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001781
1782 std::string buf;
1783 buf = "{ objc_exception_try_exit(&_stack);";
1784 buf += syncExitBuf;
1785 buf += " return";
1786
Benjamin Kramerd999b372010-02-14 14:14:16 +00001787 ReplaceText(startLoc, 6, buf);
1788 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001789 }
1790 return;
1791}
1792
Steve Naroffb29b4272008-04-14 22:03:09 +00001793Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001794 // Get the start location and compute the semi location.
1795 SourceLocation startLoc = S->getLocStart();
1796 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Steve Naroff75730982007-11-07 04:08:17 +00001798 assert((*startBuf == '@') && "bogus @try location");
1799
1800 std::string buf;
1801 // declare a new scope with two variables, _stack and _rethrow.
1802 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1803 buf += "int buf[18/*32-bit i386*/];\n";
1804 buf += "char *pointers[4];} _stack;\n";
1805 buf += "id volatile _rethrow = 0;\n";
1806 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001807 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001808
Benjamin Kramerd999b372010-02-14 14:14:16 +00001809 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Steve Naroff75730982007-11-07 04:08:17 +00001811 startLoc = S->getTryBody()->getLocEnd();
1812 startBuf = SM->getCharacterData(startLoc);
1813
1814 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Steve Naroff75730982007-11-07 04:08:17 +00001816 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001817 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001818 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001819 buf = " /* @catch begin */ else {\n";
1820 buf += " id _caught = objc_exception_extract(&_stack);\n";
1821 buf += " objc_exception_try_enter (&_stack);\n";
1822 buf += " if (_setjmp(_stack.buf))\n";
1823 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1824 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Benjamin Kramerd999b372010-02-14 14:14:16 +00001826 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001827 } else { /* no catch list */
1828 buf = "}\nelse {\n";
1829 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1830 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001831 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001832 }
Steve Naroff75730982007-11-07 04:08:17 +00001833 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001834 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1835 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001836 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001837
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001838 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001839 buf = "if ("; // we are generating code for the first catch clause
1840 else
1841 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001842 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001843 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroff75730982007-11-07 04:08:17 +00001845 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Steve Naroff75730982007-11-07 04:08:17 +00001847 const char *lParenLoc = strchr(startBuf, '(');
1848
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001849 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001850 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001851 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001852 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1853 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001854 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001855 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001856 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Steve Naroffe12e6922008-02-01 20:02:07 +00001858 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001859 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001860 } else if (catchDecl) {
1861 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001862 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001863 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001864 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001865 } else if (const ObjCObjectPointerType *Ptr =
1866 t->getAs<ObjCObjectPointerType>()) {
1867 // Should be a pointer to a class.
1868 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1869 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001870 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001871 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001872 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001873 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001874 }
1875 }
1876 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001877 lastCatchBody = Catch->getCatchBody();
1878 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001879 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1880 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1881 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1882 assert((*rParenBuf == ')') && "bogus @catch paren location");
1883 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Mike Stump1eb44332009-09-09 15:08:12 +00001885 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001886 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001887 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001888 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001889 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001890 }
Steve Naroff75730982007-11-07 04:08:17 +00001891 }
1892 // Complete the catch list...
1893 if (lastCatchBody) {
1894 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001895 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1896 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Steve Naroff378f47a2008-09-11 15:29:03 +00001898 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001899 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001900 buf = "} /* last catch end */\n";
1901 buf += "else {\n";
1902 buf += " _rethrow = _caught;\n";
1903 buf += " objc_exception_try_exit(&_stack);\n";
1904 buf += "} } /* @catch end */\n";
1905 if (!S->getFinallyStmt())
1906 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001907 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Steve Naroff75730982007-11-07 04:08:17 +00001909 // Set lastCurlyLoc
1910 lastCurlyLoc = lastCatchBody->getLocEnd();
1911 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001912 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001913 startLoc = finalStmt->getLocStart();
1914 startBuf = SM->getCharacterData(startLoc);
1915 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Benjamin Kramerd999b372010-02-14 14:14:16 +00001917 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 Stmt *body = finalStmt->getFinallyBody();
1920 SourceLocation startLoc = body->getLocStart();
1921 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001922 assert(*SM->getCharacterData(startLoc) == '{' &&
1923 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001924 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001925 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001927 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001928 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001929 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Steve Naroff75730982007-11-07 04:08:17 +00001932 // Set lastCurlyLoc
1933 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Steve Naroff8c565152008-12-05 17:03:39 +00001935 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001936 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001937 } else { /* no finally clause - make sure we synthesize an implicit one */
1938 buf = "{ /* implicit finally clause */\n";
1939 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1940 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1941 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001942 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001943
1944 // Now check for any return/continue/go statements within the @try.
1945 // The implicit finally clause won't called if the @try contains any
1946 // jump statements.
1947 bool hasReturns = false;
1948 HasReturnStmts(S->getTryBody(), hasReturns);
1949 if (hasReturns)
1950 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001951 }
1952 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001953 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001954 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001955 return 0;
1956}
1957
Mike Stump1eb44332009-09-09 15:08:12 +00001958// This can't be done with ReplaceStmt(S, ThrowExpr), since
1959// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001960// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001961Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001962 // Get the start location and compute the semi location.
1963 SourceLocation startLoc = S->getLocStart();
1964 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Steve Naroff2bd03922007-11-07 15:32:26 +00001966 assert((*startBuf == '@') && "bogus @throw location");
1967
1968 std::string buf;
1969 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001970 if (S->getThrowExpr())
1971 buf = "objc_exception_throw(";
1972 else // add an implicit argument
1973 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001975 // handle "@ throw" correctly.
1976 const char *wBuf = strchr(startBuf, 'w');
1977 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001978 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Steve Naroff2bd03922007-11-07 15:32:26 +00001980 const char *semiBuf = strchr(startBuf, ';');
1981 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001982 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001983 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001984 return 0;
1985}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001986
Steve Naroffb29b4272008-04-14 22:03:09 +00001987Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001988 // Create a new string expression.
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001989 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001990 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Stephen Hines651f13c2014-04-23 16:59:28 -07001991 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001992 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Chris Lattner07506182007-11-30 22:53:43 +00001994 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001995 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001996 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001997}
1998
Steve Naroffb29b4272008-04-14 22:03:09 +00001999Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002000 if (!SelGetUidFunctionDecl)
2001 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002002 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2003 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002004 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002005 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002006 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2007 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002008 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002009 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002010 return SelExp;
2011}
2012
Steve Naroffb29b4272008-04-14 22:03:09 +00002013CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002014 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2015 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002016 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002017 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroffebf2b562007-10-23 23:50:29 +00002019 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002020 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2021 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroffebf2b562007-10-23 23:50:29 +00002023 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002024 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002025 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002026 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002027 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
John McCall183700f2009-09-21 23:43:11 +00002029 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002031 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002032 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCallf89e55a2010-11-18 06:31:45 +00002033 FT->getCallResultType(*Context),
2034 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002035 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002036}
2037
Steve Naroffd5255f52007-11-01 13:24:47 +00002038static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2039 const char *&startRef, const char *&endRef) {
2040 while (startBuf < endBuf) {
2041 if (*startBuf == '<')
2042 startRef = startBuf; // mark the start.
2043 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002044 if (startRef && *startRef == '<') {
2045 endRef = startBuf; // mark the end.
2046 return true;
2047 }
2048 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002049 }
2050 startBuf++;
2051 }
2052 return false;
2053}
2054
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002055static void scanToNextArgument(const char *&argRef) {
2056 int angle = 0;
2057 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2058 if (*argRef == '<')
2059 angle++;
2060 else if (*argRef == '>')
2061 angle--;
2062 argRef++;
2063 }
2064 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2065}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002066
Steve Naroffb29b4272008-04-14 22:03:09 +00002067bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002068 if (T->isObjCQualifiedIdType())
2069 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002070 if (const PointerType *PT = T->getAs<PointerType>()) {
2071 if (PT->getPointeeType()->isObjCQualifiedIdType())
2072 return true;
2073 }
2074 if (T->isObjCObjectPointerType()) {
2075 T = T->getPointeeType();
2076 return T->isObjCQualifiedInterfaceType();
2077 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002078 if (T->isArrayType()) {
2079 QualType ElemTy = Context->getBaseElementType(T);
2080 return needToScanForQualifiers(ElemTy);
2081 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002082 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002083}
2084
Steve Naroff4f95b752008-07-29 18:15:38 +00002085void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2086 QualType Type = E->getType();
2087 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002088 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroffcda658e2008-11-19 21:15:47 +00002090 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2091 Loc = ECE->getLParenLoc();
2092 EndLoc = ECE->getRParenLoc();
2093 } else {
2094 Loc = E->getLocStart();
2095 EndLoc = E->getLocEnd();
2096 }
2097 // This will defend against trying to rewrite synthesized expressions.
2098 if (Loc.isInvalid() || EndLoc.isInvalid())
2099 return;
2100
Steve Naroff4f95b752008-07-29 18:15:38 +00002101 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002102 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002103 const char *startRef = 0, *endRef = 0;
2104 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2105 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002106 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2107 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002108 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002109 InsertText(LessLoc, "/*");
2110 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002111 }
2112 }
2113}
2114
Steve Naroffb29b4272008-04-14 22:03:09 +00002115void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002116 SourceLocation Loc;
2117 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002118 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002119 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2120 Loc = VD->getLocation();
2121 Type = VD->getType();
2122 }
2123 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2124 Loc = FD->getLocation();
2125 // Check for ObjC 'id' and class types that have been adorned with protocol
2126 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002127 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002128 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002129 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002130 if (!proto)
2131 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002132 Type = proto->getReturnType();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002133 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002134 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2135 Loc = FD->getLocation();
2136 Type = FD->getType();
2137 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002138 else
2139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002141 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002142 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Steve Naroffd5255f52007-11-01 13:24:47 +00002144 const char *endBuf = SM->getCharacterData(Loc);
2145 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002146 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002147 startBuf--; // scan backward (from the decl location) for return type.
2148 const char *startRef = 0, *endRef = 0;
2149 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2150 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002151 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2152 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002153 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002154 InsertText(LessLoc, "/*");
2155 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002156 }
2157 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 if (!proto)
2159 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002160 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161 const char *startBuf = SM->getCharacterData(Loc);
2162 const char *startFuncBuf = startBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07002163 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2164 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002165 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Steve Naroffd5255f52007-11-01 13:24:47 +00002167 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002168 // scan forward (from the decl location) for argument types.
2169 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 const char *startRef = 0, *endRef = 0;
2171 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2172 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002173 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002174 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002175 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002176 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002177 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002178 InsertText(LessLoc, "/*");
2179 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002180 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002181 startBuf = ++endBuf;
2182 }
2183 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002184 // If the function name is derived from a macro expansion, then the
2185 // argument buffer will not follow the name. Need to speak with Chris.
2186 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002187 startBuf++; // scan forward (from the decl location) for argument types.
2188 startBuf++;
2189 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002190 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002191}
2192
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002193void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2194 QualType QT = ND->getType();
2195 const Type* TypePtr = QT->getAs<Type>();
2196 if (!isa<TypeOfExprType>(TypePtr))
2197 return;
2198 while (isa<TypeOfExprType>(TypePtr)) {
2199 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2200 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2201 TypePtr = QT->getAs<Type>();
2202 }
2203 // FIXME. This will not work for multiple declarators; as in:
2204 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002205 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002206 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2207 const char *startBuf = SM->getCharacterData(DeclLoc);
2208 if (ND->getInit()) {
2209 std::string Name(ND->getNameAsString());
2210 TypeAsString += " " + Name + " = ";
2211 Expr *E = ND->getInit();
2212 SourceLocation startLoc;
2213 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2214 startLoc = ECE->getLParenLoc();
2215 else
2216 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002217 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002218 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002219 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002220 }
2221 else {
2222 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002223 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002224 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002225 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002226 }
2227}
2228
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002229// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002230void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002231 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002232 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002233 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002234 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002235 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002236 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002237 SourceLocation(),
2238 SourceLocation(),
2239 SelGetUidIdent, getFuncType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002240 SC_Extern);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002241}
2242
Steve Naroffb29b4272008-04-14 22:03:09 +00002243void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002244 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002245 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002246 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002247 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002248 return;
2249 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002250 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002251}
2252
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002253void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002254 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002255 const char *argPtr = TypeString.c_str();
2256 if (!strchr(argPtr, '^')) {
2257 Str += TypeString;
2258 return;
2259 }
2260 while (*argPtr) {
2261 Str += (*argPtr == '^' ? '*' : *argPtr);
2262 argPtr++;
2263 }
2264}
2265
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002266// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002267void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2268 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002269 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002270 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002271 const char *argPtr = TypeString.c_str();
2272 int paren = 0;
2273 while (*argPtr) {
2274 switch (*argPtr) {
2275 case '(':
2276 Str += *argPtr;
2277 paren++;
2278 break;
2279 case ')':
2280 Str += *argPtr;
2281 paren--;
2282 break;
2283 case '^':
2284 Str += '*';
2285 if (paren == 1)
2286 Str += VD->getNameAsString();
2287 break;
2288 default:
2289 Str += *argPtr;
2290 break;
2291 }
2292 argPtr++;
2293 }
2294}
2295
2296
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002297void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2298 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2299 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2300 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2301 if (!proto)
2302 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002303 QualType Type = proto->getReturnType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002304 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002305 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002306 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002307 FdStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07002308 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002309 for (unsigned i = 0; i < numArgs; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002310 QualType ArgType = proto->getParamType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002311 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002312 if (i+1 < numArgs)
2313 FdStr += ", ";
2314 }
2315 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002316 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002317 CurFunctionDeclToDeclareForBlock = 0;
2318}
2319
Benjamin Kramere5753592013-09-09 14:48:42 +00002320// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2321void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2322 if (SuperConstructorFunctionDecl)
Steve Naroffc0a123c2008-03-11 17:37:02 +00002323 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002324 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002325 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002326 QualType argT = Context->getObjCIdType();
2327 assert(!argT.isNull() && "Can't find 'id' type");
2328 ArgTys.push_back(argT);
2329 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002330 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002331 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002332 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002333 SourceLocation(),
2334 SourceLocation(),
2335 msgSendIdent, msgSendType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002336 0, SC_Extern);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002337}
2338
Steve Naroff09b266e2007-10-30 23:14:51 +00002339// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002340void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002341 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002342 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002343 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002344 assert(!argT.isNull() && "Can't find 'id' type");
2345 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002346 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002347 assert(!argT.isNull() && "Can't find 'SEL' type");
2348 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002349 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002350 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002351 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002352 SourceLocation(),
2353 SourceLocation(),
2354 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002355 SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002356}
2357
Steve Naroff874e2322007-11-15 10:28:18 +00002358// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002359void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002360 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002361 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002362 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002363 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002364 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002365 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2366 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2367 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002368 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002369 assert(!argT.isNull() && "Can't find 'SEL' type");
2370 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002371 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002372 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002373 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002374 SourceLocation(),
2375 SourceLocation(),
2376 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002377 SC_Extern);
Steve Naroff874e2322007-11-15 10:28:18 +00002378}
2379
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002380// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002381void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002382 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002383 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002384 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002385 assert(!argT.isNull() && "Can't find 'id' type");
2386 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002388 assert(!argT.isNull() && "Can't find 'SEL' type");
2389 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002390 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002391 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002392 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002393 SourceLocation(),
2394 SourceLocation(),
2395 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002396 SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002397}
2398
Mike Stump1eb44332009-09-09 15:08:12 +00002399// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002400// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002401void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002402 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002403 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002404 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002405 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002406 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002407 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002408 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2409 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2410 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002412 assert(!argT.isNull() && "Can't find 'SEL' type");
2413 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002414 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002415 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002416 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002417 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002418 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002419 msgSendIdent,
2420 msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002421 SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422}
2423
Steve Naroff1284db82008-05-08 22:02:18 +00002424// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002425void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002427 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002434 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002435 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002436 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002437 SourceLocation(),
2438 SourceLocation(),
2439 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002440 SC_Extern);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002441}
2442
Steve Naroff09b266e2007-10-30 23:14:51 +00002443// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002444void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002445 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002446 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002447 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002448 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002449 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002450 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002451 SourceLocation(),
2452 SourceLocation(),
2453 getClassIdent, getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002454 SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002455}
2456
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002457// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2458void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2459 IdentifierInfo *getSuperClassIdent =
2460 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002461 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002462 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002463 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002464 ArgTys);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002465 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002466 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002467 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002468 getSuperClassIdent,
2469 getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002470 SC_Extern);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002471}
2472
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002473// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002474void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002475 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002476 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002477 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002478 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002479 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002480 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002481 SourceLocation(),
2482 SourceLocation(),
2483 getClassIdent, getClassType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002484 0, SC_Extern);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002485}
2486
Steve Naroffb29b4272008-04-14 22:03:09 +00002487Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002488 QualType strType = getConstantStringStructType();
2489
2490 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002491
2492 std::string tmpName = InFileName;
2493 unsigned i;
2494 for (i=0; i < tmpName.length(); i++) {
2495 char c = tmpName.at(i);
Stephen Hines651f13c2014-04-23 16:59:28 -07002496 // replace any non-alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002497 if (!isAlphanumeric(c))
Steve Naroff7691d9b2008-05-31 03:35:42 +00002498 tmpName[i] = '_';
2499 }
2500 S += tmpName;
2501 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002502 S += utostr(NumObjCStringLiterals++);
2503
Steve Naroffba92b2e2008-03-27 22:29:16 +00002504 Preamble += "static __NSConstantStringImpl " + S;
2505 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2506 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002507 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002508 std::string prettyBufS;
2509 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002510 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002511 Preamble += prettyBuf.str();
2512 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002513 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002514
2515 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002516 SourceLocation(), &Context->Idents.get(S),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002517 strType, 0, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002518 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002519 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002520 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002521 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002522 VK_RValue, OK_Ordinary,
2523 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002524 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002525 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002526 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002527 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002528 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002529 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002530}
2531
Steve Naroff874e2322007-11-15 10:28:18 +00002532// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002533QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002534 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002535 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002536 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002537 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002538 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002539
Steve Naroff874e2322007-11-15 10:28:18 +00002540 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002541 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002542 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002543 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002544
Steve Naroff874e2322007-11-15 10:28:18 +00002545 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002546 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002547 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002548 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002549 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002550 FieldTypes[i], 0,
2551 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002552 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002553 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002554 }
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregor838db382010-02-11 01:19:42 +00002556 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002557 }
2558 return Context->getTagDeclType(SuperStructDecl);
2559}
2560
Steve Naroffb29b4272008-04-14 22:03:09 +00002561QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002562 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002563 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002564 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002565 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002566 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002568 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002569 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002570 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002571 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002572 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002573 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002574 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002575 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002576
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002577 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002578 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002579 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2580 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002581 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002582 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002583 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002584 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002585 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002586 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002587 }
2588
Douglas Gregor838db382010-02-11 01:19:42 +00002589 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002590 }
2591 return Context->getTagDeclType(ConstantStringDecl);
2592}
2593
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002594CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2595 QualType msgSendType,
2596 QualType returnType,
2597 SmallVectorImpl<QualType> &ArgTypes,
2598 SmallVectorImpl<Expr*> &MsgExprs,
2599 ObjCMethodDecl *Method) {
2600 // Create a reference to the objc_msgSend_stret() declaration.
2601 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2602 false, msgSendType,
2603 VK_LValue, SourceLocation());
2604 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2605 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2606 Context->getPointerType(Context->VoidTy),
2607 CK_BitCast, STDRE);
2608 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002609 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2610 Method ? Method->isVariadic()
2611 : false);
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002612 castType = Context->getPointerType(castType);
2613 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2614 cast);
2615
2616 // Don't forget the parens to enforce the proper binding.
2617 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2618
2619 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002620 CallExpr *STCE = new (Context) CallExpr(
2621 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002622 return STCE;
2623
2624}
2625
2626
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002627Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2628 SourceLocation StartLoc,
2629 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002630 if (!SelGetUidFunctionDecl)
2631 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002632 if (!MsgSendFunctionDecl)
2633 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002634 if (!MsgSendSuperFunctionDecl)
2635 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002636 if (!MsgSendStretFunctionDecl)
2637 SynthMsgSendStretFunctionDecl();
2638 if (!MsgSendSuperStretFunctionDecl)
2639 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002640 if (!MsgSendFpretFunctionDecl)
2641 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002642 if (!GetClassFunctionDecl)
2643 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002644 if (!GetSuperClassFunctionDecl)
2645 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002646 if (!GetMetaClassFunctionDecl)
2647 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Steve Naroff874e2322007-11-15 10:28:18 +00002649 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002650 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2651 // May need to use objc_msgSend_stret() as well.
2652 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002653 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002654 QualType resultType = mDecl->getReturnType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002655 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002656 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002657 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002658 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002659 }
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Steve Naroff934f2762007-10-24 22:48:43 +00002661 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002662 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002663 switch (Exp->getReceiverKind()) {
2664 case ObjCMessageExpr::SuperClass: {
2665 MsgSendFlavor = MsgSendSuperFunctionDecl;
2666 if (MsgSendStretFlavor)
2667 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2668 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregor04badcf2010-04-21 00:45:42 +00002670 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002673
Douglas Gregor04badcf2010-04-21 00:45:42 +00002674 // set the receiver to self, the first argument to all methods.
2675 InitExprs.push_back(
2676 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002677 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002678 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002679 false,
John McCallf89e55a2010-11-18 06:31:45 +00002680 Context->getObjCIdType(),
2681 VK_RValue,
2682 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002683 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Douglas Gregor04badcf2010-04-21 00:45:42 +00002685 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002686 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002687 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002688 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2689 &ClsExprs[0],
2690 ClsExprs.size(),
2691 StartLoc,
2692 EndLoc);
2693 // (Class)objc_getClass("CurrentClass")
2694 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2695 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002696 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002697 ClsExprs.clear();
2698 ClsExprs.push_back(ArgExpr);
2699 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2700 &ClsExprs[0], ClsExprs.size(),
2701 StartLoc, EndLoc);
2702
2703 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2704 // To turn off a warning, type-cast to 'id'
2705 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2706 NoTypeInfoCStyleCastExpr(Context,
2707 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002708 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002709 // struct objc_super
2710 QualType superType = getSuperStructType();
2711 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002712
Francois Pichet62ec1f22011-09-17 17:15:52 +00002713 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002714 SynthSuperConstructorFunctionDecl();
2715 // Simulate a constructor call...
2716 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002717 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002718 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002719 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002720 superType, VK_LValue,
2721 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002722 // The code for super is a little tricky to prevent collision with
2723 // the structure definition in the header. The rewriter has it's own
2724 // internal definition (__rw_objc_super) that is uses. This is why
2725 // we need the cast below. For example:
2726 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2727 //
John McCall2de56d12010-08-25 11:45:40 +00002728 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002729 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002730 VK_RValue, OK_Ordinary,
2731 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2733 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002734 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002735 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736 // (struct objc_super) { <exprs from above> }
2737 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002738 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 SourceLocation());
2740 TypeSourceInfo *superTInfo
2741 = Context->getTrivialTypeSourceInfo(superType);
2742 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002743 superType, VK_LValue,
2744 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002745 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002746 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002747 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002748 VK_RValue, OK_Ordinary,
2749 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002750 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002751 MsgExprs.push_back(SuperRep);
2752 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002753 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002754
2755 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002756 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002757 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002758 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002759 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002760 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2762 &ClsExprs[0],
2763 ClsExprs.size(),
2764 StartLoc, EndLoc);
2765 MsgExprs.push_back(Cls);
2766 break;
2767 }
2768
2769 case ObjCMessageExpr::SuperInstance:{
2770 MsgSendFlavor = MsgSendSuperFunctionDecl;
2771 if (MsgSendStretFlavor)
2772 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2773 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2774 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002775 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776
2777 InitExprs.push_back(
2778 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002779 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002781 false,
John McCallf89e55a2010-11-18 06:31:45 +00002782 Context->getObjCIdType(),
2783 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002784 ); // set the 'receiver'.
2785
2786 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002787 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002788 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2790 &ClsExprs[0],
2791 ClsExprs.size(),
2792 StartLoc, EndLoc);
2793 // (Class)objc_getClass("CurrentClass")
2794 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2795 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002796 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797 ClsExprs.clear();
2798 ClsExprs.push_back(ArgExpr);
2799 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2800 &ClsExprs[0], ClsExprs.size(),
2801 StartLoc, EndLoc);
2802
2803 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2804 // To turn off a warning, type-cast to 'id'
2805 InitExprs.push_back(
2806 // set 'super class', using class_getSuperclass().
2807 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002808 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809 // struct objc_super
2810 QualType superType = getSuperStructType();
2811 Expr *SuperRep;
2812
Francois Pichet62ec1f22011-09-17 17:15:52 +00002813 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002814 SynthSuperConstructorFunctionDecl();
2815 // Simulate a constructor call...
2816 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002817 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002818 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002819 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002820 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 // The code for super is a little tricky to prevent collision with
2822 // the structure definition in the header. The rewriter has it's own
2823 // internal definition (__rw_objc_super) that is uses. This is why
2824 // we need the cast below. For example:
2825 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2826 //
John McCall2de56d12010-08-25 11:45:40 +00002827 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002829 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830 SourceLocation());
2831 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2832 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002833 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 } else {
2835 // (struct objc_super) { <exprs from above> }
2836 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002837 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 SourceLocation());
2839 TypeSourceInfo *superTInfo
2840 = Context->getTrivialTypeSourceInfo(superType);
2841 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002842 superType, VK_RValue, ILE,
2843 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 }
2845 MsgExprs.push_back(SuperRep);
2846 break;
2847 }
2848
2849 case ObjCMessageExpr::Instance: {
2850 // Remove all type-casts because it may contain objc-style types; e.g.
2851 // Foo<Proto> *.
2852 Expr *recExpr = Exp->getInstanceReceiver();
2853 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2854 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002855 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2856 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2857 ? CK_BlockPointerToObjCPointerCast
2858 : CK_CPointerToObjCPointerCast;
2859
Douglas Gregor04badcf2010-04-21 00:45:42 +00002860 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002861 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002862 MsgExprs.push_back(recExpr);
2863 break;
2864 }
2865 }
2866
Steve Naroffbeaf2992007-11-03 11:27:19 +00002867 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002868 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002869 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff934f2762007-10-24 22:48:43 +00002870 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002871 &SelExprs[0], SelExprs.size(),
2872 StartLoc,
2873 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002874 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Steve Naroff934f2762007-10-24 22:48:43 +00002876 // Now push any user supplied arguments.
2877 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002878 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002879 // Make all implicit casts explicit...ICE comes in handy:-)
2880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2881 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002882 QualType type = ICE->getType();
2883 if (needToScanForQualifiers(type))
2884 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002885 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002886 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002887 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002888 CastKind CK;
2889 if (SubExpr->getType()->isIntegralType(*Context) &&
2890 type->isBooleanType()) {
2891 CK = CK_IntegralToBoolean;
2892 } else if (type->isObjCObjectPointerType()) {
2893 if (SubExpr->getType()->isBlockPointerType()) {
2894 CK = CK_BlockPointerToObjCPointerCast;
2895 } else if (SubExpr->getType()->isPointerType()) {
2896 CK = CK_CPointerToObjCPointerCast;
2897 } else {
2898 CK = CK_BitCast;
2899 }
2900 } else {
2901 CK = CK_BitCast;
2902 }
2903
2904 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002905 }
2906 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002907 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002908 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002909 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002910 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002911 CastKind CK;
2912 if (userExpr->getType()->isIntegralType(*Context)) {
2913 CK = CK_IntegralToPointer;
2914 } else if (userExpr->getType()->isBlockPointerType()) {
2915 CK = CK_BlockPointerToObjCPointerCast;
2916 } else if (userExpr->getType()->isPointerType()) {
2917 CK = CK_CPointerToObjCPointerCast;
2918 } else {
2919 CK = CK_BitCast;
2920 }
John McCall9d125032010-01-15 18:39:57 +00002921 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002922 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002923 }
Mike Stump1eb44332009-09-09 15:08:12 +00002924 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002925 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002926 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2927 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002928 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002929 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002930 }
Steve Naroffab972d32007-11-04 22:37:50 +00002931 // Generate the funky cast.
2932 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002933 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002934 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Steve Naroffab972d32007-11-04 22:37:50 +00002936 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002937 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2938 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2939 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002940 ArgTypes.push_back(Context->getObjCIdType());
2941 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002942 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002943 // Push any user argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -07002944 for (const auto *PI : OMD->params()) {
2945 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002946 ? Context->getObjCIdType()
Stephen Hines651f13c2014-04-23 16:59:28 -07002947 : PI->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002948 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002949 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002950 ArgTypes.push_back(t);
2951 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002952 returnType = Exp->getType();
2953 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002954 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002955 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002956 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002957 }
2958 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002959 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Steve Naroffab972d32007-11-04 22:37:50 +00002961 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002962 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002963 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002964
Mike Stump1eb44332009-09-09 15:08:12 +00002965 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002966 // If we don't do this cast, we get the following bizarre warning/note:
2967 // xx.m:13: warning: function called through a non-compatible type
2968 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002969 cast = NoTypeInfoCStyleCastExpr(Context,
2970 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002971 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Steve Naroffab972d32007-11-04 22:37:50 +00002973 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002974 // If we don't have a method decl, force a variadic cast.
2975 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalle23cf432010-12-14 08:05:40 +00002976 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002977 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002978 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002979 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002980 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002981
2982 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002983 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002984
John McCall183700f2009-09-21 23:43:11 +00002985 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002986 CallExpr *CE = new (Context)
2987 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002988 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002989 if (MsgSendStretFlavor) {
2990 // We have the method which returns a struct/union. Must also generate
2991 // call to objc_msgSend_stret and hang both varieties on a conditional
2992 // expression which dictate which one to envoke depending on size of
2993 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002994
2995 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2996 msgSendType, returnType,
2997 ArgTypes, MsgExprs,
2998 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003000 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003001 UnaryExprOrTypeTraitExpr *sizeofExpr =
3002 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3003 Context->getTrivialTypeSourceInfo(returnType),
3004 Context->getSizeType(), SourceLocation(),
3005 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003006 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3007 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3008 // For X86 it is more complicated and some kind of target specific routine
3009 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003010 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003011 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003012 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3013 llvm::APInt(IntSize, 8),
3014 Context->IntTy,
3015 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003016 BinaryOperator *lessThanExpr =
3017 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003018 VK_RValue, OK_Ordinary, SourceLocation(),
3019 false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003020 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003021 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003022 new (Context) ConditionalOperator(lessThanExpr,
3023 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003024 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003025 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003026 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3027 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003028 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003029 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003030 return ReplacingStmt;
3031}
3032
Steve Naroffb29b4272008-04-14 22:03:09 +00003033Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003034 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3035 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Steve Naroff934f2762007-10-24 22:48:43 +00003037 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003038 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003040 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003041 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003042}
3043
Steve Naroff621edce2009-04-29 16:37:50 +00003044// typedef struct objc_object Protocol;
3045QualType RewriteObjC::getProtocolType() {
3046 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003047 TypeSourceInfo *TInfo
3048 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003049 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003050 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003051 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003052 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003053 }
3054 return Context->getTypeDeclType(ProtocolTypeDecl);
3055}
3056
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003057/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003058/// a synthesized/forward data reference (to the protocol's metadata).
3059/// The forward references (and metadata) are generated in
3060/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003061Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003062 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3063 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003064 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003065 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003066 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003067 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3068 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003069 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003070 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003071 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003072 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003073 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003074 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003075 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003076 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003077 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003078 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003080}
3081
Mike Stump1eb44332009-09-09 15:08:12 +00003082bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003083 const char *endBuf) {
3084 while (startBuf < endBuf) {
3085 if (*startBuf == '#') {
3086 // Skip whitespace.
3087 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3088 ;
3089 if (!strncmp(startBuf, "if", strlen("if")) ||
3090 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3091 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3092 !strncmp(startBuf, "define", strlen("define")) ||
3093 !strncmp(startBuf, "undef", strlen("undef")) ||
3094 !strncmp(startBuf, "else", strlen("else")) ||
3095 !strncmp(startBuf, "elif", strlen("elif")) ||
3096 !strncmp(startBuf, "endif", strlen("endif")) ||
3097 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3098 !strncmp(startBuf, "include", strlen("include")) ||
3099 !strncmp(startBuf, "import", strlen("import")) ||
3100 !strncmp(startBuf, "include_next", strlen("include_next")))
3101 return true;
3102 }
3103 startBuf++;
3104 }
3105 return false;
3106}
3107
Fariborz Jahanian58457172011-12-05 18:43:13 +00003108/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003109/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003110void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003111 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003113 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003114 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003115 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003116 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003117 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003119 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003120 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003121 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003122
Steve Narofffea763e82007-11-14 19:25:57 +00003123 const char *startBuf = SM->getCharacterData(LocStart);
3124 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003126 // If no ivars and no root or if its root, directly or indirectly,
3127 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003128 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003129 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003130 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003131 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003132 return;
3133 }
Mike Stump1eb44332009-09-09 15:08:12 +00003134
3135 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003136 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003137 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003138 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003139 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003140 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003141
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003142 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003143 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003144 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003145 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003146 // If the buffer contains preprocessor directives, we do more fine-grained
3147 // rewrites. This is intended to fix code that looks like (which occurs in
3148 // NSURL.h, for example):
3149 //
3150 // #ifdef XYZ
3151 // @interface Foo : NSObject
3152 // #else
3153 // @interface FooBar : NSObject
3154 // #endif
3155 // {
3156 // int i;
3157 // }
3158 // @end
3159 //
3160 // This clause is segregated to avoid breaking the common case.
3161 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003162 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003163 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003164 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003165 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003166
Chris Lattnercafeb352009-02-20 18:18:36 +00003167 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003168 // advance to the end of the referenced protocols.
3169 while (endHeader < cursor && *endHeader != '>') endHeader++;
3170 endHeader++;
3171 }
3172 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003173 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003174 } else {
3175 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003176 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003177 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003178 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003179 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003180 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003181 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003182 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003183 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003184
Steve Narofffea763e82007-11-14 19:25:57 +00003185 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003186 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003187 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003188 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003189 }
3190 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Steve Narofffea763e82007-11-14 19:25:57 +00003192 // Now comment out any visibility specifiers.
3193 while (cursor < endBuf) {
3194 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003195 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003196 // Skip whitespace.
3197 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3198 /*scan*/;
3199
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003200 // FIXME: presence of @public, etc. inside comment results in
3201 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003202 if (!strncmp(cursor, "public", strlen("public")) ||
3203 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003204 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003205 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003206 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003207 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003208 // FIXME: If there are cases where '<' is used in ivar declaration part
3209 // of user code, then scan the ivar list and use needToScanForQualifiers
3210 // for type checking.
3211 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003212 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003213 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003214 cursor = strchr(cursor, '>');
3215 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003216 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003217 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003218 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003219 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003220 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003221 }
Steve Narofffea763e82007-11-14 19:25:57 +00003222 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003223 }
Steve Narofffea763e82007-11-14 19:25:57 +00003224 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003225 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003226 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003227 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003228 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003229 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003230 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003231 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003232 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003233 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003234 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003235 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003236 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003237 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003238}
3239
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003240//===----------------------------------------------------------------------===//
3241// Meta Data Emission
3242//===----------------------------------------------------------------------===//
3243
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003244
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003245/// RewriteImplementations - This routine rewrites all method implementations
3246/// and emits meta-data.
3247
Steve Narofface66252008-11-13 20:07:04 +00003248void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003249 int ClsDefCount = ClassImplementation.size();
3250 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003252 // Rewrite implemented methods
3253 for (int i = 0; i < ClsDefCount; i++)
3254 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003256 for (int i = 0; i < CatDefCount; i++)
3257 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003258}
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003260void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3261 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003262 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003263 assert(BlockByRefDeclNo.count(VD) &&
3264 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003265 if (def)
3266 ResultStr += "struct ";
3267 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003268 "_" + utostr(BlockByRefDeclNo[VD]) ;
3269}
3270
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003271static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3272 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3273 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3274 return false;
3275}
3276
Steve Naroff54055232008-10-27 17:20:55 +00003277std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003278 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003279 std::string Tag) {
3280 const FunctionType *AFT = CE->getFunctionType();
Stephen Hines651f13c2014-04-23 16:59:28 -07003281 QualType RT = AFT->getReturnType();
Steve Naroff54055232008-10-27 17:20:55 +00003282 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003283 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003284 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003285
Steve Naroff54055232008-10-27 17:20:55 +00003286 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregor72564e72009-02-26 23:50:07 +00003288 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003289 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003290 // block (to reference imported block decl refs).
3291 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003292 } else if (BD->param_empty()) {
3293 S += "(" + StructRef + " *__cself)";
3294 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003295 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003296 assert(FT && "SynthesizeBlockFunc: No function proto");
3297 S += '(';
3298 // first add the implicit argument.
3299 S += StructRef + " *__cself, ";
3300 std::string ParamStr;
3301 for (BlockDecl::param_iterator AI = BD->param_begin(),
3302 E = BD->param_end(); AI != E; ++AI) {
3303 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003304 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003305 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003306 (void)convertBlockPointerToFunctionPointer(QT);
3307 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003308 S += ParamStr;
3309 }
3310 if (FT->isVariadic()) {
3311 if (!BD->param_empty()) S += ", ";
3312 S += "...";
3313 }
3314 S += ')';
3315 }
3316 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Steve Naroff54055232008-10-27 17:20:55 +00003318 // Create local declarations to avoid rewriting all closure decl ref exprs.
3319 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00003320 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003321 E = BlockByRefDecls.end(); I != E; ++I) {
3322 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003323 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003324 std::string TypeString;
3325 RewriteByRefString(TypeString, Name, (*I));
3326 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003327 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003328 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003329 }
Steve Naroff54055232008-10-27 17:20:55 +00003330 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003331 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003332 E = BlockByCopyDecls.end(); I != E; ++I) {
3333 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003334 // Handle nested closure invocation. For example:
3335 //
3336 // void (^myImportedClosure)(void);
3337 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003338 //
Steve Naroff54055232008-10-27 17:20:55 +00003339 // void (^anotherClosure)(void);
3340 // anotherClosure = ^(void) {
3341 // myImportedClosure(); // import and invoke the closure
3342 // };
3343 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003344 if (isTopLevelBlockPointerType((*I)->getType())) {
3345 RewriteBlockPointerTypeVariable(S, (*I));
3346 S += " = (";
3347 RewriteBlockPointerType(S, (*I)->getType());
3348 S += ")";
3349 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3350 }
3351 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003352 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003353 QualType QT = (*I)->getType();
3354 if (HasLocalVariableExternalStorage(*I))
3355 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003356 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003357 S += Name + " = __cself->" +
3358 (*I)->getNameAsString() + "; // bound by copy\n";
3359 }
Steve Naroff54055232008-10-27 17:20:55 +00003360 }
3361 std::string RewrittenStr = RewrittenBlockExprs[CE];
3362 const char *cstr = RewrittenStr.c_str();
3363 while (*cstr++ != '{') ;
3364 S += cstr;
3365 S += "\n";
3366 return S;
3367}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003368
Steve Naroff54055232008-10-27 17:20:55 +00003369std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003370 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003371 std::string Tag) {
3372 std::string StructRef = "struct " + Tag;
3373 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Steve Naroff54055232008-10-27 17:20:55 +00003375 S += funcName;
3376 S += "_block_copy_" + utostr(i);
3377 S += "(" + StructRef;
3378 S += "*dst, " + StructRef;
3379 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003380 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003381 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003382 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003383 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003385 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003386 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003387 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003388 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003389 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003390 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003391 else
3392 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003393 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003394 S += "}\n";
3395
Steve Naroff54055232008-10-27 17:20:55 +00003396 S += "\nstatic void __";
3397 S += funcName;
3398 S += "_block_dispose_" + utostr(i);
3399 S += "(" + StructRef;
3400 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003401 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003402 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003403 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003404 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003405 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003406 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003407 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003408 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003409 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003410 else
3411 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003412 }
Mike Stump1eb44332009-09-09 15:08:12 +00003413 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003414 return S;
3415}
3416
Steve Naroff01aec112009-12-06 21:14:13 +00003417std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3418 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003419 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003420 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Steve Naroff54055232008-10-27 17:20:55 +00003422 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003423 S += " struct " + Desc;
3424 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Steve Naroff01aec112009-12-06 21:14:13 +00003426 Constructor += "(void *fp, "; // Invoke function pointer.
3427 Constructor += "struct " + Desc; // Descriptor pointer.
3428 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Steve Naroff54055232008-10-27 17:20:55 +00003430 if (BlockDeclRefs.size()) {
3431 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003432 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003433 E = BlockByCopyDecls.end(); I != E; ++I) {
3434 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003435 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003436 std::string ArgName = "_" + FieldName;
3437 // Handle nested closure invocation. For example:
3438 //
3439 // void (^myImportedBlock)(void);
3440 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003441 //
Steve Naroff54055232008-10-27 17:20:55 +00003442 // void (^anotherBlock)(void);
3443 // anotherBlock = ^(void) {
3444 // myImportedBlock(); // import and invoke the closure
3445 // };
3446 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003447 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003448 S += "struct __block_impl *";
3449 Constructor += ", void *" + ArgName;
3450 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003451 QualType QT = (*I)->getType();
3452 if (HasLocalVariableExternalStorage(*I))
3453 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003454 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3455 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003456 Constructor += ", " + ArgName;
3457 }
3458 S += FieldName + ";\n";
3459 }
3460 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003461 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003462 E = BlockByRefDecls.end(); I != E; ++I) {
3463 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003464 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003465 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003466 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003467 std::string TypeString;
3468 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003469 TypeString += " *";
3470 FieldName = TypeString + FieldName;
3471 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003472 Constructor += ", " + ArgName;
3473 }
3474 S += FieldName + "; // by ref\n";
3475 }
3476 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003477 Constructor += ", int flags=0)";
3478 // Initialize all "by copy" arguments.
3479 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00003480 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003481 E = BlockByCopyDecls.end(); I != E; ++I) {
3482 std::string Name = (*I)->getNameAsString();
3483 if (firsTime) {
3484 Constructor += " : ";
3485 firsTime = false;
3486 }
3487 else
3488 Constructor += ", ";
3489 if (isTopLevelBlockPointerType((*I)->getType()))
3490 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3491 else
3492 Constructor += Name + "(_" + Name + ")";
3493 }
3494 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00003495 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003496 E = BlockByRefDecls.end(); I != E; ++I) {
3497 std::string Name = (*I)->getNameAsString();
3498 if (firsTime) {
3499 Constructor += " : ";
3500 firsTime = false;
3501 }
3502 else
3503 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003504 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003505 }
3506
3507 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003508 if (GlobalVarDecl)
3509 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3510 else
3511 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003512 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Steve Naroff01aec112009-12-06 21:14:13 +00003514 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003515 } else {
3516 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003517 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003518 if (GlobalVarDecl)
3519 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3520 else
3521 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003522 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3523 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003524 }
3525 Constructor += " ";
3526 Constructor += "}\n";
3527 S += Constructor;
3528 S += "};\n";
3529 return S;
3530}
3531
Steve Naroff01aec112009-12-06 21:14:13 +00003532std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3533 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003534 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003535 unsigned hasCopy) {
3536 std::string S = "\nstatic struct " + DescTag;
3537
3538 S += " {\n unsigned long reserved;\n";
3539 S += " unsigned long Block_size;\n";
3540 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003541 S += " void (*copy)(struct ";
3542 S += ImplTag; S += "*, struct ";
3543 S += ImplTag; S += "*);\n";
3544
3545 S += " void (*dispose)(struct ";
3546 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003547 }
3548 S += "} ";
3549
3550 S += DescTag + "_DATA = { 0, sizeof(struct ";
3551 S += ImplTag + ")";
3552 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003553 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3554 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003555 }
3556 S += "};\n";
3557 return S;
3558}
3559
Steve Naroff54055232008-10-27 17:20:55 +00003560void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003561 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003562 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003563 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003564 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003565 bool RewriteSC = (GlobalVarDecl &&
3566 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003567 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003568 GlobalVarDecl->getType().getCVRQualifiers());
3569 if (RewriteSC) {
3570 std::string SC(" void __");
3571 SC += GlobalVarDecl->getNameAsString();
3572 SC += "() {}";
3573 InsertText(FunLocStart, SC);
3574 }
3575
Steve Naroff54055232008-10-27 17:20:55 +00003576 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003577 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3578 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003579 // Need to copy-in the inner copied-in variables not actually used in this
3580 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003581 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003582 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003583 ValueDecl *VD = Exp->getDecl();
3584 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003585 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003586 BlockByCopyDeclsPtrSet.insert(VD);
3587 BlockByCopyDecls.push_back(VD);
3588 }
John McCallf4b88a42012-03-10 09:33:50 +00003589 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003590 BlockByRefDeclsPtrSet.insert(VD);
3591 BlockByRefDecls.push_back(VD);
3592 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003593 // imported objects in the inner blocks not used in the outer
3594 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003595 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003596 VD->getType()->isObjCObjectPointerType() ||
3597 VD->getType()->isBlockPointerType())
3598 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003599 }
Steve Naroff54055232008-10-27 17:20:55 +00003600
Daniel Dunbar4087f272010-08-17 22:39:59 +00003601 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3602 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Steve Naroff01aec112009-12-06 21:14:13 +00003604 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003605
Benjamin Kramerd999b372010-02-14 14:14:16 +00003606 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003607
Steve Naroff01aec112009-12-06 21:14:13 +00003608 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Benjamin Kramerd999b372010-02-14 14:14:16 +00003610 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003611
3612 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003613 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003614 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003615 }
Steve Naroff01aec112009-12-06 21:14:13 +00003616 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3617 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003618 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Steve Naroff54055232008-10-27 17:20:55 +00003620 BlockDeclRefs.clear();
3621 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003622 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003623 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003624 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003625 ImportedBlockDecls.clear();
3626 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003627 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003628 // Must insert any 'const/volatile/static here. Since it has been
3629 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003630 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003631 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003632 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003633 if (GlobalVarDecl->getType().isConstQualified())
3634 SC += "const ";
3635 if (GlobalVarDecl->getType().isVolatileQualified())
3636 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003637 if (GlobalVarDecl->getType().isRestrictQualified())
3638 SC += "restrict ";
3639 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003640 }
3641
Steve Naroff54055232008-10-27 17:20:55 +00003642 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003643 InnerDeclRefsCount.clear();
3644 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003645 RewrittenBlockExprs.clear();
3646}
3647
3648void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3649 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003650 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Steve Naroff54055232008-10-27 17:20:55 +00003652 SynthesizeBlockLiterals(FunLocStart, FuncName);
3653}
3654
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003655static void BuildUniqueMethodName(std::string &Name,
3656 ObjCMethodDecl *MD) {
3657 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003658 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003659 Name += "__" + MD->getSelector().getAsString();
3660 // Convert colons to underscores.
3661 std::string::size_type loc = 0;
3662 while ((loc = Name.find(":", loc)) != std::string::npos)
3663 Name.replace(loc, 1, "_");
3664}
3665
Steve Naroff54055232008-10-27 17:20:55 +00003666void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003667 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3668 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003669 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003670 std::string FuncName;
3671 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003672 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003673}
3674
3675void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003676 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003677 if (*CI) {
3678 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3679 GetBlockDeclRefExprs(CBE->getBody());
3680 else
3681 GetBlockDeclRefExprs(*CI);
3682 }
3683 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003684 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3685 if (DRE->refersToEnclosingLocal()) {
3686 // FIXME: Handle enums.
3687 if (!isa<FunctionDecl>(DRE->getDecl()))
3688 BlockDeclRefs.push_back(DRE);
3689 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3690 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003691 }
John McCallf4b88a42012-03-10 09:33:50 +00003692 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003693
Steve Naroff54055232008-10-27 17:20:55 +00003694 return;
3695}
3696
Craig Topper6b9240e2013-07-05 19:34:19 +00003697void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3698 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003699 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003700 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003701 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003702 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3703 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003704 GetInnerBlockDeclRefExprs(CBE->getBody(),
3705 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003706 InnerContexts);
3707 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003708 else
3709 GetInnerBlockDeclRefExprs(*CI,
3710 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003711 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003712
3713 }
3714 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003715 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3716 if (DRE->refersToEnclosingLocal()) {
3717 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3718 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3719 InnerBlockDeclRefs.push_back(DRE);
3720 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3721 if (Var->isFunctionOrMethodVarDecl())
3722 ImportedLocalExternalDecls.insert(Var);
3723 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003724 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003725
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003726 return;
3727}
3728
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003729/// convertFunctionTypeOfBlocks - This routine converts a function type
3730/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003731/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003732/// all block pointers to function pointers.
3733QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3734 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3735 // FTP will be null for closures that don't take arguments.
3736 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003737 SmallVector<QualType, 8> ArgTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07003738 QualType Res = FT->getReturnType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003739 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003740
3741 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003742 for (auto &I : FTP->param_types()) {
3743 QualType t = I;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003744 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003745 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003746 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003747 ArgTypes.push_back(t);
3748 }
3749 }
3750 QualType FuncType;
3751 // FIXME. Does this work if block takes no argument but has a return type
3752 // which is of block type?
3753 if (HasBlockType)
Jordan Rosebea522f2013-03-08 21:51:21 +00003754 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003755 else FuncType = QualType(FT, 0);
3756 return FuncType;
3757}
3758
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003759Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003760 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003761 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003764 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003765 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003766 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003767 }
3768 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3769 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3770 }
3771 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3772 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3773 else if (const ConditionalOperator *CEXPR =
3774 dyn_cast<ConditionalOperator>(BlockExp)) {
3775 Expr *LHSExp = CEXPR->getLHS();
3776 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3777 Expr *RHSExp = CEXPR->getRHS();
3778 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3779 Expr *CONDExp = CEXPR->getCond();
3780 ConditionalOperator *CondExpr =
3781 new (Context) ConditionalOperator(CONDExp,
3782 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003783 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003784 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003785 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003786 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3787 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003788 } else if (const PseudoObjectExpr *POE
3789 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3790 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003791 } else {
3792 assert(1 && "RewriteBlockClass: Bad type");
3793 }
3794 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003795 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003796 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003797 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003798 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003800 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003801 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003802 &Context->Idents.get("__block_impl"));
3803 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003804
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003805 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003806 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003808 // Push the block argument type.
3809 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003810 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003811 for (auto &I : FTP->param_types()) {
3812 QualType t = I;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003813 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003814 if (!convertBlockPointerToFunctionPointer(t))
3815 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003816 ArgTypes.push_back(t);
3817 }
Steve Naroff54055232008-10-27 17:20:55 +00003818 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003819 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003820 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003822 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003823
John McCall9d125032010-01-15 18:39:57 +00003824 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003825 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003826 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003827 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003828 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3829 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Douglas Gregor44b43212008-12-11 16:49:14 +00003832 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003833 SourceLocation(),
3834 &Context->Idents.get("FuncPtr"),
3835 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003836 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003837 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003838 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003839 FD->getType(), VK_LValue,
3840 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003842
John McCall9d125032010-01-15 18:39:57 +00003843 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003844 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003845 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Chris Lattner5f9e2722011-07-23 10:55:15 +00003847 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003848 // Add the implicit argument.
3849 BlkExprs.push_back(BlkCast);
3850 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003851 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003852 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003853 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003854 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003855 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003856 Exp->getType(), VK_RValue,
3857 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003858 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003859}
3860
Steve Naroff621edce2009-04-29 16:37:50 +00003861// We need to return the rewritten expression to handle cases where the
3862// BlockDeclRefExpr is embedded in another expression being rewritten.
3863// For example:
3864//
3865// int main() {
3866// __block Foo *f;
3867// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003868//
Steve Naroff621edce2009-04-29 16:37:50 +00003869// void (^myblock)() = ^() {
3870// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3871// i = 77;
3872// };
3873//}
John McCallf4b88a42012-03-10 09:33:50 +00003874Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003875 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003876 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003877 ValueDecl *VD = DeclRefExp->getDecl();
3878 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003879
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003880 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003881 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003882 &Context->Idents.get("__forwarding"),
3883 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003884 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003885 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003886 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3887 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003888 FD->getType(), VK_LValue,
3889 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003890
Chris Lattner5f9e2722011-07-23 10:55:15 +00003891 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003892 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003893 &Context->Idents.get(Name),
3894 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003895 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003896 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003897 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003898 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003899
3900
3901
Steve Naroffdf8570d2009-02-02 17:19:26 +00003902 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003903 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3904 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003905 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003906 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003907 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003908}
3909
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003910// Rewrites the imported local variable V with external storage
3911// (static, extern, etc.) as *V
3912//
3913Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3914 ValueDecl *VD = DRE->getDecl();
3915 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3916 if (!ImportedLocalExternalDecls.count(Var))
3917 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003918 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3919 VK_LValue, OK_Ordinary,
3920 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003921 // Need parens to enforce precedence.
3922 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3923 Exp);
3924 ReplaceStmt(DRE, PE);
3925 return PE;
3926}
3927
Steve Naroffb2f9e512008-11-03 23:29:32 +00003928void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3929 SourceLocation LocStart = CE->getLParenLoc();
3930 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003931
3932 // Need to avoid trying to rewrite synthesized casts.
3933 if (LocStart.isInvalid())
3934 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003935 // Need to avoid trying to rewrite casts contained in macros.
3936 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3937 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Steve Naroff54055232008-10-27 17:20:55 +00003939 const char *startBuf = SM->getCharacterData(LocStart);
3940 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003941 QualType QT = CE->getType();
3942 const Type* TypePtr = QT->getAs<Type>();
3943 if (isa<TypeOfExprType>(TypePtr)) {
3944 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3945 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3946 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003947 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003948 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003949 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003950 return;
3951 }
Steve Naroff54055232008-10-27 17:20:55 +00003952 // advance the location to startArgList.
3953 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Steve Naroff54055232008-10-27 17:20:55 +00003955 while (*argPtr++ && (argPtr < endBuf)) {
3956 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003957 case '^':
3958 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003959 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003960 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003961 break;
Steve Naroff54055232008-10-27 17:20:55 +00003962 }
3963 }
3964 return;
3965}
3966
3967void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3968 SourceLocation DeclLoc = FD->getLocation();
3969 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Steve Naroff54055232008-10-27 17:20:55 +00003971 // We have 1 or more arguments that have closure pointers.
3972 const char *startBuf = SM->getCharacterData(DeclLoc);
3973 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00003974
Steve Naroff54055232008-10-27 17:20:55 +00003975 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Steve Naroff54055232008-10-27 17:20:55 +00003977 parenCount++;
3978 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003979 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00003980 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Steve Naroff54055232008-10-27 17:20:55 +00003982 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Steve Naroff54055232008-10-27 17:20:55 +00003984 while (*argPtr++ && parenCount) {
3985 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003986 case '^':
3987 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003988 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003989 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003990 break;
3991 case '(':
3992 parenCount++;
3993 break;
3994 case ')':
3995 parenCount--;
3996 break;
Steve Naroff54055232008-10-27 17:20:55 +00003997 }
3998 }
3999 return;
4000}
4001
4002bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004003 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004004 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004005 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004006 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004007 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004008 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004009 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004010 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004011 }
4012 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004013 for (const auto &I : FTP->param_types())
4014 if (isTopLevelBlockPointerType(I))
Steve Naroff54055232008-10-27 17:20:55 +00004015 return true;
4016 }
4017 return false;
4018}
4019
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004020bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4021 const FunctionProtoType *FTP;
4022 const PointerType *PT = QT->getAs<PointerType>();
4023 if (PT) {
4024 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4025 } else {
4026 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4027 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4028 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4029 }
4030 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004031 for (const auto &I : FTP->param_types()) {
4032 if (I->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004033 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004034 if (I->isObjCObjectPointerType() &&
4035 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004036 return true;
4037 }
4038
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004039 }
4040 return false;
4041}
4042
Ted Kremenek8189cde2009-02-07 01:47:29 +00004043void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4044 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004045 const char *argPtr = strchr(Name, '(');
4046 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Steve Naroff54055232008-10-27 17:20:55 +00004048 LParen = argPtr; // output the start.
4049 argPtr++; // skip past the left paren.
4050 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Steve Naroff54055232008-10-27 17:20:55 +00004052 while (*argPtr && parenCount) {
4053 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004054 case '(': parenCount++; break;
4055 case ')': parenCount--; break;
4056 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004057 }
4058 if (parenCount) argPtr++;
4059 }
4060 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4061 RParen = argPtr; // output the end
4062}
4063
4064void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4066 RewriteBlockPointerFunctionArgs(FD);
4067 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004068 }
Steve Naroff54055232008-10-27 17:20:55 +00004069 // Handle Variables and Typedefs.
4070 SourceLocation DeclLoc = ND->getLocation();
4071 QualType DeclT;
4072 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4073 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004074 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004075 DeclT = TDD->getUnderlyingType();
4076 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4077 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004078 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004079 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Steve Naroff54055232008-10-27 17:20:55 +00004081 const char *startBuf = SM->getCharacterData(DeclLoc);
4082 const char *endBuf = startBuf;
4083 // scan backward (from the decl location) for the end of the previous decl.
4084 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4085 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004086 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004087 std::string buf;
4088 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004089 // *startBuf != '^' if we are dealing with a pointer to function that
4090 // may take block argument types (which will be handled below).
4091 if (*startBuf == '^') {
4092 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004093 buf = '*';
4094 startBuf++;
4095 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004096 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004097 while (*startBuf != ')') {
4098 buf += *startBuf;
4099 startBuf++;
4100 OrigLength++;
4101 }
4102 buf += ')';
4103 OrigLength++;
4104
4105 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4106 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004107 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004108 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004109 DeclLoc = ND->getLocation();
4110 startBuf = SM->getCharacterData(DeclLoc);
4111 const char *argListBegin, *argListEnd;
4112 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4113 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004114 if (*argListBegin == '^')
4115 buf += '*';
4116 else if (*argListBegin == '<') {
4117 buf += "/*";
4118 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004119 OrigLength++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004120 while (*argListBegin != '>') {
4121 buf += *argListBegin++;
4122 OrigLength++;
4123 }
4124 buf += *argListBegin;
4125 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004126 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004127 else
4128 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004129 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004130 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004131 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004132 buf += ')';
4133 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004134 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004135 ReplaceText(Start, OrigLength, buf);
4136
Steve Naroff54055232008-10-27 17:20:55 +00004137 return;
4138}
4139
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004140
4141/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4142/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4143/// struct Block_byref_id_object *src) {
4144/// _Block_object_assign (&_dest->object, _src->object,
4145/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4146/// [|BLOCK_FIELD_IS_WEAK]) // object
4147/// _Block_object_assign(&_dest->object, _src->object,
4148/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4149/// [|BLOCK_FIELD_IS_WEAK]) // block
4150/// }
4151/// And:
4152/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4153/// _Block_object_dispose(_src->object,
4154/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4155/// [|BLOCK_FIELD_IS_WEAK]) // object
4156/// _Block_object_dispose(_src->object,
4157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4158/// [|BLOCK_FIELD_IS_WEAK]) // block
4159/// }
4160
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004161std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4162 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004163 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004164 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004165 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004166 CopyDestroyCache.insert(flag);
4167 S = "static void __Block_byref_id_object_copy_";
4168 S += utostr(flag);
4169 S += "(void *dst, void *src) {\n";
4170
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004171 // offset into the object pointer is computed as:
4172 // void * + void* + int + int + void* + void *
4173 unsigned IntSize =
4174 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4175 unsigned VoidPtrSize =
4176 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4177
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004178 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004179 S += " _Block_object_assign((char*)dst + ";
4180 S += utostr(offset);
4181 S += ", *(void * *) ((char*)src + ";
4182 S += utostr(offset);
4183 S += "), ";
4184 S += utostr(flag);
4185 S += ");\n}\n";
4186
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004187 S += "static void __Block_byref_id_object_dispose_";
4188 S += utostr(flag);
4189 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004190 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4191 S += utostr(offset);
4192 S += "), ";
4193 S += utostr(flag);
4194 S += ");\n}\n";
4195 return S;
4196}
4197
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004198/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4199/// the declaration into:
4200/// struct __Block_byref_ND {
4201/// void *__isa; // NULL for everything except __weak pointers
4202/// struct __Block_byref_ND *__forwarding;
4203/// int32_t __flags;
4204/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004205/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4206/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004207/// typex ND;
4208/// };
4209///
4210/// It then replaces declaration of ND variable with:
4211/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4212/// __size=sizeof(struct __Block_byref_ND),
4213/// ND=initializer-if-any};
4214///
4215///
4216void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004217 // Insert declaration for the function in which block literal is
4218 // used.
4219 if (CurFunctionDeclToDeclareForBlock)
4220 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004221 int flag = 0;
4222 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004223 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004224 if (DeclLoc.isInvalid())
4225 // If type location is missing, it is because of missing type (a warning).
4226 // Use variable's location which is good for this case.
4227 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004228 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004229 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004230 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004231 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004232 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004233 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004234 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004235 ByrefType += " {\n";
4236 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004237 RewriteByRefString(ByrefType, Name, ND);
4238 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004239 ByrefType += " int __flags;\n";
4240 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004241 // Add void *__Block_byref_id_object_copy;
4242 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004243 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004244 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004245 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004246 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4247 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004248 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004249
4250 QualType T = Ty;
4251 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004252 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004253
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004254 ByrefType += " " + Name + ";\n";
4255 ByrefType += "};\n";
4256 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004257 SourceLocation FunLocStart;
4258 if (CurFunctionDef)
4259 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4260 else {
4261 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4262 FunLocStart = CurMethodDef->getLocStart();
4263 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004264 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004265 if (Ty.isObjCGCWeak()) {
4266 flag |= BLOCK_FIELD_IS_WEAK;
4267 isa = 1;
4268 }
4269
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004270 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004271 flag = BLOCK_BYREF_CALLER;
4272 QualType Ty = ND->getType();
4273 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4274 if (Ty->isBlockPointerType())
4275 flag |= BLOCK_FIELD_IS_BLOCK;
4276 else
4277 flag |= BLOCK_FIELD_IS_OBJECT;
4278 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004279 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004280 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004281 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004282
4283 // struct __Block_byref_ND ND =
4284 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4285 // initializer-if-any};
4286 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004287 unsigned flags = 0;
4288 if (HasCopyAndDispose)
4289 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004290 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004291 ByrefType.clear();
4292 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004293 std::string ForwardingCastType("(");
4294 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004295 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004296 ByrefType += " " + Name + " = {(void*)";
4297 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004298 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004299 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004300 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004301 ByrefType += "sizeof(";
4302 RewriteByRefString(ByrefType, Name, ND);
4303 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004304 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004305 ByrefType += ", __Block_byref_id_object_copy_";
4306 ByrefType += utostr(flag);
4307 ByrefType += ", __Block_byref_id_object_dispose_";
4308 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004309 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004310 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004311 unsigned nameSize = Name.size();
4312 // for block or function pointer declaration. Name is aleady
4313 // part of the declaration.
4314 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4315 nameSize = 1;
4316 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004317 }
4318 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004319 SourceLocation startLoc;
4320 Expr *E = ND->getInit();
4321 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4322 startLoc = ECE->getLParenLoc();
4323 else
4324 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004325 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004326 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004327 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004328 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004329 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004330 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004331 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004332 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004333 ByrefType += "sizeof(";
4334 RewriteByRefString(ByrefType, Name, ND);
4335 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004336 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004337 ByrefType += "__Block_byref_id_object_copy_";
4338 ByrefType += utostr(flag);
4339 ByrefType += ", __Block_byref_id_object_dispose_";
4340 ByrefType += utostr(flag);
4341 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004342 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004343 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004344
4345 // Complete the newly synthesized compound expression by inserting a right
4346 // curly brace before the end of the declaration.
4347 // FIXME: This approach avoids rewriting the initializer expression. It
4348 // also assumes there is only one declarator. For example, the following
4349 // isn't currently supported by this routine (in general):
4350 //
4351 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4352 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004353 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4354 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004355 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4356 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004357 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004358
Benjamin Kramerd999b372010-02-14 14:14:16 +00004359 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004360 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004361 return;
4362}
4363
Mike Stump1eb44332009-09-09 15:08:12 +00004364void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004365 // Add initializers for any closure decl refs.
4366 GetBlockDeclRefExprs(Exp->getBody());
4367 if (BlockDeclRefs.size()) {
4368 // Unique all "by copy" declarations.
4369 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004370 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004371 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4372 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4373 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4374 }
4375 }
Steve Naroff54055232008-10-27 17:20:55 +00004376 // Unique all "by ref" declarations.
4377 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004378 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004379 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4380 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4381 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4382 }
Steve Naroff54055232008-10-27 17:20:55 +00004383 }
4384 // Find any imported blocks...they will need special attention.
4385 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004386 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004387 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004388 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004389 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004390 }
4391}
4392
Chris Lattner5f9e2722011-07-23 10:55:15 +00004393FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004394 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004395 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004396 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4397 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004398 false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004399}
4400
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004401Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00004402 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004403 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004404 Blocks.push_back(Exp);
4405
4406 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004407
4408 // Add inner imported variables now used in current block.
4409 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004410 if (!InnerBlockDeclRefs.empty()) {
4411 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004412 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004413 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004414 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004415 // We need to save the copied-in variables in nested
4416 // blocks because it is needed at the end for some of the API generations.
4417 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004418 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4419 BlockDeclRefs.push_back(Exp);
4420 BlockByCopyDeclsPtrSet.insert(VD);
4421 BlockByCopyDecls.push_back(VD);
4422 }
John McCallf4b88a42012-03-10 09:33:50 +00004423 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004424 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4425 BlockDeclRefs.push_back(Exp);
4426 BlockByRefDeclsPtrSet.insert(VD);
4427 BlockByRefDecls.push_back(VD);
4428 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004429 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004430 // Find any imported blocks...they will need special attention.
4431 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004432 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004433 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4434 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4435 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004436 }
4437 InnerDeclRefsCount.push_back(countOfInnerDecls);
4438
Steve Narofffa15fd92008-10-28 20:29:00 +00004439 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Steve Narofffa15fd92008-10-28 20:29:00 +00004441 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004442 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004443 else if (CurMethodDef)
4444 BuildUniqueMethodName(FuncName, CurMethodDef);
4445 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004446 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004447
Steve Narofffa15fd92008-10-28 20:29:00 +00004448 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Steve Narofffa15fd92008-10-28 20:29:00 +00004450 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4451 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Steve Narofffa15fd92008-10-28 20:29:00 +00004453 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004454 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4455 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004456
4457 FunctionDecl *FD;
4458 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004459
Benjamin Kramere5753592013-09-09 14:48:42 +00004460 // Simulate a constructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004461 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004462 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004463 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004464
Chris Lattner5f9e2722011-07-23 10:55:15 +00004465 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Steve Narofffdc03722008-10-29 21:23:59 +00004467 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004468 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004469 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4470 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004471 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004472 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004473 InitExprs.push_back(castExpr);
4474
Steve Naroff01aec112009-12-06 21:14:13 +00004475 // Initialize the block descriptor.
4476 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004478 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4479 SourceLocation(), SourceLocation(),
4480 &Context->Idents.get(DescData.c_str()),
4481 Context->VoidPtrTy, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004482 SC_Static);
John McCallf89e55a2010-11-18 06:31:45 +00004483 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004484 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004485 Context->VoidPtrTy,
4486 VK_LValue,
4487 SourceLocation()),
4488 UO_AddrOf,
4489 Context->getPointerType(Context->VoidPtrTy),
4490 VK_RValue, OK_Ordinary,
4491 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004492 InitExprs.push_back(DescRefExpr);
4493
Steve Narofffa15fd92008-10-28 20:29:00 +00004494 // Add initializers for any closure decl refs.
4495 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004496 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004498 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004500 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004501 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004502 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004503 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004504 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004505 if (HasLocalVariableExternalStorage(*I)) {
4506 QualType QT = (*I)->getType();
4507 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004508 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4509 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004510 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004511 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004512 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004513 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004514 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004515 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004516 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004517 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004518 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004519 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004520 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004521 if (HasLocalVariableExternalStorage(*I)) {
4522 QualType QT = (*I)->getType();
4523 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004524 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4525 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004526 }
4527
Steve Narofffa15fd92008-10-28 20:29:00 +00004528 }
Mike Stump1eb44332009-09-09 15:08:12 +00004529 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004530 }
4531 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004532 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004533 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004534 ValueDecl *ND = (*I);
4535 std::string Name(ND->getNameAsString());
4536 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004537 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004538 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4539 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004540 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004541 SourceLocation(), SourceLocation(),
4542 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004543 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4544 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4545
Daniel Dunbar4087f272010-08-17 22:39:59 +00004546 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004547 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004548 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004549 bool isNestedCapturedVar = false;
4550 if (block)
Stephen Hines651f13c2014-04-23 16:59:28 -07004551 for (const auto &CI : block->captures()) {
4552 const VarDecl *variable = CI.getVariable();
4553 if (variable == ND && CI.isNested()) {
4554 assert (CI.isByRef() &&
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004555 "SynthBlockInitExpr - captured block variable is not byref");
4556 isNestedCapturedVar = true;
4557 break;
4558 }
4559 }
4560 // captured nested byref variable has its address passed. Do not take
4561 // its address again.
4562 if (!isNestedCapturedVar)
4563 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004564 Context->getPointerType(Exp->getType()),
4565 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004566 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004567 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004568 }
4569 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004570 if (ImportedBlockDecls.size()) {
4571 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4572 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004573 unsigned IntSize =
4574 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004575 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4576 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004577 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004578 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004579 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00004580 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004581 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004582 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004583 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004584 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004585 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004586 BlockDeclRefs.clear();
4587 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004588 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004589 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004590 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004591 ImportedBlockDecls.clear();
4592 return NewRep;
4593}
4594
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004595bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4596 if (const ObjCForCollectionStmt * CS =
4597 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4598 return CS->getElement() == DS;
4599 return false;
4600}
4601
Steve Narofffa15fd92008-10-28 20:29:00 +00004602//===----------------------------------------------------------------------===//
4603// Function Body / Expression rewriting
4604//===----------------------------------------------------------------------===//
4605
4606Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004607 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004608 isa<DoStmt>(S) || isa<ForStmt>(S))
4609 Stmts.push_back(S);
4610 else if (isa<ObjCForCollectionStmt>(S)) {
4611 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004612 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004613 }
Mike Stump1eb44332009-09-09 15:08:12 +00004614
John McCall4b9c2d22011-11-06 09:01:30 +00004615 // Pseudo-object operations and ivar references need special
4616 // treatment because we're going to recursively rewrite them.
4617 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4618 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4619 return RewritePropertyOrImplicitSetter(PseudoOp);
4620 } else {
4621 return RewritePropertyOrImplicitGetter(PseudoOp);
4622 }
4623 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4624 return RewriteObjCIvarRefExpr(IvarRefExpr);
4625 }
4626
Steve Narofffa15fd92008-10-28 20:29:00 +00004627 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004628
Steve Narofffa15fd92008-10-28 20:29:00 +00004629 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004630 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004631 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004632 Stmt *childStmt = (*CI);
4633 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004634 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004635 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004636 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004637 }
Mike Stump1eb44332009-09-09 15:08:12 +00004638
Steve Narofffa15fd92008-10-28 20:29:00 +00004639 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004640 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004641 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4642 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004643 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004644 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004645 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004646 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004647 Stmt *SaveCurrentBody = CurrentBody;
4648 CurrentBody = BE->getBody();
4649 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004650 // block literal on rhs of a property-dot-sytax assignment
4651 // must be replaced by its synthesize ast so getRewrittenText
4652 // works as expected. In this case, what actually ends up on RHS
4653 // is the blockTranscribed which is the helper function for the
4654 // block literal; as in: self.c = ^() {[ace ARR];};
4655 bool saveDisableReplaceStmt = DisableReplaceStmt;
4656 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004657 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004658 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004659 CurrentBody = SaveCurrentBody;
4660 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004661 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004662 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004663 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004664 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004666 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4667
Steve Narofffa15fd92008-10-28 20:29:00 +00004668 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004669 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004670 return blockTranscribed;
4671 }
4672 // Handle specific things.
4673 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4674 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Steve Narofffa15fd92008-10-28 20:29:00 +00004676 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4677 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Steve Narofffa15fd92008-10-28 20:29:00 +00004679 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4680 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Steve Narofffa15fd92008-10-28 20:29:00 +00004682 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004683#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 // Before we rewrite it, put the original message expression in a comment.
4685 SourceLocation startLoc = MessExpr->getLocStart();
4686 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Steve Narofffa15fd92008-10-28 20:29:00 +00004688 const char *startBuf = SM->getCharacterData(startLoc);
4689 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 std::string messString;
4692 messString += "// ";
4693 messString.append(startBuf, endBuf-startBuf+1);
4694 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004695
4696 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004697 // InsertText(clang::SourceLocation, char const*, unsigned int).
4698 // InsertText(startLoc, messString.c_str(), messString.size());
4699 // Tried this, but it didn't work either...
4700 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004701#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004702 return RewriteMessageExpr(MessExpr);
4703 }
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Steve Narofffa15fd92008-10-28 20:29:00 +00004705 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4706 return RewriteObjCTryStmt(StmtTry);
4707
4708 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4709 return RewriteObjCSynchronizedStmt(StmtTry);
4710
4711 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4712 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Steve Narofffa15fd92008-10-28 20:29:00 +00004714 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4715 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004716
4717 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004718 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004719 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004720 OrigStmtRange.getEnd());
4721 if (BreakStmt *StmtBreakStmt =
4722 dyn_cast<BreakStmt>(S))
4723 return RewriteBreakStmt(StmtBreakStmt);
4724 if (ContinueStmt *StmtContinueStmt =
4725 dyn_cast<ContinueStmt>(S))
4726 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004727
4728 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 // and cast exprs.
4730 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4731 // FIXME: What we're doing here is modifying the type-specifier that
4732 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004733 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004734 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4735 // the context of an ObjCForCollectionStmt. For example:
4736 // NSArray *someArray;
4737 // for (id <FooProtocol> index in someArray) ;
4738 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4739 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004740 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004741 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Steve Narofffa15fd92008-10-28 20:29:00 +00004743 // Blocks rewrite rules.
Stephen Hines651f13c2014-04-23 16:59:28 -07004744 for (auto *SD : DS->decls()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004746 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004748 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004749 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004750 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004751 if (VD->hasAttr<BlocksAttr>()) {
4752 static unsigned uniqueByrefDeclCount = 0;
4753 assert(!BlockByRefDeclNo.count(ND) &&
4754 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4755 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004756 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004757 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004758 else
4759 RewriteTypeOfDecl(VD);
4760 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004761 }
Richard Smith162e1c12011-04-15 14:24:37 +00004762 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004763 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004764 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004765 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4767 }
4768 }
4769 }
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4772 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004773
4774 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004775 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4776 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004777 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4778 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 && "Statement stack mismatch");
4780 Stmts.pop_back();
4781 }
4782 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4784 ValueDecl *VD = DRE->getDecl();
4785 if (VD->hasAttr<BlocksAttr>())
4786 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004787 if (HasLocalVariableExternalStorage(VD))
4788 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004789 }
4790
Steve Narofffa15fd92008-10-28 20:29:00 +00004791 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004792 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004793 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004794 ReplaceStmt(S, BlockCall);
4795 return BlockCall;
4796 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004797 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004798 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004799 RewriteCastExpr(CE);
4800 }
4801#if 0
4802 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004803 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4804 ICE->getSubExpr(),
4805 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004806 // Get the new text.
4807 std::string SStr;
4808 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004809 Replacement->printPretty(Buf);
Steve Narofffa15fd92008-10-28 20:29:00 +00004810 const std::string &Str = Buf.str();
4811
4812 printf("CAST = %s\n", &Str[0]);
4813 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4814 delete S;
4815 return Replacement;
4816 }
4817#endif
4818 // Return this stmt unmodified.
4819 return S;
4820}
4821
Steve Naroff3d7e7862009-12-05 15:55:59 +00004822void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004823 for (auto *FD : RD->fields()) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00004824 if (isTopLevelBlockPointerType(FD->getType()))
4825 RewriteBlockPointerDecl(FD);
4826 if (FD->getType()->isObjCQualifiedIdType() ||
4827 FD->getType()->isObjCQualifiedInterfaceType())
4828 RewriteObjCQualifiedInterfaceTypes(FD);
4829 }
4830}
4831
Steve Narofffa15fd92008-10-28 20:29:00 +00004832/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4833/// main file of the input.
4834void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004835 switch (D->getKind()) {
4836 case Decl::Function: {
4837 FunctionDecl *FD = cast<FunctionDecl>(D);
4838 if (FD->isOverloadedOperator())
4839 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004840
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004841 // Since function prototypes don't have ParmDecl's, we check the function
4842 // prototype. This enables us to rewrite function declarations and
4843 // definitions using the same code.
4844 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004845
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004846 if (!FD->isThisDeclarationADefinition())
4847 break;
4848
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004849 // FIXME: If this should support Obj-C++, support CXXTryStmt
4850 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4851 CurFunctionDef = FD;
4852 CurFunctionDeclToDeclareForBlock = FD;
4853 CurrentBody = Body;
4854 Body =
4855 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4856 FD->setBody(Body);
4857 CurrentBody = 0;
4858 if (PropParentMap) {
4859 delete PropParentMap;
4860 PropParentMap = 0;
4861 }
4862 // This synthesizes and inserts the block "impl" struct, invoke function,
4863 // and any copy/dispose helper functions.
4864 InsertBlockLiteralsWithinFunction(FD);
4865 CurFunctionDef = 0;
4866 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004867 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004868 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004869 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004870 case Decl::ObjCMethod: {
4871 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4872 if (CompoundStmt *Body = MD->getCompoundBody()) {
4873 CurMethodDef = MD;
4874 CurrentBody = Body;
4875 Body =
4876 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4877 MD->setBody(Body);
4878 CurrentBody = 0;
4879 if (PropParentMap) {
4880 delete PropParentMap;
4881 PropParentMap = 0;
4882 }
4883 InsertBlockLiteralsWithinMethod(MD);
4884 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004885 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004886 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004887 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004888 case Decl::ObjCImplementation: {
4889 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4890 ClassImplementation.push_back(CI);
4891 break;
4892 }
4893 case Decl::ObjCCategoryImpl: {
4894 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4895 CategoryImplementation.push_back(CI);
4896 break;
4897 }
4898 case Decl::Var: {
4899 VarDecl *VD = cast<VarDecl>(D);
4900 RewriteObjCQualifiedInterfaceTypes(VD);
4901 if (isTopLevelBlockPointerType(VD->getType()))
4902 RewriteBlockPointerDecl(VD);
4903 else if (VD->getType()->isFunctionPointerType()) {
4904 CheckFunctionPointerDecl(VD->getType(), VD);
4905 if (VD->getInit()) {
4906 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4907 RewriteCastExpr(CE);
4908 }
4909 }
4910 } else if (VD->getType()->isRecordType()) {
4911 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4912 if (RD->isCompleteDefinition())
4913 RewriteRecordBody(RD);
4914 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004915 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004916 GlobalVarDecl = VD;
4917 CurrentBody = VD->getInit();
4918 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4919 CurrentBody = 0;
4920 if (PropParentMap) {
4921 delete PropParentMap;
4922 PropParentMap = 0;
4923 }
4924 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4925 GlobalVarDecl = 0;
4926
4927 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004928 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004929 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004930 }
4931 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004932 break;
4933 }
4934 case Decl::TypeAlias:
4935 case Decl::Typedef: {
4936 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4937 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4938 RewriteBlockPointerDecl(TD);
4939 else if (TD->getUnderlyingType()->isFunctionPointerType())
4940 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4941 }
4942 break;
4943 }
4944 case Decl::CXXRecord:
4945 case Decl::Record: {
4946 RecordDecl *RD = cast<RecordDecl>(D);
4947 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004948 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004949 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004950 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004951 default:
4952 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004953 }
4954 // Nothing yet.
4955}
4956
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004957void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004958 if (Diags.hasErrorOccurred())
4959 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004960
Steve Narofffa15fd92008-10-28 20:29:00 +00004961 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Steve Naroff621edce2009-04-29 16:37:50 +00004963 // Here's a great place to add any extra declarations that may be needed.
4964 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00004965 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004966 E = ProtocolExprDecls.end(); I != E; ++I)
4967 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4968
Benjamin Kramerd999b372010-02-14 14:14:16 +00004969 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004970 if (ClassImplementation.size() || CategoryImplementation.size())
4971 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004972
Steve Narofffa15fd92008-10-28 20:29:00 +00004973 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4974 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00004975 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00004976 Rewrite.getRewriteBufferFor(MainFileID)) {
4977 //printf("Changed:\n");
4978 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4979 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00004980 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00004981 }
Steve Narofface66252008-11-13 20:07:04 +00004982
Steve Naroff621edce2009-04-29 16:37:50 +00004983 if (ClassImplementation.size() || CategoryImplementation.size() ||
4984 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004985 // Rewrite Objective-c meta data*
4986 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00004987 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00004988 // Emit metadata.
4989 *OutFile << ResultStr;
4990 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004991 OutFile->flush();
4992}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00004993
4994void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4995 InitializeCommon(context);
4996
4997 // declaring objc_selector outside the parameter list removes a silly
4998 // scope related warning...
4999 if (IsHeader)
5000 Preamble = "#pragma once\n";
5001 Preamble += "struct objc_selector; struct objc_class;\n";
5002 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5003 Preamble += "struct objc_object *superClass; ";
5004 if (LangOpts.MicrosoftExt) {
5005 // Add a constructor for creating temporary objects.
5006 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5007 ": ";
5008 Preamble += "object(o), superClass(s) {} ";
5009 }
5010 Preamble += "};\n";
5011 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5012 Preamble += "typedef struct objc_object Protocol;\n";
5013 Preamble += "#define _REWRITER_typedef_Protocol\n";
5014 Preamble += "#endif\n";
5015 if (LangOpts.MicrosoftExt) {
5016 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5017 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5018 } else
5019 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5020 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5021 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5022 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5023 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5024 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5025 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5026 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5027 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5028 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5029 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5030 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5031 Preamble += "(const char *);\n";
5032 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5033 Preamble += "(struct objc_class *);\n";
5034 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5035 Preamble += "(const char *);\n";
5036 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5037 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5039 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5040 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5041 Preamble += "(struct objc_class *, struct objc_object *);\n";
5042 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005043 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5044 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005045 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5046 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5047 Preamble += "struct __objcFastEnumerationState {\n\t";
5048 Preamble += "unsigned long state;\n\t";
5049 Preamble += "void **itemsPtr;\n\t";
5050 Preamble += "unsigned long *mutationsPtr;\n\t";
5051 Preamble += "unsigned long extra[5];\n};\n";
5052 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5053 Preamble += "#define __FASTENUMERATIONSTATE\n";
5054 Preamble += "#endif\n";
5055 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5056 Preamble += "struct __NSConstantStringImpl {\n";
5057 Preamble += " int *isa;\n";
5058 Preamble += " int flags;\n";
5059 Preamble += " char *str;\n";
5060 Preamble += " long length;\n";
5061 Preamble += "};\n";
5062 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5063 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5064 Preamble += "#else\n";
5065 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5066 Preamble += "#endif\n";
5067 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5068 Preamble += "#endif\n";
5069 // Blocks preamble.
5070 Preamble += "#ifndef BLOCK_IMPL\n";
5071 Preamble += "#define BLOCK_IMPL\n";
5072 Preamble += "struct __block_impl {\n";
5073 Preamble += " void *isa;\n";
5074 Preamble += " int Flags;\n";
5075 Preamble += " int Reserved;\n";
5076 Preamble += " void *FuncPtr;\n";
5077 Preamble += "};\n";
5078 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5079 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5080 Preamble += "extern \"C\" __declspec(dllexport) "
5081 "void _Block_object_assign(void *, const void *, const int);\n";
5082 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5083 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5084 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5085 Preamble += "#else\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5090 Preamble += "#endif\n";
5091 Preamble += "#endif\n";
5092 if (LangOpts.MicrosoftExt) {
5093 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5094 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5095 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5096 Preamble += "#define __attribute__(X)\n";
5097 Preamble += "#endif\n";
5098 Preamble += "#define __weak\n";
5099 }
5100 else {
5101 Preamble += "#define __block\n";
5102 Preamble += "#define __weak\n";
5103 }
5104 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5105 // as this avoids warning in any 64bit/32bit compilation model.
5106 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5107}
5108
5109/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5110/// ivar offset.
5111void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5112 std::string &Result) {
5113 if (ivar->isBitField()) {
5114 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5115 // place all bitfields at offset 0.
5116 Result += "0";
5117 } else {
5118 Result += "__OFFSETOFIVAR__(struct ";
5119 Result += ivar->getContainingInterface()->getNameAsString();
5120 if (LangOpts.MicrosoftExt)
5121 Result += "_IMPL";
5122 Result += ", ";
5123 Result += ivar->getNameAsString();
5124 Result += ")";
5125 }
5126}
5127
5128/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5129void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5130 ObjCProtocolDecl *PDecl, StringRef prefix,
5131 StringRef ClassName, std::string &Result) {
5132 static bool objc_protocol_methods = false;
5133
5134 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005135 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005136 /* struct protocol_methods {
5137 SEL _cmd;
5138 char *method_types;
5139 }
5140 */
5141 Result += "\nstruct _protocol_methods {\n";
5142 Result += "\tstruct objc_selector *_cmd;\n";
5143 Result += "\tchar *method_types;\n";
5144 Result += "};\n";
5145
5146 objc_protocol_methods = true;
5147 }
5148 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005149 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005150 return;
5151
Douglas Gregor61cc2962012-01-02 02:00:30 +00005152 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5153 PDecl = Def;
5154
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005155 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5156 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5157 PDecl->instmeth_end());
5158 /* struct _objc_protocol_method_list {
5159 int protocol_method_count;
5160 struct protocol_methods protocols[];
5161 }
5162 */
5163 Result += "\nstatic struct {\n";
5164 Result += "\tint protocol_method_count;\n";
5165 Result += "\tstruct _protocol_methods protocol_methods[";
5166 Result += utostr(NumMethods);
5167 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5168 Result += PDecl->getNameAsString();
5169 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5170 "{\n\t" + utostr(NumMethods) + "\n";
5171
5172 // Output instance methods declared in this protocol.
5173 for (ObjCProtocolDecl::instmeth_iterator
5174 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5175 I != E; ++I) {
5176 if (I == PDecl->instmeth_begin())
5177 Result += "\t ,{{(struct objc_selector *)\"";
5178 else
5179 Result += "\t ,{(struct objc_selector *)\"";
5180 Result += (*I)->getSelector().getAsString();
5181 std::string MethodTypeString;
5182 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5183 Result += "\", \"";
5184 Result += MethodTypeString;
5185 Result += "\"}\n";
5186 }
5187 Result += "\t }\n};\n";
5188 }
5189
5190 // Output class methods declared in this protocol.
5191 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5192 PDecl->classmeth_end());
5193 if (NumMethods > 0) {
5194 /* struct _objc_protocol_method_list {
5195 int protocol_method_count;
5196 struct protocol_methods protocols[];
5197 }
5198 */
5199 Result += "\nstatic struct {\n";
5200 Result += "\tint protocol_method_count;\n";
5201 Result += "\tstruct _protocol_methods protocol_methods[";
5202 Result += utostr(NumMethods);
5203 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5204 Result += PDecl->getNameAsString();
5205 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5206 "{\n\t";
5207 Result += utostr(NumMethods);
5208 Result += "\n";
5209
5210 // Output instance methods declared in this protocol.
5211 for (ObjCProtocolDecl::classmeth_iterator
5212 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5213 I != E; ++I) {
5214 if (I == PDecl->classmeth_begin())
5215 Result += "\t ,{{(struct objc_selector *)\"";
5216 else
5217 Result += "\t ,{(struct objc_selector *)\"";
5218 Result += (*I)->getSelector().getAsString();
5219 std::string MethodTypeString;
5220 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5221 Result += "\", \"";
5222 Result += MethodTypeString;
5223 Result += "\"}\n";
5224 }
5225 Result += "\t }\n};\n";
5226 }
5227
5228 // Output:
5229 /* struct _objc_protocol {
5230 // Objective-C 1.0 extensions
5231 struct _objc_protocol_extension *isa;
5232 char *protocol_name;
5233 struct _objc_protocol **protocol_list;
5234 struct _objc_protocol_method_list *instance_methods;
5235 struct _objc_protocol_method_list *class_methods;
5236 };
5237 */
5238 static bool objc_protocol = false;
5239 if (!objc_protocol) {
5240 Result += "\nstruct _objc_protocol {\n";
5241 Result += "\tstruct _objc_protocol_extension *isa;\n";
5242 Result += "\tchar *protocol_name;\n";
5243 Result += "\tstruct _objc_protocol **protocol_list;\n";
5244 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5245 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5246 Result += "};\n";
5247
5248 objc_protocol = true;
5249 }
5250
5251 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5252 Result += PDecl->getNameAsString();
5253 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5254 "{\n\t0, \"";
5255 Result += PDecl->getNameAsString();
5256 Result += "\", 0, ";
5257 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5258 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5259 Result += PDecl->getNameAsString();
5260 Result += ", ";
5261 }
5262 else
5263 Result += "0, ";
5264 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5265 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5266 Result += PDecl->getNameAsString();
5267 Result += "\n";
5268 }
5269 else
5270 Result += "0\n";
5271 Result += "};\n";
5272
5273 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005274 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005275 llvm_unreachable("protocol already synthesized");
5276
5277}
5278
5279void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5280 const ObjCList<ObjCProtocolDecl> &Protocols,
5281 StringRef prefix, StringRef ClassName,
5282 std::string &Result) {
5283 if (Protocols.empty()) return;
5284
5285 for (unsigned i = 0; i != Protocols.size(); i++)
5286 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5287
5288 // Output the top lovel protocol meta-data for the class.
5289 /* struct _objc_protocol_list {
5290 struct _objc_protocol_list *next;
5291 int protocol_count;
5292 struct _objc_protocol *class_protocols[];
5293 }
5294 */
5295 Result += "\nstatic struct {\n";
5296 Result += "\tstruct _objc_protocol_list *next;\n";
5297 Result += "\tint protocol_count;\n";
5298 Result += "\tstruct _objc_protocol *class_protocols[";
5299 Result += utostr(Protocols.size());
5300 Result += "];\n} _OBJC_";
5301 Result += prefix;
5302 Result += "_PROTOCOLS_";
5303 Result += ClassName;
5304 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5305 "{\n\t0, ";
5306 Result += utostr(Protocols.size());
5307 Result += "\n";
5308
5309 Result += "\t,{&_OBJC_PROTOCOL_";
5310 Result += Protocols[0]->getNameAsString();
5311 Result += " \n";
5312
5313 for (unsigned i = 1; i != Protocols.size(); i++) {
5314 Result += "\t ,&_OBJC_PROTOCOL_";
5315 Result += Protocols[i]->getNameAsString();
5316 Result += "\n";
5317 }
5318 Result += "\t }\n};\n";
5319}
5320
5321void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5322 std::string &Result) {
5323 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5324
5325 // Explicitly declared @interface's are already synthesized.
5326 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005327 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005328 // produce correct synthesis as yet.
5329 RewriteObjCInternalStruct(CDecl, Result);
5330 }
5331
5332 // Build _objc_ivar_list metadata for classes ivars if needed
5333 unsigned NumIvars = !IDecl->ivar_empty()
5334 ? IDecl->ivar_size()
5335 : (CDecl ? CDecl->ivar_size() : 0);
5336 if (NumIvars > 0) {
5337 static bool objc_ivar = false;
5338 if (!objc_ivar) {
5339 /* struct _objc_ivar {
5340 char *ivar_name;
5341 char *ivar_type;
5342 int ivar_offset;
5343 };
5344 */
5345 Result += "\nstruct _objc_ivar {\n";
5346 Result += "\tchar *ivar_name;\n";
5347 Result += "\tchar *ivar_type;\n";
5348 Result += "\tint ivar_offset;\n";
5349 Result += "};\n";
5350
5351 objc_ivar = true;
5352 }
5353
5354 /* struct {
5355 int ivar_count;
5356 struct _objc_ivar ivar_list[nIvars];
5357 };
5358 */
5359 Result += "\nstatic struct {\n";
5360 Result += "\tint ivar_count;\n";
5361 Result += "\tstruct _objc_ivar ivar_list[";
5362 Result += utostr(NumIvars);
5363 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5364 Result += IDecl->getNameAsString();
5365 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5366 "{\n\t";
5367 Result += utostr(NumIvars);
5368 Result += "\n";
5369
5370 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5371 SmallVector<ObjCIvarDecl *, 8> IVars;
5372 if (!IDecl->ivar_empty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005373 for (auto *IV : IDecl->ivars())
5374 IVars.push_back(IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005375 IVI = IDecl->ivar_begin();
5376 IVE = IDecl->ivar_end();
5377 } else {
5378 IVI = CDecl->ivar_begin();
5379 IVE = CDecl->ivar_end();
5380 }
5381 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005382 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005383 Result += "\", \"";
5384 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005385 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005386 QuoteDoublequotes(TmpString, StrEncoding);
5387 Result += StrEncoding;
5388 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005389 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005390 Result += "}\n";
5391 for (++IVI; IVI != IVE; ++IVI) {
5392 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005393 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005394 Result += "\", \"";
5395 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005396 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005397 QuoteDoublequotes(TmpString, StrEncoding);
5398 Result += StrEncoding;
5399 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005400 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005401 Result += "}\n";
5402 }
5403
5404 Result += "\t }\n};\n";
5405 }
5406
5407 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005408 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005409
5410 // If any of our property implementations have associated getters or
5411 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005412 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005413 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005414 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005415 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005416 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005417 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005418 if (!PD)
5419 continue;
5420 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5421 if (!Getter->isDefined())
5422 InstanceMethods.push_back(Getter);
5423 if (PD->isReadOnly())
5424 continue;
5425 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5426 if (!Setter->isDefined())
5427 InstanceMethods.push_back(Setter);
5428 }
5429 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5430 true, "", IDecl->getName(), Result);
5431
5432 // Build _objc_method_list for class's class methods if needed
5433 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5434 false, "", IDecl->getName(), Result);
5435
5436 // Protocols referenced in class declaration?
5437 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5438 "CLASS", CDecl->getName(), Result);
5439
5440 // Declaration of class/meta-class metadata
5441 /* struct _objc_class {
5442 struct _objc_class *isa; // or const char *root_class_name when metadata
5443 const char *super_class_name;
5444 char *name;
5445 long version;
5446 long info;
5447 long instance_size;
5448 struct _objc_ivar_list *ivars;
5449 struct _objc_method_list *methods;
5450 struct objc_cache *cache;
5451 struct objc_protocol_list *protocols;
5452 const char *ivar_layout;
5453 struct _objc_class_ext *ext;
5454 };
5455 */
5456 static bool objc_class = false;
5457 if (!objc_class) {
5458 Result += "\nstruct _objc_class {\n";
5459 Result += "\tstruct _objc_class *isa;\n";
5460 Result += "\tconst char *super_class_name;\n";
5461 Result += "\tchar *name;\n";
5462 Result += "\tlong version;\n";
5463 Result += "\tlong info;\n";
5464 Result += "\tlong instance_size;\n";
5465 Result += "\tstruct _objc_ivar_list *ivars;\n";
5466 Result += "\tstruct _objc_method_list *methods;\n";
5467 Result += "\tstruct objc_cache *cache;\n";
5468 Result += "\tstruct _objc_protocol_list *protocols;\n";
5469 Result += "\tconst char *ivar_layout;\n";
5470 Result += "\tstruct _objc_class_ext *ext;\n";
5471 Result += "};\n";
5472 objc_class = true;
5473 }
5474
5475 // Meta-class metadata generation.
5476 ObjCInterfaceDecl *RootClass = 0;
5477 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5478 while (SuperClass) {
5479 RootClass = SuperClass;
5480 SuperClass = SuperClass->getSuperClass();
5481 }
5482 SuperClass = CDecl->getSuperClass();
5483
5484 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5485 Result += CDecl->getNameAsString();
5486 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5487 "{\n\t(struct _objc_class *)\"";
5488 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5489 Result += "\"";
5490
5491 if (SuperClass) {
5492 Result += ", \"";
5493 Result += SuperClass->getNameAsString();
5494 Result += "\", \"";
5495 Result += CDecl->getNameAsString();
5496 Result += "\"";
5497 }
5498 else {
5499 Result += ", 0, \"";
5500 Result += CDecl->getNameAsString();
5501 Result += "\"";
5502 }
5503 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5504 // 'info' field is initialized to CLS_META(2) for metaclass
5505 Result += ", 0,2, sizeof(struct _objc_class), 0";
5506 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5507 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5508 Result += IDecl->getNameAsString();
5509 Result += "\n";
5510 }
5511 else
5512 Result += ", 0\n";
5513 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5514 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5515 Result += CDecl->getNameAsString();
5516 Result += ",0,0\n";
5517 }
5518 else
5519 Result += "\t,0,0,0,0\n";
5520 Result += "};\n";
5521
5522 // class metadata generation.
5523 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5524 Result += CDecl->getNameAsString();
5525 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5526 "{\n\t&_OBJC_METACLASS_";
5527 Result += CDecl->getNameAsString();
5528 if (SuperClass) {
5529 Result += ", \"";
5530 Result += SuperClass->getNameAsString();
5531 Result += "\", \"";
5532 Result += CDecl->getNameAsString();
5533 Result += "\"";
5534 }
5535 else {
5536 Result += ", 0, \"";
5537 Result += CDecl->getNameAsString();
5538 Result += "\"";
5539 }
5540 // 'info' field is initialized to CLS_CLASS(1) for class
5541 Result += ", 0,1";
5542 if (!ObjCSynthesizedStructs.count(CDecl))
5543 Result += ",0";
5544 else {
5545 // class has size. Must synthesize its size.
5546 Result += ",sizeof(struct ";
5547 Result += CDecl->getNameAsString();
5548 if (LangOpts.MicrosoftExt)
5549 Result += "_IMPL";
5550 Result += ")";
5551 }
5552 if (NumIvars > 0) {
5553 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5554 Result += CDecl->getNameAsString();
5555 Result += "\n\t";
5556 }
5557 else
5558 Result += ",0";
5559 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5560 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5561 Result += CDecl->getNameAsString();
5562 Result += ", 0\n\t";
5563 }
5564 else
5565 Result += ",0,0";
5566 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5567 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5568 Result += CDecl->getNameAsString();
5569 Result += ", 0,0\n";
5570 }
5571 else
5572 Result += ",0,0,0\n";
5573 Result += "};\n";
5574}
5575
5576void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5577 int ClsDefCount = ClassImplementation.size();
5578 int CatDefCount = CategoryImplementation.size();
5579
5580 // For each implemented class, write out all its meta data.
5581 for (int i = 0; i < ClsDefCount; i++)
5582 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5583
5584 // For each implemented category, write out all its meta data.
5585 for (int i = 0; i < CatDefCount; i++)
5586 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5587
5588 // Write objc_symtab metadata
5589 /*
5590 struct _objc_symtab
5591 {
5592 long sel_ref_cnt;
5593 SEL *refs;
5594 short cls_def_cnt;
5595 short cat_def_cnt;
5596 void *defs[cls_def_cnt + cat_def_cnt];
5597 };
5598 */
5599
5600 Result += "\nstruct _objc_symtab {\n";
5601 Result += "\tlong sel_ref_cnt;\n";
5602 Result += "\tSEL *refs;\n";
5603 Result += "\tshort cls_def_cnt;\n";
5604 Result += "\tshort cat_def_cnt;\n";
5605 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5606 Result += "};\n\n";
5607
5608 Result += "static struct _objc_symtab "
5609 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5610 Result += "\t0, 0, " + utostr(ClsDefCount)
5611 + ", " + utostr(CatDefCount) + "\n";
5612 for (int i = 0; i < ClsDefCount; i++) {
5613 Result += "\t,&_OBJC_CLASS_";
5614 Result += ClassImplementation[i]->getNameAsString();
5615 Result += "\n";
5616 }
5617
5618 for (int i = 0; i < CatDefCount; i++) {
5619 Result += "\t,&_OBJC_CATEGORY_";
5620 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5621 Result += "_";
5622 Result += CategoryImplementation[i]->getNameAsString();
5623 Result += "\n";
5624 }
5625
5626 Result += "};\n\n";
5627
5628 // Write objc_module metadata
5629
5630 /*
5631 struct _objc_module {
5632 long version;
5633 long size;
5634 const char *name;
5635 struct _objc_symtab *symtab;
5636 }
5637 */
5638
5639 Result += "\nstruct _objc_module {\n";
5640 Result += "\tlong version;\n";
5641 Result += "\tlong size;\n";
5642 Result += "\tconst char *name;\n";
5643 Result += "\tstruct _objc_symtab *symtab;\n";
5644 Result += "};\n\n";
5645 Result += "static struct _objc_module "
5646 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5647 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5648 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5649 Result += "};\n\n";
5650
5651 if (LangOpts.MicrosoftExt) {
5652 if (ProtocolExprDecls.size()) {
5653 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5654 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5655 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5656 E = ProtocolExprDecls.end(); I != E; ++I) {
5657 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5658 Result += (*I)->getNameAsString();
5659 Result += " = &_OBJC_PROTOCOL_";
5660 Result += (*I)->getNameAsString();
5661 Result += ";\n";
5662 }
5663 Result += "#pragma data_seg(pop)\n\n";
5664 }
5665 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5666 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5667 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5668 Result += "&_OBJC_MODULES;\n";
5669 Result += "#pragma data_seg(pop)\n\n";
5670 }
5671}
5672
5673/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5674/// implementation.
5675void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5676 std::string &Result) {
5677 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5678 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00005679 ObjCCategoryDecl *CDecl
5680 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005681
5682 std::string FullCategoryName = ClassDecl->getNameAsString();
5683 FullCategoryName += '_';
5684 FullCategoryName += IDecl->getNameAsString();
5685
5686 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005687 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005688
5689 // If any of our property implementations have associated getters or
5690 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005691 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005692 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005693 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005694 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005695 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005696 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005697 if (!PD)
5698 continue;
5699 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5700 InstanceMethods.push_back(Getter);
5701 if (PD->isReadOnly())
5702 continue;
5703 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5704 InstanceMethods.push_back(Setter);
5705 }
5706 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5707 true, "CATEGORY_", FullCategoryName.c_str(),
5708 Result);
5709
5710 // Build _objc_method_list for class's class methods if needed
5711 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5712 false, "CATEGORY_", FullCategoryName.c_str(),
5713 Result);
5714
5715 // Protocols referenced in class declaration?
5716 // Null CDecl is case of a category implementation with no category interface
5717 if (CDecl)
5718 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5719 FullCategoryName, Result);
5720 /* struct _objc_category {
5721 char *category_name;
5722 char *class_name;
5723 struct _objc_method_list *instance_methods;
5724 struct _objc_method_list *class_methods;
5725 struct _objc_protocol_list *protocols;
5726 // Objective-C 1.0 extensions
5727 uint32_t size; // sizeof (struct _objc_category)
5728 struct _objc_property_list *instance_properties; // category's own
5729 // @property decl.
5730 };
5731 */
5732
5733 static bool objc_category = false;
5734 if (!objc_category) {
5735 Result += "\nstruct _objc_category {\n";
5736 Result += "\tchar *category_name;\n";
5737 Result += "\tchar *class_name;\n";
5738 Result += "\tstruct _objc_method_list *instance_methods;\n";
5739 Result += "\tstruct _objc_method_list *class_methods;\n";
5740 Result += "\tstruct _objc_protocol_list *protocols;\n";
5741 Result += "\tunsigned int size;\n";
5742 Result += "\tstruct _objc_property_list *instance_properties;\n";
5743 Result += "};\n";
5744 objc_category = true;
5745 }
5746 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5747 Result += FullCategoryName;
5748 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5749 Result += IDecl->getNameAsString();
5750 Result += "\"\n\t, \"";
5751 Result += ClassDecl->getNameAsString();
5752 Result += "\"\n";
5753
5754 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5755 Result += "\t, (struct _objc_method_list *)"
5756 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5757 Result += FullCategoryName;
5758 Result += "\n";
5759 }
5760 else
5761 Result += "\t, 0\n";
5762 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5763 Result += "\t, (struct _objc_method_list *)"
5764 "&_OBJC_CATEGORY_CLASS_METHODS_";
5765 Result += FullCategoryName;
5766 Result += "\n";
5767 }
5768 else
5769 Result += "\t, 0\n";
5770
5771 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5772 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5773 Result += FullCategoryName;
5774 Result += "\n";
5775 }
5776 else
5777 Result += "\t, 0\n";
5778 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5779}
5780
5781// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5782/// class methods.
5783template<typename MethodIterator>
5784void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5785 MethodIterator MethodEnd,
5786 bool IsInstanceMethod,
5787 StringRef prefix,
5788 StringRef ClassName,
5789 std::string &Result) {
5790 if (MethodBegin == MethodEnd) return;
5791
5792 if (!objc_impl_method) {
5793 /* struct _objc_method {
5794 SEL _cmd;
5795 char *method_types;
5796 void *_imp;
5797 }
5798 */
5799 Result += "\nstruct _objc_method {\n";
5800 Result += "\tSEL _cmd;\n";
5801 Result += "\tchar *method_types;\n";
5802 Result += "\tvoid *_imp;\n";
5803 Result += "};\n";
5804
5805 objc_impl_method = true;
5806 }
5807
5808 // Build _objc_method_list for class's methods if needed
5809
5810 /* struct {
5811 struct _objc_method_list *next_method;
5812 int method_count;
5813 struct _objc_method method_list[];
5814 }
5815 */
5816 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5817 Result += "\nstatic struct {\n";
5818 Result += "\tstruct _objc_method_list *next_method;\n";
5819 Result += "\tint method_count;\n";
5820 Result += "\tstruct _objc_method method_list[";
5821 Result += utostr(NumMethods);
5822 Result += "];\n} _OBJC_";
5823 Result += prefix;
5824 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5825 Result += "_METHODS_";
5826 Result += ClassName;
5827 Result += " __attribute__ ((used, section (\"__OBJC, __";
5828 Result += IsInstanceMethod ? "inst" : "cls";
5829 Result += "_meth\")))= ";
5830 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5831
5832 Result += "\t,{{(SEL)\"";
5833 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5834 std::string MethodTypeString;
5835 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5836 Result += "\", \"";
5837 Result += MethodTypeString;
5838 Result += "\", (void *)";
5839 Result += MethodInternalNames[*MethodBegin];
5840 Result += "}\n";
5841 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5842 Result += "\t ,{(SEL)\"";
5843 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5844 std::string MethodTypeString;
5845 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5846 Result += "\", \"";
5847 Result += MethodTypeString;
5848 Result += "\", (void *)";
5849 Result += MethodInternalNames[*MethodBegin];
5850 Result += "}\n";
5851 }
5852 Result += "\t }\n};\n";
5853}
5854
5855Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5856 SourceRange OldRange = IV->getSourceRange();
5857 Expr *BaseExpr = IV->getBase();
5858
5859 // Rewrite the base, but without actually doing replaces.
5860 {
5861 DisableReplaceStmtScope S(*this);
5862 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5863 IV->setBase(BaseExpr);
5864 }
5865
5866 ObjCIvarDecl *D = IV->getDecl();
5867
5868 Expr *Replacement = IV;
5869 if (CurMethodDef) {
5870 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5871 const ObjCInterfaceType *iFaceDecl =
5872 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5873 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5874 // lookup which class implements the instance variable.
5875 ObjCInterfaceDecl *clsDeclared = 0;
5876 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5877 clsDeclared);
5878 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5879
5880 // Synthesize an explicit cast to gain access to the ivar.
5881 std::string RecName = clsDeclared->getIdentifier()->getName();
5882 RecName += "_IMPL";
5883 IdentifierInfo *II = &Context->Idents.get(RecName);
5884 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5885 SourceLocation(), SourceLocation(),
5886 II);
5887 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5888 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5889 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5890 CK_BitCast,
5891 IV->getBase());
5892 // Don't forget the parens to enforce the proper binding.
5893 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5894 OldRange.getEnd(),
5895 castExpr);
5896 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005897 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005898 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5899 IV->getLocation(),
5900 D->getType(),
5901 VK_LValue, OK_Ordinary);
5902 Replacement = ME;
5903 } else {
5904 IV->setBase(PE);
5905 }
5906 }
5907 } else { // we are outside a method.
5908 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5909
5910 // Explicit ivar refs need to have a cast inserted.
5911 // FIXME: consider sharing some of this code with the code above.
5912 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5913 const ObjCInterfaceType *iFaceDecl =
5914 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5915 // lookup which class implements the instance variable.
5916 ObjCInterfaceDecl *clsDeclared = 0;
5917 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5918 clsDeclared);
5919 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5920
5921 // Synthesize an explicit cast to gain access to the ivar.
5922 std::string RecName = clsDeclared->getIdentifier()->getName();
5923 RecName += "_IMPL";
5924 IdentifierInfo *II = &Context->Idents.get(RecName);
5925 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5926 SourceLocation(), SourceLocation(),
5927 II);
5928 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5929 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5930 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5931 CK_BitCast,
5932 IV->getBase());
5933 // Don't forget the parens to enforce the proper binding.
5934 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5935 IV->getBase()->getLocEnd(), castExpr);
5936 // Cannot delete IV->getBase(), since PE points to it.
5937 // Replace the old base with the cast. This is important when doing
5938 // embedded rewrites. For example, [newInv->_container addObject:0].
5939 IV->setBase(PE);
5940 }
5941 }
5942
5943 ReplaceStmtWithRange(IV, Replacement, OldRange);
5944 return Replacement;
5945}