blob: 1c1243a230c7fe016026894a2041efb20c89845f [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
John McCalld935e9c2011-06-15 23:37:01 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00008//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000024//
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman14acfac2013-07-06 01:39:23 +000027#include "ARCRuntimeEntryPoints.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "BlotMapVector.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000030#include "ObjCARC.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
Michael Gottesman68b91db2015-03-05 23:29:03 +000032#include "PtrState.h"
John McCalld935e9c2011-06-15 23:37:01 +000033#include "llvm/ADT/DenseMap.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000034#include "llvm/ADT/None.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000035#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000036#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000037#include "llvm/ADT/SmallVector.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/ADT/Statistic.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000039#include "llvm/Analysis/AliasAnalysis.h"
Saleem Abdulrasool8b342682018-03-12 21:46:09 +000040#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth0f792182015-08-20 08:06:03 +000041#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000042#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
43#include "llvm/Analysis/ObjCARCInstKind.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000045#include "llvm/IR/CFG.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000046#include "llvm/IR/CallSite.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DerivedTypes.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalVariable.h"
52#include "llvm/IR/InstIterator.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
55#include "llvm/IR/Instructions.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000056#include "llvm/IR/LLVMContext.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000057#include "llvm/IR/Metadata.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Compiler.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000064#include "llvm/Support/Debug.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000065#include "llvm/Support/ErrorHandling.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000066#include "llvm/Support/raw_ostream.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000067#include <cassert>
68#include <iterator>
69#include <utility>
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000070
John McCalld935e9c2011-06-15 23:37:01 +000071using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000072using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "objc-arc-opts"
75
Michael Gottesman97e3df02013-01-14 00:35:14 +000076/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
77/// @{
John McCalld935e9c2011-06-15 23:37:01 +000078
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000079/// This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000080/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000081static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +000082 // ConstantData (like ConstantPointerNull and UndefValue) is used across
83 // modules. It's never a single-use value.
84 if (isa<ConstantData>(Arg))
85 return nullptr;
86
John McCalld935e9c2011-06-15 23:37:01 +000087 if (Arg->hasOneUse()) {
88 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
89 return FindSingleUseIdentifiedObject(BC->getOperand(0));
90 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
91 if (GEP->hasAllZeroIndices())
92 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000093 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000094 return FindSingleUseIdentifiedObject(
95 cast<CallInst>(Arg)->getArgOperand(0));
96 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000097 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000098 return Arg;
99 }
100
Dan Gohman41375a32012-05-08 23:39:44 +0000101 // If we found an identifiable object but it has multiple uses, but they are
102 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000103 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000104 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000105 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +0000106 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000107
108 return Arg;
109 }
110
Craig Topperf40110f2014-04-25 05:29:35 +0000111 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000112}
113
Michael Gottesman97e3df02013-01-14 00:35:14 +0000114/// @}
115///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000116/// \defgroup ARCOpt ARC Optimization.
117/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000118
119// TODO: On code like this:
120//
121// objc_retain(%x)
122// stuff_that_cannot_release()
123// objc_autorelease(%x)
124// stuff_that_cannot_release()
125// objc_retain(%x)
126// stuff_that_cannot_release()
127// objc_autorelease(%x)
128//
129// The second retain and autorelease can be deleted.
130
131// TODO: It should be possible to delete
132// objc_autoreleasePoolPush and objc_autoreleasePoolPop
133// pairs if nothing is actually autoreleased between them. Also, autorelease
134// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
135// after inlining) can be turned into plain release calls.
136
137// TODO: Critical-edge splitting. If the optimial insertion point is
138// a critical edge, the current algorithm has to fail, because it doesn't
139// know how to split edges. It should be possible to make the optimizer
140// think in terms of edges, rather than blocks, and then split critical
141// edges on demand.
142
143// TODO: OptimizeSequences could generalized to be Interprocedural.
144
145// TODO: Recognize that a bunch of other objc runtime calls have
146// non-escaping arguments and non-releasing arguments, and may be
147// non-autoreleasing.
148
149// TODO: Sink autorelease calls as far as possible. Unfortunately we
150// usually can't sink them past other calls, which would be the main
151// case where it would be useful.
152
Dan Gohmanb3894012011-08-19 00:26:36 +0000153// TODO: The pointer returned from objc_loadWeakRetained is retained.
154
155// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000156
John McCalld935e9c2011-06-15 23:37:01 +0000157STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
158STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
159STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
160STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000161 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000162STATISTIC(NumRRs, "Number of retain+release paths eliminated");
163STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000164#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000165STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000166 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000167STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000168 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000169STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000170 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000171STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000172 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000173#endif
John McCalld935e9c2011-06-15 23:37:01 +0000174
175namespace {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000176
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000177 /// Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000178 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179 /// The number of unique control paths from the entry which can reach this
180 /// block.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000181 unsigned TopDownPathCount = 0;
John McCalld935e9c2011-06-15 23:37:01 +0000182
Michael Gottesman97e3df02013-01-14 00:35:14 +0000183 /// The number of unique control paths to exits from this block.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000184 unsigned BottomUpPathCount = 0;
John McCalld935e9c2011-06-15 23:37:01 +0000185
Michael Gottesman97e3df02013-01-14 00:35:14 +0000186 /// The top-down traversal uses this to record information known about a
187 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000188 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000189
Michael Gottesman97e3df02013-01-14 00:35:14 +0000190 /// The bottom-up traversal uses this to record information known about a
191 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000192 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000193
Michael Gottesman97e3df02013-01-14 00:35:14 +0000194 /// Effective predecessors of the current block ignoring ignorable edges and
195 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000196 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000197
Michael Gottesman97e3df02013-01-14 00:35:14 +0000198 /// Effective successors of the current block ignoring ignorable edges and
199 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000200 SmallVector<BasicBlock *, 2> Succs;
201
John McCalld935e9c2011-06-15 23:37:01 +0000202 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000203 static const unsigned OverflowOccurredValue;
204
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000205 BBState() = default;
John McCalld935e9c2011-06-15 23:37:01 +0000206
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000207 using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
208 using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000209
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000210 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
211 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
212 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000213 return PerPtrTopDown.begin();
214 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000215 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000216 return PerPtrTopDown.end();
217 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000218 bool hasTopDownPtrs() const {
219 return !PerPtrTopDown.empty();
220 }
John McCalld935e9c2011-06-15 23:37:01 +0000221
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000222 using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
223 using const_bottom_up_ptr_iterator =
224 decltype(PerPtrBottomUp)::const_iterator;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000225
226 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000227 return PerPtrBottomUp.begin();
228 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000229 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
230 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
231 return PerPtrBottomUp.begin();
232 }
233 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000234 return PerPtrBottomUp.end();
235 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000236 bool hasBottomUpPtrs() const {
237 return !PerPtrBottomUp.empty();
238 }
John McCalld935e9c2011-06-15 23:37:01 +0000239
Michael Gottesman97e3df02013-01-14 00:35:14 +0000240 /// Mark this block as being an entry block, which has one path from the
241 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000242 void SetAsEntry() { TopDownPathCount = 1; }
243
Michael Gottesman97e3df02013-01-14 00:35:14 +0000244 /// Mark this block as being an exit block, which has one path to an exit by
245 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000246 void SetAsExit() { BottomUpPathCount = 1; }
247
Michael Gottesman993fbf72013-05-13 19:40:39 +0000248 /// Attempt to find the PtrState object describing the top down state for
249 /// pointer Arg. Return a new initialized PtrState describing the top down
250 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000251 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000252 return PerPtrTopDown[Arg];
253 }
254
Michael Gottesman993fbf72013-05-13 19:40:39 +0000255 /// Attempt to find the PtrState object describing the bottom up state for
256 /// pointer Arg. Return a new initialized PtrState describing the bottom up
257 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000258 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000259 return PerPtrBottomUp[Arg];
260 }
261
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000262 /// Attempt to find the PtrState object describing the bottom up state for
263 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000264 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000265 return PerPtrBottomUp.find(Arg);
266 }
267
John McCalld935e9c2011-06-15 23:37:01 +0000268 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000269 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000270 }
271
272 void clearTopDownPointers() {
273 PerPtrTopDown.clear();
274 }
275
276 void InitFromPred(const BBState &Other);
277 void InitFromSucc(const BBState &Other);
278 void MergePred(const BBState &Other);
279 void MergeSucc(const BBState &Other);
280
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000281 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000282 /// which pass through this block. This is only valid after both the
283 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000284 ///
Alp Tokercb402912014-01-24 17:20:08 +0000285 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000286 /// occur.
287 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000288 if (TopDownPathCount == OverflowOccurredValue ||
289 BottomUpPathCount == OverflowOccurredValue)
290 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000291 unsigned long long Product =
292 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000293 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000294 // the lower bits of Product are all set.
295 return (Product >> 32) ||
296 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000297 }
Dan Gohman12130272011-08-12 00:26:31 +0000298
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000299 // Specialized CFG utilities.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000300 using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator;
301
Michael Gottesman0fecf982013-08-07 23:56:34 +0000302 edge_iterator pred_begin() const { return Preds.begin(); }
303 edge_iterator pred_end() const { return Preds.end(); }
304 edge_iterator succ_begin() const { return Succs.begin(); }
305 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000306
307 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
308 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
309
310 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000311 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000312
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000313} // end anonymous namespace
314
315const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000316
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000317namespace llvm {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000318
Michael Gottesmand63436f2015-03-16 08:00:27 +0000319raw_ostream &operator<<(raw_ostream &OS,
320 BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000321
322} // end namespace llvm
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000323
John McCalld935e9c2011-06-15 23:37:01 +0000324void BBState::InitFromPred(const BBState &Other) {
325 PerPtrTopDown = Other.PerPtrTopDown;
326 TopDownPathCount = Other.TopDownPathCount;
327}
328
329void BBState::InitFromSucc(const BBState &Other) {
330 PerPtrBottomUp = Other.PerPtrBottomUp;
331 BottomUpPathCount = Other.BottomUpPathCount;
332}
333
Michael Gottesman97e3df02013-01-14 00:35:14 +0000334/// The top-down traversal uses this to merge information about predecessors to
335/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000336void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000337 if (TopDownPathCount == OverflowOccurredValue)
338 return;
339
John McCalld935e9c2011-06-15 23:37:01 +0000340 // Other.TopDownPathCount can be 0, in which case it is either dead or a
341 // loop backedge. Loop backedges are special.
342 TopDownPathCount += Other.TopDownPathCount;
343
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000344 // In order to be consistent, we clear the top down pointers when by adding
345 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000346 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000347 if (TopDownPathCount == OverflowOccurredValue) {
348 clearTopDownPointers();
349 return;
350 }
351
Michael Gottesman4385edf2013-01-14 01:47:53 +0000352 // Check for overflow. If we have overflow, fall back to conservative
353 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000354 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000355 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000356 clearTopDownPointers();
357 return;
358 }
359
John McCalld935e9c2011-06-15 23:37:01 +0000360 // For each entry in the other set, if our set has an entry with the same key,
361 // merge the entries. Otherwise, copy the entry and merge it with an empty
362 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000363 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
364 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000365 auto Pair = PerPtrTopDown.insert(*MI);
366 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000367 /*TopDown=*/true);
368 }
369
Dan Gohman7e315fc32011-08-11 21:06:32 +0000370 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000371 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000372 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000373 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000374 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000375}
376
Michael Gottesman97e3df02013-01-14 00:35:14 +0000377/// The bottom-up traversal uses this to merge information about successors to
378/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000379void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000380 if (BottomUpPathCount == OverflowOccurredValue)
381 return;
382
John McCalld935e9c2011-06-15 23:37:01 +0000383 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
384 // loop backedge. Loop backedges are special.
385 BottomUpPathCount += Other.BottomUpPathCount;
386
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000387 // In order to be consistent, we clear the top down pointers when by adding
388 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000389 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000390 if (BottomUpPathCount == OverflowOccurredValue) {
391 clearBottomUpPointers();
392 return;
393 }
394
Michael Gottesman4385edf2013-01-14 01:47:53 +0000395 // Check for overflow. If we have overflow, fall back to conservative
396 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000397 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000398 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000399 clearBottomUpPointers();
400 return;
401 }
402
John McCalld935e9c2011-06-15 23:37:01 +0000403 // For each entry in the other set, if our set has an entry with the
404 // same key, merge the entries. Otherwise, copy the entry and merge
405 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000406 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
407 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000408 auto Pair = PerPtrBottomUp.insert(*MI);
409 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000410 /*TopDown=*/false);
411 }
412
Dan Gohman7e315fc32011-08-11 21:06:32 +0000413 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000414 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000415 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
416 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000417 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000418 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000419}
420
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000421raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
422 // Dump the pointers we are tracking.
423 OS << " TopDown State:\n";
424 if (!BBInfo.hasTopDownPtrs()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000425 LLVM_DEBUG(dbgs() << " NONE!\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000426 } else {
427 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
428 I != E; ++I) {
429 const PtrState &P = I->second;
430 OS << " Ptr: " << *I->first
431 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
432 << "\n ImpreciseRelease: "
433 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
434 << " HasCFGHazards: "
435 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
436 << " KnownPositive: "
437 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
438 << " Seq: "
439 << P.GetSeq() << "\n";
440 }
441 }
442
443 OS << " BottomUp State:\n";
444 if (!BBInfo.hasBottomUpPtrs()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000445 LLVM_DEBUG(dbgs() << " NONE!\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000446 } else {
447 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
448 I != E; ++I) {
449 const PtrState &P = I->second;
450 OS << " Ptr: " << *I->first
451 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
452 << "\n ImpreciseRelease: "
453 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
454 << " HasCFGHazards: "
455 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
456 << " KnownPositive: "
457 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
458 << " Seq: "
459 << P.GetSeq() << "\n";
460 }
461 }
462
463 return OS;
464}
465
John McCalld935e9c2011-06-15 23:37:01 +0000466namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000467
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000468 /// The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000469 class ObjCARCOpt : public FunctionPass {
470 bool Changed;
471 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000472
473 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000474 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000475
Michael Gottesman41c01002015-03-06 00:34:33 +0000476 /// A cache of MDKinds that can be passed into other functions to propagate
477 /// MDKind identifiers.
478 ARCMDKindCache MDKindCache;
479
Michael Gottesman97e3df02013-01-14 00:35:14 +0000480 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000481 bool Run;
482
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000483 /// Flags which determine whether each of the interesting runtime functions
Michael Gottesman97e3df02013-01-14 00:35:14 +0000484 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000485 unsigned UsedInThisFunction;
486
John McCalld935e9c2011-06-15 23:37:01 +0000487 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000488 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000489 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000490 void OptimizeIndividualCalls(Function &F);
491
492 void CheckForCFGHazards(const BasicBlock *BB,
493 DenseMap<const BasicBlock *, BBState> &BBStates,
494 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000495 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
496 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000497 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000498 bool VisitBottomUp(BasicBlock *BB,
499 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000500 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000501 bool VisitInstructionTopDown(Instruction *Inst,
502 DenseMap<Value *, RRInfo> &Releases,
503 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000504 bool VisitTopDown(BasicBlock *BB,
505 DenseMap<const BasicBlock *, BBState> &BBStates,
506 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000507 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
508 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000509 DenseMap<Value *, RRInfo> &Releases);
510
511 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000512 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000513 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000514 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000515
Michael Gottesman67792172015-03-16 07:02:30 +0000516 bool
517 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
518 BlotMapVector<Value *, RRInfo> &Retains,
519 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +0000520 Instruction * Retain,
Michael Gottesman67792172015-03-16 07:02:30 +0000521 SmallVectorImpl<Instruction *> &DeadInsts,
522 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
523 Value *Arg, bool KnownSafe,
524 bool &AnyPairsCompletelyEliminated);
Michael Gottesman9de6f962013-01-22 21:49:00 +0000525
John McCalld935e9c2011-06-15 23:37:01 +0000526 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000527 BlotMapVector<Value *, RRInfo> &Retains,
528 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000529
530 void OptimizeWeakCalls(Function &F);
531
532 bool OptimizeSequences(Function &F);
533
534 void OptimizeReturns(Function &F);
535
Michael Gottesman9c118152013-04-29 06:16:57 +0000536#ifndef NDEBUG
537 void GatherStatistics(Function &F, bool AfterOptimization = false);
538#endif
539
Craig Topper3e4c6972014-03-05 09:10:37 +0000540 void getAnalysisUsage(AnalysisUsage &AU) const override;
541 bool doInitialization(Module &M) override;
542 bool runOnFunction(Function &F) override;
543 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000544
545 public:
546 static char ID;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000547
John McCalld935e9c2011-06-15 23:37:01 +0000548 ObjCARCOpt() : FunctionPass(ID) {
549 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
550 }
551 };
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000552
553} // end anonymous namespace
John McCalld935e9c2011-06-15 23:37:01 +0000554
555char ObjCARCOpt::ID = 0;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000556
John McCalld935e9c2011-06-15 23:37:01 +0000557INITIALIZE_PASS_BEGIN(ObjCARCOpt,
558 "objc-arc", "ObjC ARC optimization", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000559INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
John McCalld935e9c2011-06-15 23:37:01 +0000560INITIALIZE_PASS_END(ObjCARCOpt,
561 "objc-arc", "ObjC ARC optimization", false, false)
562
563Pass *llvm::createObjCARCOptPass() {
564 return new ObjCARCOpt();
565}
566
567void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000568 AU.addRequired<ObjCARCAAWrapperPass>();
569 AU.addRequired<AAResultsWrapperPass>();
John McCalld935e9c2011-06-15 23:37:01 +0000570 // ARC optimization doesn't currently split critical edges.
571 AU.setPreservesCFG();
572}
573
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
575/// not a return value. Or, if it can be paired with an
576/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000577bool
578ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000579 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000580 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000581 ImmutableCallSite CS(Arg);
582 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000583 if (Call->getParent() == RetainRV->getParent()) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000584 BasicBlock::const_iterator I(Call);
John McCalld935e9c2011-06-15 23:37:01 +0000585 ++I;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000586 while (IsNoopInstruction(&*I))
587 ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000588 if (&*I == RetainRV)
589 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000590 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000591 BasicBlock *RetainRVParent = RetainRV->getParent();
592 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000593 BasicBlock::const_iterator I = RetainRVParent->begin();
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000594 while (IsNoopInstruction(&*I))
595 ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000596 if (&*I == RetainRV)
597 return false;
598 }
John McCalld935e9c2011-06-15 23:37:01 +0000599 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000600 }
John McCalld935e9c2011-06-15 23:37:01 +0000601
Pete Cooper697281d2019-01-03 01:38:08 +0000602 // Track PHIs which are equivalent to our Arg.
603 SmallDenseSet<const Value*, 2> EquivalentArgs;
604 EquivalentArgs.insert(Arg);
605
606 // Add PHIs that are equivalent to Arg to ArgUsers.
607 if (const PHINode *PN = dyn_cast<PHINode>(Arg)) {
608 SmallVector<const Value *, 2> ArgUsers;
609 getEquivalentPHIs(*PN, ArgUsers);
610 EquivalentArgs.insert(ArgUsers.begin(), ArgUsers.end());
611 }
612
John McCalld935e9c2011-06-15 23:37:01 +0000613 // Check for being preceded by an objc_autoreleaseReturnValue on the same
614 // pointer. In this case, we can delete the pair.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000615 BasicBlock::iterator I = RetainRV->getIterator(),
616 Begin = RetainRV->getParent()->begin();
John McCalld935e9c2011-06-15 23:37:01 +0000617 if (I != Begin) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000618 do
619 --I;
620 while (I != Begin && IsNoopInstruction(&*I));
621 if (GetBasicARCInstKind(&*I) == ARCInstKind::AutoreleaseRV &&
Pete Cooper697281d2019-01-03 01:38:08 +0000622 EquivalentArgs.count(GetArgRCIdentityRoot(&*I))) {
John McCalld935e9c2011-06-15 23:37:01 +0000623 Changed = true;
624 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000625
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000626 LLVM_DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
627 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000628
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000629 EraseInstruction(&*I);
John McCalld935e9c2011-06-15 23:37:01 +0000630 EraseInstruction(RetainRV);
631 return true;
632 }
633 }
634
635 // Turn it to a plain objc_retain.
636 Changed = true;
637 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000638
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000639 LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
640 "objc_retain since the operand is not a return value.\n"
641 "Old = "
642 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000643
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000644 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000645 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000646
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000647 LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000648
John McCalld935e9c2011-06-15 23:37:01 +0000649 return false;
650}
651
Michael Gottesman97e3df02013-01-14 00:35:14 +0000652/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
653/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000654void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
655 Instruction *AutoreleaseRV,
656 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000657 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000658 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +0000659
660 // If the argument is ConstantPointerNull or UndefValue, its other users
661 // aren't actually interesting to look at.
662 if (isa<ConstantData>(Ptr))
663 return;
664
Dan Gohman10a18d52011-08-12 00:36:31 +0000665 SmallVector<const Value *, 2> Users;
666 Users.push_back(Ptr);
Akira Hatanaka73ceb502018-01-19 23:51:13 +0000667
668 // Add PHIs that are equivalent to Ptr to Users.
669 if (const PHINode *PN = dyn_cast<PHINode>(Ptr))
670 getEquivalentPHIs(*PN, Users);
671
Dan Gohman10a18d52011-08-12 00:36:31 +0000672 do {
673 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000674 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000675 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000676 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000677 if (isa<BitCastInst>(U))
678 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000679 }
680 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000681
682 Changed = true;
683 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000684
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000685 LLVM_DEBUG(
686 dbgs() << "Transforming objc_autoreleaseReturnValue => "
687 "objc_autorelease since its operand is not used as a return "
688 "value.\n"
689 "Old = "
690 << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000691
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000692 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000693 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000694 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000695 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000696 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000697
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000698 LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000699}
700
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000701namespace {
702Instruction *
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000703CloneCallInstForBB(CallInst &CI, BasicBlock &BB,
Shoaib Meenai106df7d2018-04-20 22:14:45 +0000704 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000705 SmallVector<OperandBundleDef, 1> OpBundles;
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000706 for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) {
707 auto Bundle = CI.getOperandBundleAt(I);
708 // Funclets will be reassociated in the future.
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000709 if (Bundle.getTagID() == LLVMContext::OB_funclet)
710 continue;
711 OpBundles.emplace_back(Bundle);
712 }
713
714 if (!BlockColors.empty()) {
715 const ColorVector &CV = BlockColors.find(&BB)->second;
716 assert(CV.size() == 1 && "non-unique color for block!");
717 Instruction *EHPad = CV.front()->getFirstNonPHI();
718 if (EHPad->isEHPad())
719 OpBundles.emplace_back("funclet", EHPad);
720 }
721
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000722 return CallInst::Create(&CI, OpBundles);
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000723}
724}
725
Michael Gottesman97e3df02013-01-14 00:35:14 +0000726/// Visit each call, one at a time, and make simplifications without doing any
727/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000728void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000729 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000730 // Reset all the flags in preparation for recomputing them.
731 UsedInThisFunction = 0;
732
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000733 DenseMap<BasicBlock *, ColorVector> BlockColors;
734 if (F.hasPersonalityFn() &&
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000735 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000736 BlockColors = colorEHFunclets(F);
737
John McCalld935e9c2011-06-15 23:37:01 +0000738 // Visit all objc_* calls in F.
739 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
740 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000741
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000742 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000743
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000744 LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000745
John McCalld935e9c2011-06-15 23:37:01 +0000746 switch (Class) {
747 default: break;
748
749 // Delete no-op casts. These function calls have special semantics, but
750 // the semantics are entirely implemented via lowering in the front-end,
751 // so by the time they reach the optimizer, they are just no-op calls
752 // which return their argument.
753 //
754 // There are gray areas here, as the ability to cast reference-counted
755 // pointers to raw void* and back allows code to break ARC assumptions,
756 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000757 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000758 Changed = true;
759 ++NumNoops;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000760 LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000761 EraseInstruction(Inst);
762 continue;
763
764 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000765 case ARCInstKind::StoreWeak:
766 case ARCInstKind::LoadWeak:
767 case ARCInstKind::LoadWeakRetained:
768 case ARCInstKind::InitWeak:
769 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000770 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000771 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000772 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000773 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000774 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
775 Constant::getNullValue(Ty),
776 CI);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000777 Value *NewValue = UndefValue::get(CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000778 LLVM_DEBUG(
779 dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
780 "\nOld = "
781 << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000782 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000783 CI->eraseFromParent();
784 continue;
785 }
786 break;
787 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000788 case ARCInstKind::CopyWeak:
789 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000790 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000791 if (IsNullOrUndef(CI->getArgOperand(0)) ||
792 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000793 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000794 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000795 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
796 Constant::getNullValue(Ty),
797 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000798
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000799 Value *NewValue = UndefValue::get(CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000800 LLVM_DEBUG(
801 dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
802 "\nOld = "
803 << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000804
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000805 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000806 CI->eraseFromParent();
807 continue;
808 }
809 break;
810 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000811 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000812 if (OptimizeRetainRVCall(F, Inst))
813 continue;
814 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000815 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000816 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000817 break;
818 }
819
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000820 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000821 if (IsAutorelease(Class) && Inst->use_empty()) {
822 CallInst *Call = cast<CallInst>(Inst);
823 const Value *Arg = Call->getArgOperand(0);
824 Arg = FindSingleUseIdentifiedObject(Arg);
825 if (Arg) {
826 Changed = true;
827 ++NumAutoreleases;
828
829 // Create the declaration lazily.
830 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000831
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000832 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000833 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
834 Call);
Michael Gottesman65cb7372015-03-16 07:02:27 +0000835 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
Michael Gottesman41c01002015-03-06 00:34:33 +0000836 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000837
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000838 LLVM_DEBUG(
839 dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
840 "since x is otherwise unused.\nOld: "
841 << *Call << "\nNew: " << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000842
John McCalld935e9c2011-06-15 23:37:01 +0000843 EraseInstruction(Call);
844 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000845 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000846 }
847 }
848
849 // For functions which can never be passed stack arguments, add
850 // a tail keyword.
851 if (IsAlwaysTail(Class)) {
852 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000853 LLVM_DEBUG(
854 dbgs() << "Adding tail keyword to function since it can never be "
855 "passed stack args: "
856 << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000857 cast<CallInst>(Inst)->setTailCall();
858 }
859
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000860 // Ensure that functions that can never have a "tail" keyword due to the
861 // semantics of ARC truly do not do so.
862 if (IsNeverTail(Class)) {
863 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000864 LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst
865 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000866 cast<CallInst>(Inst)->setTailCall(false);
867 }
868
John McCalld935e9c2011-06-15 23:37:01 +0000869 // Set nounwind as needed.
870 if (IsNoThrow(Class)) {
871 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000872 LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: "
873 << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000874 cast<CallInst>(Inst)->setDoesNotThrow();
875 }
876
877 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000878 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000879 continue;
880 }
881
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000882 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000883
884 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000885 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000886 Changed = true;
887 ++NumNoops;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000888 LLVM_DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
889 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000890 EraseInstruction(Inst);
891 continue;
892 }
893
894 // Keep track of which of retain, release, autorelease, and retain_block
895 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000896 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000897
898 // If Arg is a PHI, and one or more incoming values to the
899 // PHI are null, and the call is control-equivalent to the PHI, and there
Akira Hatanakae8c1a542017-10-16 16:46:59 +0000900 // are no relevant side effects between the PHI and the call, and the call
901 // is not a release that doesn't have the clang.imprecise_release tag, the
902 // call could be pushed up to just those paths with non-null incoming
903 // values. For now, don't bother splitting critical edges for this.
904 if (Class == ARCInstKind::Release &&
905 !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease)))
906 continue;
907
John McCalld935e9c2011-06-15 23:37:01 +0000908 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
909 Worklist.push_back(std::make_pair(Inst, Arg));
910 do {
911 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
912 Inst = Pair.first;
913 Arg = Pair.second;
914
915 const PHINode *PN = dyn_cast<PHINode>(Arg);
916 if (!PN) continue;
917
918 // Determine if the PHI has any null operands, or any incoming
919 // critical edges.
920 bool HasNull = false;
921 bool HasCriticalEdges = false;
922 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
923 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000924 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000925 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000926 HasNull = true;
Chandler Carruthc1e3ee22018-10-18 00:38:34 +0000927 else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() !=
928 1) {
John McCalld935e9c2011-06-15 23:37:01 +0000929 HasCriticalEdges = true;
930 break;
931 }
932 }
933 // If we have null operands and no critical edges, optimize.
934 if (!HasCriticalEdges && HasNull) {
935 SmallPtrSet<Instruction *, 4> DependingInstructions;
936 SmallPtrSet<const BasicBlock *, 4> Visited;
937
938 // Check that there is nothing that cares about the reference
939 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000940 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000941 case ARCInstKind::Retain:
942 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000943 // These can always be moved up.
944 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000945 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000946 // These can't be moved across things that care about the retain
947 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000948 FindDependencies(NeedsPositiveRetainCount, Arg,
949 Inst->getParent(), Inst,
950 DependingInstructions, Visited, PA);
951 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000952 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000953 // These can't be moved across autorelease pool scope boundaries.
954 FindDependencies(AutoreleasePoolBoundary, Arg,
955 Inst->getParent(), Inst,
956 DependingInstructions, Visited, PA);
957 break;
Frederic Riss009d6062016-02-17 18:51:27 +0000958 case ARCInstKind::ClaimRV:
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000959 case ARCInstKind::RetainRV:
960 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000961 // Don't move these; the RV optimization depends on the autoreleaseRV
962 // being tail called, and the retainRV being immediately after a call
963 // (which might still happen if we get lucky with codegen layout, but
964 // it's not worth taking the chance).
965 continue;
966 default:
967 llvm_unreachable("Invalid dependence flavor");
968 }
969
John McCalld935e9c2011-06-15 23:37:01 +0000970 if (DependingInstructions.size() == 1 &&
971 *DependingInstructions.begin() == PN) {
972 Changed = true;
973 ++NumPartialNoops;
974 // Clone the call into each predecessor that has a non-null value.
975 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000976 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000977 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
978 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000979 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000980 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000981 Value *Op = PN->getIncomingValue(i);
982 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000983 CallInst *Clone = cast<CallInst>(CloneCallInstForBB(
984 *CInst, *InsertPos->getParent(), BlockColors));
John McCalld935e9c2011-06-15 23:37:01 +0000985 if (Op->getType() != ParamTy)
986 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
987 Clone->setArgOperand(0, Op);
988 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000989
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000990 LLVM_DEBUG(dbgs() << "Cloning " << *CInst
991 << "\n"
992 "And inserting clone at "
993 << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000994 Worklist.push_back(std::make_pair(Clone, Incoming));
995 }
996 }
997 // Erase the original call.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000998 LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000999 EraseInstruction(CInst);
1000 continue;
1001 }
1002 }
1003 } while (!Worklist.empty());
1004 }
1005}
1006
Michael Gottesman323964c2013-04-18 05:39:45 +00001007/// If we have a top down pointer in the S_Use state, make sure that there are
1008/// no CFG hazards by checking the states of various bottom up pointers.
1009static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1010 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001011 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +00001012 bool &SomeSuccHasSame,
1013 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001014 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001015 bool &ShouldContinue) {
1016 switch (SuccSSeq) {
1017 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001018 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001019 S.ClearSequenceProgress();
1020 break;
1021 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001022 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001023 ShouldContinue = true;
1024 break;
1025 }
1026 case S_Use:
1027 SomeSuccHasSame = true;
1028 break;
1029 case S_Stop:
1030 case S_Release:
1031 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001032 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001033 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001034 else
1035 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001036 break;
1037 case S_Retain:
1038 llvm_unreachable("bottom-up pointer in retain state!");
1039 case S_None:
1040 llvm_unreachable("This should have been handled earlier.");
1041 }
1042}
1043
1044/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1045/// there are no CFG hazards by checking the states of various bottom up
1046/// pointers.
1047static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1048 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001049 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +00001050 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001051 bool &AllSuccsHaveSame,
1052 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001053 switch (SuccSSeq) {
1054 case S_CanRelease:
1055 SomeSuccHasSame = true;
1056 break;
1057 case S_Stop:
1058 case S_Release:
1059 case S_MovableRelease:
1060 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001061 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001062 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001063 else
1064 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001065 break;
1066 case S_Retain:
1067 llvm_unreachable("bottom-up pointer in retain state!");
1068 case S_None:
1069 llvm_unreachable("This should have been handled earlier.");
1070 }
1071}
1072
Michael Gottesman97e3df02013-01-14 00:35:14 +00001073/// Check for critical edges, loop boundaries, irreducible control flow, or
1074/// other CFG structures where moving code across the edge would result in it
1075/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001076void
1077ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1078 DenseMap<const BasicBlock *, BBState> &BBStates,
1079 BBState &MyStates) const {
1080 // If any top-down local-use or possible-dec has a succ which is earlier in
1081 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001082 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
1083 I != E; ++I) {
1084 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +00001085 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001086
Michael Gottesman323964c2013-04-18 05:39:45 +00001087 // We only care about S_Retain, S_CanRelease, and S_Use.
1088 if (Seq == S_None)
1089 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001090
Michael Gottesman323964c2013-04-18 05:39:45 +00001091 // Make sure that if extra top down states are added in the future that this
1092 // code is updated to handle it.
1093 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1094 "Unknown top down sequence state.");
1095
1096 const Value *Arg = I->first;
Michael Gottesman323964c2013-04-18 05:39:45 +00001097 bool SomeSuccHasSame = false;
1098 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001099 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001100
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001101 for (const BasicBlock *Succ : successors(BB)) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001102 // If VisitBottomUp has pointer information for this successor, take
1103 // what we know about it.
1104 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001105 BBStates.find(Succ);
Michael Gottesman323964c2013-04-18 05:39:45 +00001106 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001107 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +00001108 const Sequence SuccSSeq = SuccS.GetSeq();
1109
1110 // If bottom up, the pointer is in an S_None state, clear the sequence
1111 // progress since the sequence in the bottom up state finished
1112 // suggesting a mismatch in between retains/releases. This is true for
1113 // all three cases that we are handling here: S_Retain, S_Use, and
1114 // S_CanRelease.
1115 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001116 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001117 continue;
1118 }
1119
1120 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1121 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001122 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001123
1124 // *NOTE* We do not use Seq from above here since we are allowing for
1125 // S.GetSeq() to change while we are visiting basic blocks.
1126 switch(S.GetSeq()) {
1127 case S_Use: {
1128 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001129 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1130 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001131 ShouldContinue);
1132 if (ShouldContinue)
1133 continue;
1134 break;
1135 }
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001136 case S_CanRelease:
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001137 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1138 SomeSuccHasSame, AllSuccsHaveSame,
1139 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001140 break;
Michael Gottesman323964c2013-04-18 05:39:45 +00001141 case S_Retain:
1142 case S_None:
1143 case S_Stop:
1144 case S_Release:
1145 case S_MovableRelease:
1146 break;
1147 }
John McCalld935e9c2011-06-15 23:37:01 +00001148 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001149
1150 // If the state at the other end of any of the successor edges
1151 // matches the current state, require all edges to match. This
1152 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001153 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001154 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001155 } else if (NotAllSeqEqualButKnownSafe) {
1156 // If we would have cleared the state foregoing the fact that we are known
1157 // safe, stop code motion. This is because whether or not it is safe to
1158 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1159 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001160 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001161 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001162 }
John McCalld935e9c2011-06-15 23:37:01 +00001163}
1164
Michael Gottesman0be69202015-03-05 23:28:58 +00001165bool ObjCARCOpt::VisitInstructionBottomUp(
1166 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1167 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001168 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001169 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001170 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001171
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001172 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001173
Dan Gohman817a7c62012-03-22 18:24:56 +00001174 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001175 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001176 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001177
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001178 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001179 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001180 break;
1181 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001182 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001183 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1184 // objc_retainBlocks to objc_retains. Thus at this point any
1185 // objc_retainBlocks that we see are not optimizable.
1186 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001187 case ARCInstKind::Retain:
1188 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001189 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001190 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001191 if (S.MatchWithRetain()) {
1192 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1193 // it's better to let it remain as the first instruction after a call.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001194 if (Class != ARCInstKind::RetainRV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001195 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001196 Retains[Inst] = S.GetRRInfo();
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001197 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001198 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001199 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001200 // A retain moving bottom up can be a use.
1201 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001202 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001203 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001204 // Conservatively, clear MyStates for all known pointers.
1205 MyStates.clearBottomUpPointers();
1206 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001207 case ARCInstKind::AutoreleasepoolPush:
1208 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001209 // These are irrelevant.
1210 return NestingDetected;
1211 default:
1212 break;
1213 }
1214
1215 // Consider any other possible effects of this instruction on each
1216 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001217 for (auto MI = MyStates.bottom_up_ptr_begin(),
1218 ME = MyStates.bottom_up_ptr_end();
1219 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001220 const Value *Ptr = MI->first;
1221 if (Ptr == Arg)
1222 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001223 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001224
Michael Gottesman16e6a202015-03-06 02:07:12 +00001225 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1226 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001227
Michael Gottesman16e6a202015-03-06 02:07:12 +00001228 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001229 }
1230
1231 return NestingDetected;
1232}
1233
Michael Gottesman0be69202015-03-05 23:28:58 +00001234bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1235 DenseMap<const BasicBlock *, BBState> &BBStates,
1236 BlotMapVector<Value *, RRInfo> &Retains) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001237 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001238
John McCalld935e9c2011-06-15 23:37:01 +00001239 bool NestingDetected = false;
1240 BBState &MyStates = BBStates[BB];
1241
1242 // Merge the states from each successor to compute the initial state
1243 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001244 BBState::edge_iterator SI(MyStates.succ_begin()),
1245 SE(MyStates.succ_end());
1246 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001247 const BasicBlock *Succ = *SI;
1248 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1249 assert(I != BBStates.end());
1250 MyStates.InitFromSucc(I->second);
1251 ++SI;
1252 for (; SI != SE; ++SI) {
1253 Succ = *SI;
1254 I = BBStates.find(Succ);
1255 assert(I != BBStates.end());
1256 MyStates.MergeSucc(I->second);
1257 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001258 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001259
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001260 LLVM_DEBUG(dbgs() << "Before:\n"
1261 << BBStates[BB] << "\n"
1262 << "Performing Dataflow:\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001263
John McCalld935e9c2011-06-15 23:37:01 +00001264 // Visit all the instructions, bottom-up.
1265 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001266 Instruction *Inst = &*std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001267
1268 // Invoke instructions are visited as part of their successors (below).
1269 if (isa<InvokeInst>(Inst))
1270 continue;
1271
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001272 LLVM_DEBUG(dbgs() << " Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001273
Dan Gohman5c70fad2012-03-23 17:47:54 +00001274 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1275 }
1276
Dan Gohmandae33492012-04-27 18:56:31 +00001277 // If there's a predecessor with an invoke, visit the invoke as if it were
1278 // part of this block, since we can't insert code after an invoke in its own
1279 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001280 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1281 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001282 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001283 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1284 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001285 }
John McCalld935e9c2011-06-15 23:37:01 +00001286
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001287 LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001288
Dan Gohman817a7c62012-03-22 18:24:56 +00001289 return NestingDetected;
1290}
John McCalld935e9c2011-06-15 23:37:01 +00001291
Dan Gohman817a7c62012-03-22 18:24:56 +00001292bool
1293ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1294 DenseMap<Value *, RRInfo> &Releases,
1295 BBState &MyStates) {
1296 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001297 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001298 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001299
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001300 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001301
Dan Gohman817a7c62012-03-22 18:24:56 +00001302 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001303 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001304 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1305 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001306 // objc_retainBlocks that we see are not optimizable. We need to break since
1307 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001308 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001309 case ARCInstKind::Retain:
1310 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001311 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001312 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001313 NestingDetected |= S.InitTopDown(Class, Inst);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001314 // A retain can be a potential use; proceed to the generic checking
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001315 // code below.
1316 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001317 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001318 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001319 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001320 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001321 // Try to form a tentative pair in between this release instruction and the
1322 // top down pointers that we are tracking.
1323 if (S.MatchWithRelease(MDKindCache, Inst)) {
1324 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1325 // Map}. Then we clear S.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001326 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001327 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001328 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001329 }
1330 break;
1331 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001332 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001333 // Conservatively, clear MyStates for all known pointers.
1334 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001335 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001336 case ARCInstKind::AutoreleasepoolPush:
1337 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001338 // These can not be uses of
1339 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001340 default:
1341 break;
1342 }
1343
1344 // Consider any other possible effects of this instruction on each
1345 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001346 for (auto MI = MyStates.top_down_ptr_begin(),
1347 ME = MyStates.top_down_ptr_end();
1348 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001349 const Value *Ptr = MI->first;
1350 if (Ptr == Arg)
1351 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001352 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001353 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1354 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001355
Michael Gottesman16e6a202015-03-06 02:07:12 +00001356 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001357 }
1358
1359 return NestingDetected;
1360}
1361
1362bool
1363ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1364 DenseMap<const BasicBlock *, BBState> &BBStates,
1365 DenseMap<Value *, RRInfo> &Releases) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001366 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001367 bool NestingDetected = false;
1368 BBState &MyStates = BBStates[BB];
1369
1370 // Merge the states from each predecessor to compute the initial state
1371 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001372 BBState::edge_iterator PI(MyStates.pred_begin()),
1373 PE(MyStates.pred_end());
1374 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001375 const BasicBlock *Pred = *PI;
1376 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1377 assert(I != BBStates.end());
1378 MyStates.InitFromPred(I->second);
1379 ++PI;
1380 for (; PI != PE; ++PI) {
1381 Pred = *PI;
1382 I = BBStates.find(Pred);
1383 assert(I != BBStates.end());
1384 MyStates.MergePred(I->second);
1385 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001386 }
John McCalld935e9c2011-06-15 23:37:01 +00001387
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001388 LLVM_DEBUG(dbgs() << "Before:\n"
1389 << BBStates[BB] << "\n"
1390 << "Performing Dataflow:\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001391
John McCalld935e9c2011-06-15 23:37:01 +00001392 // Visit all the instructions, top-down.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001393 for (Instruction &Inst : *BB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001394 LLVM_DEBUG(dbgs() << " Visiting " << Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001395
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001396 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001397 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001398
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001399 LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n"
1400 << BBStates[BB] << "\n\n");
John McCalld935e9c2011-06-15 23:37:01 +00001401 CheckForCFGHazards(BB, BBStates, MyStates);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001402 LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001403 return NestingDetected;
1404}
1405
Dan Gohmana53a12c2011-12-12 19:42:25 +00001406static void
1407ComputePostOrders(Function &F,
1408 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001409 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1410 unsigned NoObjCARCExceptionsMDKind,
1411 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001412 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001413 SmallPtrSet<BasicBlock *, 16> Visited;
1414
1415 // Do DFS, computing the PostOrder.
1416 SmallPtrSet<BasicBlock *, 16> OnStack;
1417 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001418
1419 // Functions always have exactly one entry block, and we don't have
1420 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001421 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001422 BBState &MyStates = BBStates[EntryBB];
1423 MyStates.SetAsEntry();
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001424 Instruction *EntryTI = EntryBB->getTerminator();
Dan Gohman41375a32012-05-08 23:39:44 +00001425 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001426 Visited.insert(EntryBB);
1427 OnStack.insert(EntryBB);
1428 do {
1429 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001430 BasicBlock *CurrBB = SuccStack.back().first;
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001431 succ_iterator SE(CurrBB->getTerminator(), false);
Dan Gohman41375a32012-05-08 23:39:44 +00001432
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001433 while (SuccStack.back().second != SE) {
1434 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001435 if (Visited.insert(SuccBB).second) {
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001436 SuccStack.push_back(
1437 std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator())));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001438 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001439 BBState &SuccStates = BBStates[SuccBB];
1440 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001441 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001442 goto dfs_next_succ;
1443 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001444
1445 if (!OnStack.count(SuccBB)) {
1446 BBStates[CurrBB].addSucc(SuccBB);
1447 BBStates[SuccBB].addPred(CurrBB);
1448 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001449 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001450 OnStack.erase(CurrBB);
1451 PostOrder.push_back(CurrBB);
1452 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001453 } while (!SuccStack.empty());
1454
1455 Visited.clear();
1456
Dan Gohmana53a12c2011-12-12 19:42:25 +00001457 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001458 // Functions may have many exits, and there also blocks which we treat
1459 // as exits due to ignored edges.
1460 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001461 for (BasicBlock &ExitBB : F) {
1462 BBState &MyStates = BBStates[&ExitBB];
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001463 if (!MyStates.isExit())
1464 continue;
1465
Dan Gohmandae33492012-04-27 18:56:31 +00001466 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001467
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001468 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1469 Visited.insert(&ExitBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001470 while (!PredStack.empty()) {
1471 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001472 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1473 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001474 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001475 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001476 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001477 goto reverse_dfs_next_succ;
1478 }
1479 }
1480 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1481 }
1482 }
1483}
1484
Michael Gottesman97e3df02013-01-14 00:35:14 +00001485// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001486bool ObjCARCOpt::Visit(Function &F,
1487 DenseMap<const BasicBlock *, BBState> &BBStates,
1488 BlotMapVector<Value *, RRInfo> &Retains,
1489 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001490 // Use reverse-postorder traversals, because we magically know that loops
1491 // will be well behaved, i.e. they won't repeatedly call retain on a single
1492 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1493 // class here because we want the reverse-CFG postorder to consider each
1494 // function exit point, and we want to ignore selected cycle edges.
1495 SmallVector<BasicBlock *, 16> PostOrder;
1496 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001497 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman65cb7372015-03-16 07:02:27 +00001498 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1499 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001500
1501 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001502 bool BottomUpNestingDetected = false;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001503 for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder))
David Majnemerd7708772016-06-24 04:05:21 +00001504 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001505
Dan Gohmana53a12c2011-12-12 19:42:25 +00001506 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001507 bool TopDownNestingDetected = false;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001508 for (BasicBlock *BB : llvm::reverse(PostOrder))
David Majnemerd7708772016-06-24 04:05:21 +00001509 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001510
1511 return TopDownNestingDetected && BottomUpNestingDetected;
1512}
1513
Michael Gottesman97e3df02013-01-14 00:35:14 +00001514/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001515void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001516 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001517 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001518 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001519 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001520 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001521 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001522 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001523
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001524 LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001525
John McCalld935e9c2011-06-15 23:37:01 +00001526 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001527 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001528 Value *MyArg = ArgTy == ParamTy ? Arg :
1529 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001530 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001531 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001532 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001533 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001534
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001535 LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call
1536 << "\n"
1537 "At insertion point: "
1538 << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001539 }
Craig Topper46276792014-08-24 23:23:06 +00001540 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001541 Value *MyArg = ArgTy == ParamTy ? Arg :
1542 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001543 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001544 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001545 // Attach a clang.imprecise_release metadata tag, if appropriate.
1546 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman65cb7372015-03-16 07:02:27 +00001547 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001548 Call->setDoesNotThrow();
1549 if (ReleasesToMove.IsTailCallRelease)
1550 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001551
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001552 LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call
1553 << "\n"
1554 "At insertion point: "
1555 << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001556 }
1557
1558 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001559 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001560 Retains.blot(OrigRetain);
1561 DeadInsts.push_back(OrigRetain);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001562 LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001563 }
Craig Topper46276792014-08-24 23:23:06 +00001564 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001565 Releases.erase(OrigRelease);
1566 DeadInsts.push_back(OrigRelease);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001567 LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001568 }
1569}
1570
Michael Gottesman67792172015-03-16 07:02:30 +00001571bool ObjCARCOpt::PairUpRetainsAndReleases(
Michael Gottesman0be69202015-03-05 23:28:58 +00001572 DenseMap<const BasicBlock *, BBState> &BBStates,
1573 BlotMapVector<Value *, RRInfo> &Retains,
1574 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +00001575 Instruction *Retain,
Michael Gottesman0be69202015-03-05 23:28:58 +00001576 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1577 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1578 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001579 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001580 // is already incremented, we can similarly ignore possible decrements unless
1581 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001582 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001583 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001584
1585 // Connect the dots between the top-down-collected RetainsToMove and
1586 // bottom-up-collected ReleasesToMove to form sets of related calls.
1587 // This is an iterative process so that we connect multiple releases
1588 // to multiple retains if needed.
1589 unsigned OldDelta = 0;
1590 unsigned NewDelta = 0;
1591 unsigned OldCount = 0;
1592 unsigned NewCount = 0;
1593 bool FirstRelease = true;
Akira Hatanaka2b882052017-02-25 00:53:38 +00001594 for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
1595 SmallVector<Instruction *, 4> NewReleases;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001596 for (Instruction *NewRetain : NewRetains) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001597 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001598 assert(It != Retains.end());
1599 const RRInfo &NewRetainRRI = It->second;
1600 KnownSafeTD &= NewRetainRRI.KnownSafe;
Shoaib Meenai074728a2018-05-16 04:52:18 +00001601 CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001602 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001603 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001604 if (Jt == Releases.end())
1605 return false;
1606 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001607
1608 // If the release does not have a reference to the retain as well,
1609 // something happened which is unaccounted for. Do not do anything.
1610 //
1611 // This can happen if we catch an additive overflow during path count
1612 // merging.
1613 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1614 return false;
1615
David Blaikie70573dc2014-11-19 07:49:26 +00001616 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001617 // If we overflow when we compute the path count, don't remove/move
1618 // anything.
1619 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001620 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001621 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1622 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001623 assert(PathCount != BBState::OverflowOccurredValue &&
1624 "PathCount at this point can not be "
1625 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001626 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001627
1628 // Merge the ReleaseMetadata and IsTailCallRelease values.
1629 if (FirstRelease) {
1630 ReleasesToMove.ReleaseMetadata =
1631 NewRetainReleaseRRI.ReleaseMetadata;
1632 ReleasesToMove.IsTailCallRelease =
1633 NewRetainReleaseRRI.IsTailCallRelease;
1634 FirstRelease = false;
1635 } else {
1636 if (ReleasesToMove.ReleaseMetadata !=
1637 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001638 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001639 if (ReleasesToMove.IsTailCallRelease !=
1640 NewRetainReleaseRRI.IsTailCallRelease)
1641 ReleasesToMove.IsTailCallRelease = false;
1642 }
1643
1644 // Collect the optimal insertion points.
1645 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001646 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001647 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001648 // If we overflow when we compute the path count, don't
1649 // remove/move anything.
1650 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001651 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001652 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1653 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001654 assert(PathCount != BBState::OverflowOccurredValue &&
1655 "PathCount at this point can not be "
1656 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001657 NewDelta -= PathCount;
1658 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001659 }
1660 NewReleases.push_back(NewRetainRelease);
1661 }
1662 }
1663 }
1664 NewRetains.clear();
1665 if (NewReleases.empty()) break;
1666
1667 // Back the other way.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001668 for (Instruction *NewRelease : NewReleases) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001669 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001670 assert(It != Releases.end());
1671 const RRInfo &NewReleaseRRI = It->second;
1672 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001673 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001674 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001675 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001676 if (Jt == Retains.end())
1677 return false;
1678 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001679
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001680 // If the retain does not have a reference to the release as well,
1681 // something happened which is unaccounted for. Do not do anything.
1682 //
1683 // This can happen if we catch an additive overflow during path count
1684 // merging.
1685 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1686 return false;
1687
David Blaikie70573dc2014-11-19 07:49:26 +00001688 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001689 // If we overflow when we compute the path count, don't remove/move
1690 // anything.
1691 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001692 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001693 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1694 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001695 assert(PathCount != BBState::OverflowOccurredValue &&
1696 "PathCount at this point can not be "
1697 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001698 OldDelta += PathCount;
1699 OldCount += PathCount;
1700
Michael Gottesman9de6f962013-01-22 21:49:00 +00001701 // Collect the optimal insertion points.
1702 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001703 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001704 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001705 // If we overflow when we compute the path count, don't
1706 // remove/move anything.
1707 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001708
1709 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001710 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1711 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001712 assert(PathCount != BBState::OverflowOccurredValue &&
1713 "PathCount at this point can not be "
1714 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001715 NewDelta += PathCount;
1716 NewCount += PathCount;
1717 }
1718 }
1719 NewRetains.push_back(NewReleaseRetain);
1720 }
1721 }
1722 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001723 if (NewRetains.empty()) break;
1724 }
1725
Michael Gottesmandd60f9b2015-03-16 07:02:36 +00001726 // We can only remove pointers if we are known safe in both directions.
1727 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001728 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001729 RetainsToMove.ReverseInsertPts.clear();
1730 ReleasesToMove.ReverseInsertPts.clear();
1731 NewCount = 0;
1732 } else {
1733 // Determine whether the new insertion points we computed preserve the
1734 // balance of retain and release calls through the program.
1735 // TODO: If the fully aggressive solution isn't valid, try to find a
1736 // less aggressive solution which is.
1737 if (NewDelta != 0)
1738 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001739
1740 // At this point, we are not going to remove any RR pairs, but we still are
1741 // able to move RR pairs. If one of our pointers is afflicted with
1742 // CFGHazards, we cannot perform such code motion so exit early.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001743 const bool WillPerformCodeMotion =
1744 !RetainsToMove.ReverseInsertPts.empty() ||
1745 !ReleasesToMove.ReverseInsertPts.empty();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001746 if (CFGHazardAfflicted && WillPerformCodeMotion)
1747 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001748 }
1749
1750 // Determine whether the original call points are balanced in the retain and
1751 // release calls through the program. If not, conservatively don't touch
1752 // them.
1753 // TODO: It's theoretically possible to do code motion in this case, as
1754 // long as the existing imbalances are maintained.
1755 if (OldDelta != 0)
1756 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001757
Michael Gottesman9de6f962013-01-22 21:49:00 +00001758 Changed = true;
1759 assert(OldCount != 0 && "Unreachable code?");
1760 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001761 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001762 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001763
1764 // We can move calls!
1765 return true;
1766}
1767
Michael Gottesman97e3df02013-01-14 00:35:14 +00001768/// Identify pairings between the retains and releases, and delete and/or move
1769/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001770bool ObjCARCOpt::PerformCodePlacement(
1771 DenseMap<const BasicBlock *, BBState> &BBStates,
1772 BlotMapVector<Value *, RRInfo> &Retains,
1773 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001774 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
Michael Gottesman89279f82013-04-05 18:10:41 +00001775
John McCalld935e9c2011-06-15 23:37:01 +00001776 bool AnyPairsCompletelyEliminated = false;
John McCalld935e9c2011-06-15 23:37:01 +00001777 SmallVector<Instruction *, 8> DeadInsts;
1778
Dan Gohman670f9372012-04-13 18:57:48 +00001779 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001780 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1781 E = Retains.end();
1782 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001783 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001784 if (!V) continue; // blotted
1785
1786 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001787
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001788 LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001789
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001790 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001791
Dan Gohman728db492012-01-13 00:39:07 +00001792 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001793 // not being managed by ObjC reference counting, so we can delete pairs
1794 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001795 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001796
Dan Gohman56e1cef2011-08-22 17:29:11 +00001797 // A constant pointer can't be pointing to an object on the heap. It may
1798 // be reference-counted, but it won't be deleted.
1799 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1800 if (const GlobalVariable *GV =
1801 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001802 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001803 if (GV->isConstant())
1804 KnownSafe = true;
1805
John McCalld935e9c2011-06-15 23:37:01 +00001806 // Connect the dots between the top-down-collected RetainsToMove and
1807 // bottom-up-collected ReleasesToMove to form sets of related calls.
Akira Hatanaka2b882052017-02-25 00:53:38 +00001808 RRInfo RetainsToMove, ReleasesToMove;
1809
Michael Gottesman67792172015-03-16 07:02:30 +00001810 bool PerformMoveCalls = PairUpRetainsAndReleases(
Akira Hatanaka2b882052017-02-25 00:53:38 +00001811 BBStates, Retains, Releases, M, Retain, DeadInsts,
Michael Gottesman67792172015-03-16 07:02:30 +00001812 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1813 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001814
Michael Gottesman9de6f962013-01-22 21:49:00 +00001815 if (PerformMoveCalls) {
1816 // Ok, everything checks out and we're all set. Let's move/delete some
1817 // code!
1818 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1819 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001820 }
John McCalld935e9c2011-06-15 23:37:01 +00001821 }
1822
1823 // Now that we're done moving everything, we can delete the newly dead
1824 // instructions, as we no longer need them as insert points.
1825 while (!DeadInsts.empty())
1826 EraseInstruction(DeadInsts.pop_back_val());
1827
1828 return AnyPairsCompletelyEliminated;
1829}
1830
Michael Gottesman97e3df02013-01-14 00:35:14 +00001831/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001832void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001833 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001834
John McCalld935e9c2011-06-15 23:37:01 +00001835 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1836 // itself because it uses AliasAnalysis and we need to do provenance
1837 // queries instead.
1838 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1839 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001840
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001841 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001842
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001843 ARCInstKind Class = GetBasicARCInstKind(Inst);
1844 if (Class != ARCInstKind::LoadWeak &&
1845 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001846 continue;
1847
1848 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001849 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001850 Inst->eraseFromParent();
1851 continue;
1852 }
1853
1854 // TODO: For now, just look for an earlier available version of this value
1855 // within the same block. Theoretically, we could do memdep-style non-local
1856 // analysis too, but that would want caching. A better approach would be to
1857 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001858 inst_iterator Current = std::prev(I);
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001859 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
John McCalld935e9c2011-06-15 23:37:01 +00001860 for (BasicBlock::iterator B = CurrentBB->begin(),
1861 J = Current.getInstructionIterator();
1862 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001863 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001864 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001865 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001866 case ARCInstKind::LoadWeak:
1867 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001868 // If this is loading from the same pointer, replace this load's value
1869 // with that one.
1870 CallInst *Call = cast<CallInst>(Inst);
1871 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1872 Value *Arg = Call->getArgOperand(0);
1873 Value *EarlierArg = EarlierCall->getArgOperand(0);
1874 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001875 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001876 Changed = true;
1877 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001878 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001879 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001880 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001881 CI->setTailCall();
1882 }
1883 // Zap the fully redundant load.
1884 Call->replaceAllUsesWith(EarlierCall);
1885 Call->eraseFromParent();
1886 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001887 case MayAlias:
1888 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001889 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001890 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001891 break;
1892 }
1893 break;
1894 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001895 case ARCInstKind::StoreWeak:
1896 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001897 // If this is storing to the same pointer and has the same size etc.
1898 // replace this load's value with the stored value.
1899 CallInst *Call = cast<CallInst>(Inst);
1900 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1901 Value *Arg = Call->getArgOperand(0);
1902 Value *EarlierArg = EarlierCall->getArgOperand(0);
1903 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001904 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001905 Changed = true;
1906 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001907 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001908 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001909 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001910 CI->setTailCall();
1911 }
1912 // Zap the fully redundant load.
1913 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1914 Call->eraseFromParent();
1915 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001916 case MayAlias:
1917 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001918 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001919 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001920 break;
1921 }
1922 break;
1923 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001924 case ARCInstKind::MoveWeak:
1925 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001926 // TOOD: Grab the copied value.
1927 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001928 case ARCInstKind::AutoreleasepoolPush:
1929 case ARCInstKind::None:
1930 case ARCInstKind::IntrinsicUser:
1931 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001932 // Weak pointers are only modified through the weak entry points
1933 // (and arbitrary calls, which could call the weak entry points).
1934 break;
1935 default:
1936 // Anything else could modify the weak pointer.
1937 goto clobbered;
1938 }
1939 }
1940 clobbered:;
1941 }
1942
1943 // Then, for each destroyWeak with an alloca operand, check to see if
1944 // the alloca and all its users can be zapped.
1945 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1946 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001947 ARCInstKind Class = GetBasicARCInstKind(Inst);
1948 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001949 continue;
1950
1951 CallInst *Call = cast<CallInst>(Inst);
1952 Value *Arg = Call->getArgOperand(0);
1953 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001954 for (User *U : Alloca->users()) {
1955 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001956 switch (GetBasicARCInstKind(UserInst)) {
1957 case ARCInstKind::InitWeak:
1958 case ARCInstKind::StoreWeak:
1959 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001960 continue;
1961 default:
1962 goto done;
1963 }
1964 }
1965 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001966 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001967 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001968 switch (GetBasicARCInstKind(UserInst)) {
1969 case ARCInstKind::InitWeak:
1970 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001971 // These functions return their second argument.
1972 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1973 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001974 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001975 // No return value.
1976 break;
1977 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001978 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001979 }
John McCalld935e9c2011-06-15 23:37:01 +00001980 UserInst->eraseFromParent();
1981 }
1982 Alloca->eraseFromParent();
1983 done:;
1984 }
1985 }
1986}
1987
Michael Gottesman97e3df02013-01-14 00:35:14 +00001988/// Identify program paths which execute sequences of retains and releases which
1989/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001990bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001991 // Releases, Retains - These are used to store the results of the main flow
1992 // analysis. These use Value* as the key instead of Instruction* so that the
1993 // map stays valid when we get around to rewriting code and calls get
1994 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00001995 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00001996 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00001997
Michael Gottesman740db972013-05-23 02:35:21 +00001998 // This is used during the traversal of the function to track the
1999 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002000 DenseMap<const BasicBlock *, BBState> BBStates;
2001
2002 // Analyze the CFG of the function, and all instructions.
2003 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2004
2005 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002006 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2007 Releases,
2008 F.getParent());
2009
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002010 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002011}
2012
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002013/// Check if there is a dependent call earlier that does not have anything in
2014/// between the Retain and the call that can affect the reference count of their
2015/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002016static bool
2017HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00002018 SmallPtrSetImpl<Instruction *> &DepInsts,
2019 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002020 ProvenanceAnalysis &PA) {
2021 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2022 DepInsts, Visited, PA);
2023 if (DepInsts.size() != 1)
2024 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002025
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002026 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002027
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002028 // Check that the pointer is the return value of the call.
2029 if (!Call || Arg != Call)
2030 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002031
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002032 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002033 ARCInstKind Class = GetBasicARCInstKind(Call);
Alexander Kornienkod0af3b32015-12-28 16:19:08 +00002034 return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call;
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002035}
2036
Michael Gottesman6908db12013-04-03 23:16:05 +00002037/// Find a dependent retain that precedes the given autorelease for which there
2038/// is nothing in between the two instructions that can affect the ref count of
2039/// Arg.
2040static CallInst *
2041FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2042 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002043 SmallPtrSetImpl<Instruction *> &DepInsts,
2044 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002045 ProvenanceAnalysis &PA) {
2046 FindDependencies(CanChangeRetainCount, Arg,
2047 BB, Autorelease, DepInsts, Visited, PA);
2048 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002049 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002050
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002051 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002052
Michael Gottesman6908db12013-04-03 23:16:05 +00002053 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002054 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002055 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002056 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002057 }
Michael Gottesman79249972013-04-05 23:46:45 +00002058
Michael Gottesman6908db12013-04-03 23:16:05 +00002059 return Retain;
2060}
2061
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002062/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2063/// no instructions dependent on Arg that need a positive ref count in between
2064/// the autorelease and the ret.
2065static CallInst *
2066FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2067 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002068 SmallPtrSetImpl<Instruction *> &DepInsts,
2069 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002070 ProvenanceAnalysis &PA) {
2071 FindDependencies(NeedsPositiveRetainCount, Arg,
2072 BB, Ret, DepInsts, V, PA);
2073 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002074 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002075
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002076 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002077 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002078 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002079 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002080 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002081 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002082 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002083 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002084
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002085 return Autorelease;
2086}
2087
Michael Gottesman97e3df02013-01-14 00:35:14 +00002088/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002089/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002090/// %call = call i8* @something(...)
2091/// %2 = call i8* @objc_retain(i8* %call)
2092/// %3 = call i8* @objc_autorelease(i8* %2)
2093/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002094/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002095/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002096void ObjCARCOpt::OptimizeReturns(Function &F) {
2097 if (!F.getReturnType()->isPointerTy())
2098 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002099
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002100 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002101
John McCalld935e9c2011-06-15 23:37:01 +00002102 SmallPtrSet<Instruction *, 4> DependingInstructions;
2103 SmallPtrSet<const BasicBlock *, 4> Visited;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002104 for (BasicBlock &BB: F) {
2105 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002106 if (!Ret)
2107 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002108
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002109 LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Chandler Carruthd9ef4b62016-11-04 06:59:50 +00002110
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002111 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002112
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002113 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002114 // dependent on Arg such that there are no instructions dependent on Arg
2115 // that need a positive ref count in between the autorelease and Ret.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002116 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath(
2117 Arg, &BB, Ret, DependingInstructions, Visited, PA);
John McCalld935e9c2011-06-15 23:37:01 +00002118 DependingInstructions.clear();
2119 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002120
2121 if (!Autorelease)
2122 continue;
2123
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002124 CallInst *Retain = FindPredecessorRetainWithSafePath(
Akira Hatanaka13d2beb2017-08-31 18:27:47 +00002125 Arg, Autorelease->getParent(), Autorelease, DependingInstructions,
2126 Visited, PA);
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002127 DependingInstructions.clear();
2128 Visited.clear();
2129
2130 if (!Retain)
2131 continue;
2132
2133 // Check that there is nothing that can affect the reference count
2134 // between the retain and the call. Note that Retain need not be in BB.
2135 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2136 DependingInstructions,
2137 Visited, PA);
2138 DependingInstructions.clear();
2139 Visited.clear();
2140
2141 if (!HasSafePathToCall)
2142 continue;
2143
2144 // If so, we can zap the retain and autorelease.
2145 Changed = true;
2146 ++NumRets;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002147 LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease
2148 << "\n");
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002149 EraseInstruction(Retain);
2150 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002151 }
2152}
2153
Michael Gottesman9c118152013-04-29 06:16:57 +00002154#ifndef NDEBUG
2155void
2156ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00002157 Statistic &NumRetains =
2158 AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2159 Statistic &NumReleases =
2160 AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt;
Michael Gottesman9c118152013-04-29 06:16:57 +00002161
2162 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2163 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002164 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002165 default:
2166 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002167 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002168 ++NumRetains;
2169 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002170 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002171 ++NumReleases;
2172 break;
2173 }
2174 }
2175}
2176#endif
2177
John McCalld935e9c2011-06-15 23:37:01 +00002178bool ObjCARCOpt::doInitialization(Module &M) {
2179 if (!EnableARCOpts)
2180 return false;
2181
Dan Gohman670f9372012-04-13 18:57:48 +00002182 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002183 Run = ModuleHasARC(M);
2184 if (!Run)
2185 return false;
2186
John McCalld935e9c2011-06-15 23:37:01 +00002187 // Intuitively, objc_retain and others are nocapture, however in practice
2188 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002189 // calls finalizers which can have arbitrary side effects.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002190 MDKindCache.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002191
Michael Gottesman14acfac2013-07-06 01:39:23 +00002192 // Initialize our runtime entry point cache.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002193 EP.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002194
2195 return false;
2196}
2197
2198bool ObjCARCOpt::runOnFunction(Function &F) {
2199 if (!EnableARCOpts)
2200 return false;
2201
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002202 // If nothing in the Module uses ARC, don't do anything.
2203 if (!Run)
2204 return false;
2205
John McCalld935e9c2011-06-15 23:37:01 +00002206 Changed = false;
2207
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002208 LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName()
2209 << " >>>"
2210 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002211
Chandler Carruth7b560d42015-09-09 17:55:00 +00002212 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
John McCalld935e9c2011-06-15 23:37:01 +00002213
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002214#ifndef NDEBUG
2215 if (AreStatisticsEnabled()) {
2216 GatherStatistics(F, false);
2217 }
2218#endif
2219
John McCalld935e9c2011-06-15 23:37:01 +00002220 // This pass performs several distinct transformations. As a compile-time aid
2221 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2222 // library functions aren't declared.
2223
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002224 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002225 OptimizeIndividualCalls(F);
2226
2227 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002228 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2229 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2230 (1 << unsigned(ARCInstKind::StoreWeak)) |
2231 (1 << unsigned(ARCInstKind::InitWeak)) |
2232 (1 << unsigned(ARCInstKind::CopyWeak)) |
2233 (1 << unsigned(ARCInstKind::MoveWeak)) |
2234 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002235 OptimizeWeakCalls(F);
2236
2237 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002238 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2239 (1 << unsigned(ARCInstKind::RetainRV)) |
2240 (1 << unsigned(ARCInstKind::RetainBlock))))
2241 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002242 // Run OptimizeSequences until it either stops making changes or
2243 // no retain+release pair nesting is detected.
2244 while (OptimizeSequences(F)) {}
2245
2246 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002247 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2248 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002249 OptimizeReturns(F);
2250
Michael Gottesman9c118152013-04-29 06:16:57 +00002251 // Gather statistics after optimization.
2252#ifndef NDEBUG
2253 if (AreStatisticsEnabled()) {
2254 GatherStatistics(F, true);
2255 }
2256#endif
2257
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002258 LLVM_DEBUG(dbgs() << "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002259
John McCalld935e9c2011-06-15 23:37:01 +00002260 return Changed;
2261}
2262
2263void ObjCARCOpt::releaseMemory() {
2264 PA.clear();
2265}
2266
Michael Gottesman97e3df02013-01-14 00:35:14 +00002267/// @}
2268///