blob: 2c3f295cabe6cfe491a03cea4c2e05da4bd337ff [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#include "ObjCARC.h"
Michael Gottesman14acfac2013-07-06 01:39:23 +000028#include "ARCRuntimeEntryPoints.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "BlotMapVector.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000030#include "DependencyAnalysis.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"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000034#include "llvm/ADT/DenseSet.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"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/ADT/Statistic.h"
Chandler Carruth0f792182015-08-20 08:06:03 +000038#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000039#include "llvm/IR/CFG.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000040#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000041#include "llvm/IR/LLVMContext.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000042#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000043#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000044
John McCalld935e9c2011-06-15 23:37:01 +000045using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000046using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000047
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "objc-arc-opts"
49
Michael Gottesman97e3df02013-01-14 00:35:14 +000050/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
51/// @{
John McCalld935e9c2011-06-15 23:37:01 +000052
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000053/// \brief This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000054/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000055static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56 if (Arg->hasOneUse()) {
57 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58 return FindSingleUseIdentifiedObject(BC->getOperand(0));
59 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60 if (GEP->hasAllZeroIndices())
61 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000062 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000063 return FindSingleUseIdentifiedObject(
64 cast<CallInst>(Arg)->getArgOperand(0));
65 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000066 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000067 return Arg;
68 }
69
Dan Gohman41375a32012-05-08 23:39:44 +000070 // If we found an identifiable object but it has multiple uses, but they are
71 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +000072 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000073 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000074 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +000075 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000076
77 return Arg;
78 }
79
Craig Topperf40110f2014-04-25 05:29:35 +000080 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000081}
82
Michael Gottesmana76143ee2013-05-13 23:49:42 +000083/// This is a wrapper around getUnderlyingObjCPtr along the lines of
84/// GetUnderlyingObjects except that it returns early when it sees the first
85/// alloca.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000086static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V,
87 const DataLayout &DL) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +000088 SmallPtrSet<const Value *, 4> Visited;
89 SmallVector<const Value *, 4> Worklist;
90 Worklist.push_back(V);
91 do {
92 const Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +000093 P = GetUnderlyingObjCPtr(P, DL);
Michael Gottesman0c8b5622013-05-14 06:40:10 +000094
Michael Gottesmana76143ee2013-05-13 23:49:42 +000095 if (isa<AllocaInst>(P))
96 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000097
David Blaikie70573dc2014-11-19 07:49:26 +000098 if (!Visited.insert(P).second)
Michael Gottesmana76143ee2013-05-13 23:49:42 +000099 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000100
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000101 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
102 Worklist.push_back(SI->getTrueValue());
103 Worklist.push_back(SI->getFalseValue());
104 continue;
105 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000106
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000107 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000108 for (Value *IncValue : PN->incoming_values())
109 Worklist.push_back(IncValue);
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000110 continue;
111 }
112 } while (!Worklist.empty());
113
114 return false;
115}
116
117
Michael Gottesman97e3df02013-01-14 00:35:14 +0000118/// @}
119///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000120/// \defgroup ARCOpt ARC Optimization.
121/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000122
123// TODO: On code like this:
124//
125// objc_retain(%x)
126// stuff_that_cannot_release()
127// objc_autorelease(%x)
128// stuff_that_cannot_release()
129// objc_retain(%x)
130// stuff_that_cannot_release()
131// objc_autorelease(%x)
132//
133// The second retain and autorelease can be deleted.
134
135// TODO: It should be possible to delete
136// objc_autoreleasePoolPush and objc_autoreleasePoolPop
137// pairs if nothing is actually autoreleased between them. Also, autorelease
138// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
139// after inlining) can be turned into plain release calls.
140
141// TODO: Critical-edge splitting. If the optimial insertion point is
142// a critical edge, the current algorithm has to fail, because it doesn't
143// know how to split edges. It should be possible to make the optimizer
144// think in terms of edges, rather than blocks, and then split critical
145// edges on demand.
146
147// TODO: OptimizeSequences could generalized to be Interprocedural.
148
149// TODO: Recognize that a bunch of other objc runtime calls have
150// non-escaping arguments and non-releasing arguments, and may be
151// non-autoreleasing.
152
153// TODO: Sink autorelease calls as far as possible. Unfortunately we
154// usually can't sink them past other calls, which would be the main
155// case where it would be useful.
156
Dan Gohmanb3894012011-08-19 00:26:36 +0000157// TODO: The pointer returned from objc_loadWeakRetained is retained.
158
159// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000160
John McCalld935e9c2011-06-15 23:37:01 +0000161STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
162STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
163STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
164STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000165 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000166STATISTIC(NumRRs, "Number of retain+release paths eliminated");
167STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000168#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000169STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000170 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000171STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000172 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000173STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000174 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000175STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000176 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000177#endif
John McCalld935e9c2011-06-15 23:37:01 +0000178
179namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000180 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000181 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000182 /// The number of unique control paths from the entry which can reach this
183 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000184 unsigned TopDownPathCount;
185
Michael Gottesman97e3df02013-01-14 00:35:14 +0000186 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000187 unsigned BottomUpPathCount;
188
Michael Gottesman97e3df02013-01-14 00:35:14 +0000189 /// The top-down traversal uses this to record information known about a
190 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000191 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000192
Michael Gottesman97e3df02013-01-14 00:35:14 +0000193 /// The bottom-up traversal uses this to record information known about a
194 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000195 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000196
Michael Gottesman97e3df02013-01-14 00:35:14 +0000197 /// Effective predecessors of the current block ignoring ignorable edges and
198 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000199 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000200
Michael Gottesman97e3df02013-01-14 00:35:14 +0000201 /// Effective successors of the current block ignoring ignorable edges and
202 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000203 SmallVector<BasicBlock *, 2> Succs;
204
John McCalld935e9c2011-06-15 23:37:01 +0000205 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000206 static const unsigned OverflowOccurredValue;
207
208 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000209
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000210 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
211 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000212
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000213 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
214 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
215 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000216 return PerPtrTopDown.begin();
217 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000218 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000219 return PerPtrTopDown.end();
220 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000221 bool hasTopDownPtrs() const {
222 return !PerPtrTopDown.empty();
223 }
John McCalld935e9c2011-06-15 23:37:01 +0000224
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000225 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
226 typedef decltype(
227 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
228
229 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000230 return PerPtrBottomUp.begin();
231 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000232 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
233 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
234 return PerPtrBottomUp.begin();
235 }
236 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000237 return PerPtrBottomUp.end();
238 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000239 bool hasBottomUpPtrs() const {
240 return !PerPtrBottomUp.empty();
241 }
John McCalld935e9c2011-06-15 23:37:01 +0000242
Michael Gottesman97e3df02013-01-14 00:35:14 +0000243 /// Mark this block as being an entry block, which has one path from the
244 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000245 void SetAsEntry() { TopDownPathCount = 1; }
246
Michael Gottesman97e3df02013-01-14 00:35:14 +0000247 /// Mark this block as being an exit block, which has one path to an exit by
248 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000249 void SetAsExit() { BottomUpPathCount = 1; }
250
Michael Gottesman993fbf72013-05-13 19:40:39 +0000251 /// Attempt to find the PtrState object describing the top down state for
252 /// pointer Arg. Return a new initialized PtrState describing the top down
253 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000254 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000255 return PerPtrTopDown[Arg];
256 }
257
Michael Gottesman993fbf72013-05-13 19:40:39 +0000258 /// Attempt to find the PtrState object describing the bottom up state for
259 /// pointer Arg. Return a new initialized PtrState describing the bottom up
260 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000261 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000262 return PerPtrBottomUp[Arg];
263 }
264
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000265 /// Attempt to find the PtrState object describing the bottom up state for
266 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000267 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000268 return PerPtrBottomUp.find(Arg);
269 }
270
John McCalld935e9c2011-06-15 23:37:01 +0000271 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000272 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000273 }
274
275 void clearTopDownPointers() {
276 PerPtrTopDown.clear();
277 }
278
279 void InitFromPred(const BBState &Other);
280 void InitFromSucc(const BBState &Other);
281 void MergePred(const BBState &Other);
282 void MergeSucc(const BBState &Other);
283
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000284 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000285 /// which pass through this block. This is only valid after both the
286 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000287 ///
Alp Tokercb402912014-01-24 17:20:08 +0000288 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000289 /// occur.
290 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000291 if (TopDownPathCount == OverflowOccurredValue ||
292 BottomUpPathCount == OverflowOccurredValue)
293 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000294 unsigned long long Product =
295 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000296 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000297 // the lower bits of Product are all set.
298 return (Product >> 32) ||
299 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000300 }
Dan Gohman12130272011-08-12 00:26:31 +0000301
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000302 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000303 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000304 edge_iterator pred_begin() const { return Preds.begin(); }
305 edge_iterator pred_end() const { return Preds.end(); }
306 edge_iterator succ_begin() const { return Succs.begin(); }
307 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000308
309 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
310 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
311
312 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000313 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000314
315 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000316}
John McCalld935e9c2011-06-15 23:37:01 +0000317
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000318namespace llvm {
Michael Gottesmand63436f2015-03-16 08:00:27 +0000319raw_ostream &operator<<(raw_ostream &OS,
320 BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000321}
322
John McCalld935e9c2011-06-15 23:37:01 +0000323void BBState::InitFromPred(const BBState &Other) {
324 PerPtrTopDown = Other.PerPtrTopDown;
325 TopDownPathCount = Other.TopDownPathCount;
326}
327
328void BBState::InitFromSucc(const BBState &Other) {
329 PerPtrBottomUp = Other.PerPtrBottomUp;
330 BottomUpPathCount = Other.BottomUpPathCount;
331}
332
Michael Gottesman97e3df02013-01-14 00:35:14 +0000333/// The top-down traversal uses this to merge information about predecessors to
334/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000335void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000336 if (TopDownPathCount == OverflowOccurredValue)
337 return;
338
John McCalld935e9c2011-06-15 23:37:01 +0000339 // Other.TopDownPathCount can be 0, in which case it is either dead or a
340 // loop backedge. Loop backedges are special.
341 TopDownPathCount += Other.TopDownPathCount;
342
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000343 // In order to be consistent, we clear the top down pointers when by adding
344 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000345 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000346 if (TopDownPathCount == OverflowOccurredValue) {
347 clearTopDownPointers();
348 return;
349 }
350
Michael Gottesman4385edf2013-01-14 01:47:53 +0000351 // Check for overflow. If we have overflow, fall back to conservative
352 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000353 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000354 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000355 clearTopDownPointers();
356 return;
357 }
358
John McCalld935e9c2011-06-15 23:37:01 +0000359 // For each entry in the other set, if our set has an entry with the same key,
360 // merge the entries. Otherwise, copy the entry and merge it with an empty
361 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000362 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
363 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000364 auto Pair = PerPtrTopDown.insert(*MI);
365 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000366 /*TopDown=*/true);
367 }
368
Dan Gohman7e315fc32011-08-11 21:06:32 +0000369 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000370 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000371 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000372 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000373 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000374}
375
Michael Gottesman97e3df02013-01-14 00:35:14 +0000376/// The bottom-up traversal uses this to merge information about successors to
377/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000378void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000379 if (BottomUpPathCount == OverflowOccurredValue)
380 return;
381
John McCalld935e9c2011-06-15 23:37:01 +0000382 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
383 // loop backedge. Loop backedges are special.
384 BottomUpPathCount += Other.BottomUpPathCount;
385
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000386 // In order to be consistent, we clear the top down pointers when by adding
387 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000388 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000389 if (BottomUpPathCount == OverflowOccurredValue) {
390 clearBottomUpPointers();
391 return;
392 }
393
Michael Gottesman4385edf2013-01-14 01:47:53 +0000394 // Check for overflow. If we have overflow, fall back to conservative
395 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000396 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000397 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000398 clearBottomUpPointers();
399 return;
400 }
401
John McCalld935e9c2011-06-15 23:37:01 +0000402 // For each entry in the other set, if our set has an entry with the
403 // same key, merge the entries. Otherwise, copy the entry and merge
404 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000405 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
406 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000407 auto Pair = PerPtrBottomUp.insert(*MI);
408 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000409 /*TopDown=*/false);
410 }
411
Dan Gohman7e315fc32011-08-11 21:06:32 +0000412 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000413 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000414 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
415 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000416 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000417 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000418}
419
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000420raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
421 // Dump the pointers we are tracking.
422 OS << " TopDown State:\n";
423 if (!BBInfo.hasTopDownPtrs()) {
424 DEBUG(llvm::dbgs() << " NONE!\n");
425 } else {
426 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
427 I != E; ++I) {
428 const PtrState &P = I->second;
429 OS << " Ptr: " << *I->first
430 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
431 << "\n ImpreciseRelease: "
432 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
433 << " HasCFGHazards: "
434 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
435 << " KnownPositive: "
436 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
437 << " Seq: "
438 << P.GetSeq() << "\n";
439 }
440 }
441
442 OS << " BottomUp State:\n";
443 if (!BBInfo.hasBottomUpPtrs()) {
444 DEBUG(llvm::dbgs() << " NONE!\n");
445 } else {
446 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
447 I != E; ++I) {
448 const PtrState &P = I->second;
449 OS << " Ptr: " << *I->first
450 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
451 << "\n ImpreciseRelease: "
452 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
453 << " HasCFGHazards: "
454 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
455 << " KnownPositive: "
456 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
457 << " Seq: "
458 << P.GetSeq() << "\n";
459 }
460 }
461
462 return OS;
463}
464
John McCalld935e9c2011-06-15 23:37:01 +0000465namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000466
Michael Gottesman97e3df02013-01-14 00:35:14 +0000467 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000468 class ObjCARCOpt : public FunctionPass {
469 bool Changed;
470 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000471
472 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000473 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000474
Michael Gottesman41c01002015-03-06 00:34:33 +0000475 /// A cache of MDKinds that can be passed into other functions to propagate
476 /// MDKind identifiers.
477 ARCMDKindCache MDKindCache;
478
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000479 // This is used to track if a pointer is stored into an alloca.
480 DenseSet<const Value *> MultiOwnersSet;
481
Michael Gottesman97e3df02013-01-14 00:35:14 +0000482 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000483 bool Run;
484
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000485 /// Flags which determine whether each of the interesting runtime functions
Michael Gottesman97e3df02013-01-14 00:35:14 +0000486 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000487 unsigned UsedInThisFunction;
488
John McCalld935e9c2011-06-15 23:37:01 +0000489 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000490 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000491 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000492 void OptimizeIndividualCalls(Function &F);
493
494 void CheckForCFGHazards(const BasicBlock *BB,
495 DenseMap<const BasicBlock *, BBState> &BBStates,
496 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000497 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
498 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000499 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000500 bool VisitBottomUp(BasicBlock *BB,
501 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000502 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000503 bool VisitInstructionTopDown(Instruction *Inst,
504 DenseMap<Value *, RRInfo> &Releases,
505 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000506 bool VisitTopDown(BasicBlock *BB,
507 DenseMap<const BasicBlock *, BBState> &BBStates,
508 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000509 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
510 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000511 DenseMap<Value *, RRInfo> &Releases);
512
513 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000514 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000515 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000516 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000517
Michael Gottesman67792172015-03-16 07:02:30 +0000518 bool
519 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
520 BlotMapVector<Value *, RRInfo> &Retains,
521 DenseMap<Value *, RRInfo> &Releases, Module *M,
522 SmallVectorImpl<Instruction *> &NewRetains,
523 SmallVectorImpl<Instruction *> &NewReleases,
524 SmallVectorImpl<Instruction *> &DeadInsts,
525 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
526 Value *Arg, bool KnownSafe,
527 bool &AnyPairsCompletelyEliminated);
Michael Gottesman9de6f962013-01-22 21:49:00 +0000528
John McCalld935e9c2011-06-15 23:37:01 +0000529 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000530 BlotMapVector<Value *, RRInfo> &Retains,
531 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000532
533 void OptimizeWeakCalls(Function &F);
534
535 bool OptimizeSequences(Function &F);
536
537 void OptimizeReturns(Function &F);
538
Michael Gottesman9c118152013-04-29 06:16:57 +0000539#ifndef NDEBUG
540 void GatherStatistics(Function &F, bool AfterOptimization = false);
541#endif
542
Craig Topper3e4c6972014-03-05 09:10:37 +0000543 void getAnalysisUsage(AnalysisUsage &AU) const override;
544 bool doInitialization(Module &M) override;
545 bool runOnFunction(Function &F) override;
546 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000547
548 public:
549 static char ID;
550 ObjCARCOpt() : FunctionPass(ID) {
551 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
552 }
553 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000554}
John McCalld935e9c2011-06-15 23:37:01 +0000555
556char ObjCARCOpt::ID = 0;
557INITIALIZE_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
602 // Check for being preceded by an objc_autoreleaseReturnValue on the same
603 // pointer. In this case, we can delete the pair.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000604 BasicBlock::iterator I = RetainRV->getIterator(),
605 Begin = RetainRV->getParent()->begin();
John McCalld935e9c2011-06-15 23:37:01 +0000606 if (I != Begin) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000607 do
608 --I;
609 while (I != Begin && IsNoopInstruction(&*I));
610 if (GetBasicARCInstKind(&*I) == ARCInstKind::AutoreleaseRV &&
611 GetArgRCIdentityRoot(&*I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000612 Changed = true;
613 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000614
Michael Gottesman89279f82013-04-05 18:10:41 +0000615 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
616 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000617
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000618 EraseInstruction(&*I);
John McCalld935e9c2011-06-15 23:37:01 +0000619 EraseInstruction(RetainRV);
620 return true;
621 }
622 }
623
624 // Turn it to a plain objc_retain.
625 Changed = true;
626 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000627
Michael Gottesman89279f82013-04-05 18:10:41 +0000628 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000629 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000630 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000631
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000632 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000633 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000634
Michael Gottesman89279f82013-04-05 18:10:41 +0000635 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000636
John McCalld935e9c2011-06-15 23:37:01 +0000637 return false;
638}
639
Michael Gottesman97e3df02013-01-14 00:35:14 +0000640/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
641/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000642void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
643 Instruction *AutoreleaseRV,
644 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000645 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000646 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +0000647 SmallVector<const Value *, 2> Users;
648 Users.push_back(Ptr);
649 do {
650 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000651 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000652 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000653 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000654 if (isa<BitCastInst>(U))
655 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000656 }
657 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000658
659 Changed = true;
660 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000661
Michael Gottesman89279f82013-04-05 18:10:41 +0000662 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000663 "objc_autorelease since its operand is not used as a return "
664 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000665 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000666
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000667 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000668 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000669 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000670 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000671 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000672
Michael Gottesman89279f82013-04-05 18:10:41 +0000673 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000674
John McCalld935e9c2011-06-15 23:37:01 +0000675}
676
Michael Gottesman97e3df02013-01-14 00:35:14 +0000677/// Visit each call, one at a time, and make simplifications without doing any
678/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000679void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000680 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000681 // Reset all the flags in preparation for recomputing them.
682 UsedInThisFunction = 0;
683
684 // Visit all objc_* calls in F.
685 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
686 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000687
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000688 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000689
Michael Gottesman89279f82013-04-05 18:10:41 +0000690 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000691
John McCalld935e9c2011-06-15 23:37:01 +0000692 switch (Class) {
693 default: break;
694
695 // Delete no-op casts. These function calls have special semantics, but
696 // the semantics are entirely implemented via lowering in the front-end,
697 // so by the time they reach the optimizer, they are just no-op calls
698 // which return their argument.
699 //
700 // There are gray areas here, as the ability to cast reference-counted
701 // pointers to raw void* and back allows code to break ARC assumptions,
702 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000703 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000704 Changed = true;
705 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000706 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000707 EraseInstruction(Inst);
708 continue;
709
710 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000711 case ARCInstKind::StoreWeak:
712 case ARCInstKind::LoadWeak:
713 case ARCInstKind::LoadWeakRetained:
714 case ARCInstKind::InitWeak:
715 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000716 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000717 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000718 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000719 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000720 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
721 Constant::getNullValue(Ty),
722 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000723 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000724 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
725 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000726 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000727 CI->eraseFromParent();
728 continue;
729 }
730 break;
731 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000732 case ARCInstKind::CopyWeak:
733 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000734 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000735 if (IsNullOrUndef(CI->getArgOperand(0)) ||
736 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000737 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000738 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000739 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
740 Constant::getNullValue(Ty),
741 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000742
743 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000744 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
745 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000746
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000747 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000748 CI->eraseFromParent();
749 continue;
750 }
751 break;
752 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000753 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000754 if (OptimizeRetainRVCall(F, Inst))
755 continue;
756 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000757 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000758 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000759 break;
760 }
761
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000762 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000763 if (IsAutorelease(Class) && Inst->use_empty()) {
764 CallInst *Call = cast<CallInst>(Inst);
765 const Value *Arg = Call->getArgOperand(0);
766 Arg = FindSingleUseIdentifiedObject(Arg);
767 if (Arg) {
768 Changed = true;
769 ++NumAutoreleases;
770
771 // Create the declaration lazily.
772 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000773
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000774 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000775 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
776 Call);
Michael Gottesman65cb7372015-03-16 07:02:27 +0000777 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
Michael Gottesman41c01002015-03-06 00:34:33 +0000778 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000779
Michael Gottesman89279f82013-04-05 18:10:41 +0000780 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
781 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
782 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000783
John McCalld935e9c2011-06-15 23:37:01 +0000784 EraseInstruction(Call);
785 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000786 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000787 }
788 }
789
790 // For functions which can never be passed stack arguments, add
791 // a tail keyword.
792 if (IsAlwaysTail(Class)) {
793 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000794 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
795 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000796 cast<CallInst>(Inst)->setTailCall();
797 }
798
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000799 // Ensure that functions that can never have a "tail" keyword due to the
800 // semantics of ARC truly do not do so.
801 if (IsNeverTail(Class)) {
802 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000803 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000804 "\n");
805 cast<CallInst>(Inst)->setTailCall(false);
806 }
807
John McCalld935e9c2011-06-15 23:37:01 +0000808 // Set nounwind as needed.
809 if (IsNoThrow(Class)) {
810 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000811 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
812 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000813 cast<CallInst>(Inst)->setDoesNotThrow();
814 }
815
816 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000817 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000818 continue;
819 }
820
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000821 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000822
823 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000824 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000825 Changed = true;
826 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000827 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
828 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000829 EraseInstruction(Inst);
830 continue;
831 }
832
833 // Keep track of which of retain, release, autorelease, and retain_block
834 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000835 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000836
837 // If Arg is a PHI, and one or more incoming values to the
838 // PHI are null, and the call is control-equivalent to the PHI, and there
839 // are no relevant side effects between the PHI and the call, the call
840 // could be pushed up to just those paths with non-null incoming values.
841 // For now, don't bother splitting critical edges for this.
842 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
843 Worklist.push_back(std::make_pair(Inst, Arg));
844 do {
845 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
846 Inst = Pair.first;
847 Arg = Pair.second;
848
849 const PHINode *PN = dyn_cast<PHINode>(Arg);
850 if (!PN) continue;
851
852 // Determine if the PHI has any null operands, or any incoming
853 // critical edges.
854 bool HasNull = false;
855 bool HasCriticalEdges = false;
856 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
857 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000858 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000859 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000860 HasNull = true;
861 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
862 .getNumSuccessors() != 1) {
863 HasCriticalEdges = true;
864 break;
865 }
866 }
867 // If we have null operands and no critical edges, optimize.
868 if (!HasCriticalEdges && HasNull) {
869 SmallPtrSet<Instruction *, 4> DependingInstructions;
870 SmallPtrSet<const BasicBlock *, 4> Visited;
871
872 // Check that there is nothing that cares about the reference
873 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000874 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000875 case ARCInstKind::Retain:
876 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000877 // These can always be moved up.
878 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000879 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000880 // These can't be moved across things that care about the retain
881 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000882 FindDependencies(NeedsPositiveRetainCount, Arg,
883 Inst->getParent(), Inst,
884 DependingInstructions, Visited, PA);
885 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000886 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000887 // These can't be moved across autorelease pool scope boundaries.
888 FindDependencies(AutoreleasePoolBoundary, Arg,
889 Inst->getParent(), Inst,
890 DependingInstructions, Visited, PA);
891 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000892 case ARCInstKind::RetainRV:
893 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000894 // Don't move these; the RV optimization depends on the autoreleaseRV
895 // being tail called, and the retainRV being immediately after a call
896 // (which might still happen if we get lucky with codegen layout, but
897 // it's not worth taking the chance).
898 continue;
899 default:
900 llvm_unreachable("Invalid dependence flavor");
901 }
902
John McCalld935e9c2011-06-15 23:37:01 +0000903 if (DependingInstructions.size() == 1 &&
904 *DependingInstructions.begin() == PN) {
905 Changed = true;
906 ++NumPartialNoops;
907 // Clone the call into each predecessor that has a non-null value.
908 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000909 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000910 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
911 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000912 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000913 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000914 CallInst *Clone = cast<CallInst>(CInst->clone());
915 Value *Op = PN->getIncomingValue(i);
916 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
917 if (Op->getType() != ParamTy)
918 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
919 Clone->setArgOperand(0, Op);
920 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000921
Michael Gottesman89279f82013-04-05 18:10:41 +0000922 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +0000923 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000924 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000925 Worklist.push_back(std::make_pair(Clone, Incoming));
926 }
927 }
928 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +0000929 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000930 EraseInstruction(CInst);
931 continue;
932 }
933 }
934 } while (!Worklist.empty());
935 }
936}
937
Michael Gottesman323964c2013-04-18 05:39:45 +0000938/// If we have a top down pointer in the S_Use state, make sure that there are
939/// no CFG hazards by checking the states of various bottom up pointers.
940static void CheckForUseCFGHazard(const Sequence SuccSSeq,
941 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000942 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000943 bool &SomeSuccHasSame,
944 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000945 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +0000946 bool &ShouldContinue) {
947 switch (SuccSSeq) {
948 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +0000949 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000950 S.ClearSequenceProgress();
951 break;
952 }
Michael Gottesman2f294592013-06-21 19:12:36 +0000953 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +0000954 ShouldContinue = true;
955 break;
956 }
957 case S_Use:
958 SomeSuccHasSame = true;
959 break;
960 case S_Stop:
961 case S_Release:
962 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +0000963 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000964 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000965 else
966 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000967 break;
968 case S_Retain:
969 llvm_unreachable("bottom-up pointer in retain state!");
970 case S_None:
971 llvm_unreachable("This should have been handled earlier.");
972 }
973}
974
975/// If we have a Top Down pointer in the S_CanRelease state, make sure that
976/// there are no CFG hazards by checking the states of various bottom up
977/// pointers.
978static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
979 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000980 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000981 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000982 bool &AllSuccsHaveSame,
983 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000984 switch (SuccSSeq) {
985 case S_CanRelease:
986 SomeSuccHasSame = true;
987 break;
988 case S_Stop:
989 case S_Release:
990 case S_MovableRelease:
991 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +0000992 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000993 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000994 else
995 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000996 break;
997 case S_Retain:
998 llvm_unreachable("bottom-up pointer in retain state!");
999 case S_None:
1000 llvm_unreachable("This should have been handled earlier.");
1001 }
1002}
1003
Michael Gottesman97e3df02013-01-14 00:35:14 +00001004/// Check for critical edges, loop boundaries, irreducible control flow, or
1005/// other CFG structures where moving code across the edge would result in it
1006/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001007void
1008ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1009 DenseMap<const BasicBlock *, BBState> &BBStates,
1010 BBState &MyStates) const {
1011 // If any top-down local-use or possible-dec has a succ which is earlier in
1012 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001013 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
1014 I != E; ++I) {
1015 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +00001016 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001017
Michael Gottesman323964c2013-04-18 05:39:45 +00001018 // We only care about S_Retain, S_CanRelease, and S_Use.
1019 if (Seq == S_None)
1020 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001021
Michael Gottesman323964c2013-04-18 05:39:45 +00001022 // Make sure that if extra top down states are added in the future that this
1023 // code is updated to handle it.
1024 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1025 "Unknown top down sequence state.");
1026
1027 const Value *Arg = I->first;
1028 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1029 bool SomeSuccHasSame = false;
1030 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001031 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001032
1033 succ_const_iterator SI(TI), SE(TI, false);
1034
1035 for (; SI != SE; ++SI) {
1036 // If VisitBottomUp has pointer information for this successor, take
1037 // what we know about it.
1038 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1039 BBStates.find(*SI);
1040 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001041 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +00001042 const Sequence SuccSSeq = SuccS.GetSeq();
1043
1044 // If bottom up, the pointer is in an S_None state, clear the sequence
1045 // progress since the sequence in the bottom up state finished
1046 // suggesting a mismatch in between retains/releases. This is true for
1047 // all three cases that we are handling here: S_Retain, S_Use, and
1048 // S_CanRelease.
1049 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001050 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001051 continue;
1052 }
1053
1054 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1055 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001056 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001057
1058 // *NOTE* We do not use Seq from above here since we are allowing for
1059 // S.GetSeq() to change while we are visiting basic blocks.
1060 switch(S.GetSeq()) {
1061 case S_Use: {
1062 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001063 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1064 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001065 ShouldContinue);
1066 if (ShouldContinue)
1067 continue;
1068 break;
1069 }
1070 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001071 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1072 SomeSuccHasSame, AllSuccsHaveSame,
1073 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001074 break;
1075 }
1076 case S_Retain:
1077 case S_None:
1078 case S_Stop:
1079 case S_Release:
1080 case S_MovableRelease:
1081 break;
1082 }
John McCalld935e9c2011-06-15 23:37:01 +00001083 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001084
1085 // If the state at the other end of any of the successor edges
1086 // matches the current state, require all edges to match. This
1087 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001088 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001089 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001090 } else if (NotAllSeqEqualButKnownSafe) {
1091 // If we would have cleared the state foregoing the fact that we are known
1092 // safe, stop code motion. This is because whether or not it is safe to
1093 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1094 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001095 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001096 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001097 }
John McCalld935e9c2011-06-15 23:37:01 +00001098}
1099
Michael Gottesman0be69202015-03-05 23:28:58 +00001100bool ObjCARCOpt::VisitInstructionBottomUp(
1101 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1102 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001103 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001104 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001105 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001106
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001107 DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001108
Dan Gohman817a7c62012-03-22 18:24:56 +00001109 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001110 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001111 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001112
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001113 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001114 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001115 break;
1116 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001117 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001118 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1119 // objc_retainBlocks to objc_retains. Thus at this point any
1120 // objc_retainBlocks that we see are not optimizable.
1121 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001122 case ARCInstKind::Retain:
1123 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001124 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001125 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001126 if (S.MatchWithRetain()) {
1127 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1128 // it's better to let it remain as the first instruction after a call.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001129 if (Class != ARCInstKind::RetainRV) {
1130 DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001131 Retains[Inst] = S.GetRRInfo();
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001132 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001133 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001134 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001135 // A retain moving bottom up can be a use.
1136 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001137 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001138 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001139 // Conservatively, clear MyStates for all known pointers.
1140 MyStates.clearBottomUpPointers();
1141 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001142 case ARCInstKind::AutoreleasepoolPush:
1143 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001144 // These are irrelevant.
1145 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001146 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001147 // If we have a store into an alloca of a pointer we are tracking, the
1148 // pointer has multiple owners implying that we must be more conservative.
1149 //
1150 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001151 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001152 // objc_retain on the original pointer and the release on the pointer loaded
1153 // from the alloca. The optimizer will through the provenance analysis
1154 // realize that the two are related, but since we only require KnownSafe in
1155 // one direction, will match the inner retain on the original pointer with
1156 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001157 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001158 // both our retain and our release are KnownSafe.
1159 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001160 const DataLayout &DL = BB->getModule()->getDataLayout();
1161 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001162 auto I = MyStates.findPtrBottomUpState(
1163 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001164 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001165 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001166 }
1167 }
1168 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001169 default:
1170 break;
1171 }
1172
1173 // Consider any other possible effects of this instruction on each
1174 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001175 for (auto MI = MyStates.bottom_up_ptr_begin(),
1176 ME = MyStates.bottom_up_ptr_end();
1177 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001178 const Value *Ptr = MI->first;
1179 if (Ptr == Arg)
1180 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001181 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001182
Michael Gottesman16e6a202015-03-06 02:07:12 +00001183 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1184 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001185
Michael Gottesman16e6a202015-03-06 02:07:12 +00001186 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001187 }
1188
1189 return NestingDetected;
1190}
1191
Michael Gottesman0be69202015-03-05 23:28:58 +00001192bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1193 DenseMap<const BasicBlock *, BBState> &BBStates,
1194 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001195
1196 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001197
John McCalld935e9c2011-06-15 23:37:01 +00001198 bool NestingDetected = false;
1199 BBState &MyStates = BBStates[BB];
1200
1201 // Merge the states from each successor to compute the initial state
1202 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001203 BBState::edge_iterator SI(MyStates.succ_begin()),
1204 SE(MyStates.succ_end());
1205 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001206 const BasicBlock *Succ = *SI;
1207 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1208 assert(I != BBStates.end());
1209 MyStates.InitFromSucc(I->second);
1210 ++SI;
1211 for (; SI != SE; ++SI) {
1212 Succ = *SI;
1213 I = BBStates.find(Succ);
1214 assert(I != BBStates.end());
1215 MyStates.MergeSucc(I->second);
1216 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001217 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001218
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001219 DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
1220 << "Performing Dataflow:\n");
1221
John McCalld935e9c2011-06-15 23:37:01 +00001222 // Visit all the instructions, bottom-up.
1223 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001224 Instruction *Inst = &*std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001225
1226 // Invoke instructions are visited as part of their successors (below).
1227 if (isa<InvokeInst>(Inst))
1228 continue;
1229
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001230 DEBUG(dbgs() << " Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001231
Dan Gohman5c70fad2012-03-23 17:47:54 +00001232 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1233 }
1234
Dan Gohmandae33492012-04-27 18:56:31 +00001235 // If there's a predecessor with an invoke, visit the invoke as if it were
1236 // part of this block, since we can't insert code after an invoke in its own
1237 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001238 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1239 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001240 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001241 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1242 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001243 }
John McCalld935e9c2011-06-15 23:37:01 +00001244
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001245 DEBUG(llvm::dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
1246
Dan Gohman817a7c62012-03-22 18:24:56 +00001247 return NestingDetected;
1248}
John McCalld935e9c2011-06-15 23:37:01 +00001249
Dan Gohman817a7c62012-03-22 18:24:56 +00001250bool
1251ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1252 DenseMap<Value *, RRInfo> &Releases,
1253 BBState &MyStates) {
1254 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001255 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001256 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001257
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001258 DEBUG(llvm::dbgs() << " Class: " << Class << "\n");
1259
Dan Gohman817a7c62012-03-22 18:24:56 +00001260 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001261 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001262 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1263 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001264 // objc_retainBlocks that we see are not optimizable. We need to break since
1265 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001266 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001267 case ARCInstKind::Retain:
1268 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001269 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001270 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001271 NestingDetected |= S.InitTopDown(Class, Inst);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001272 // A retain can be a potential use; proceed to the generic checking
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001273 // code below.
1274 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001275 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001276 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001277 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001278 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001279 // Try to form a tentative pair in between this release instruction and the
1280 // top down pointers that we are tracking.
1281 if (S.MatchWithRelease(MDKindCache, Inst)) {
1282 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1283 // Map}. Then we clear S.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001284 DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001285 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001286 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001287 }
1288 break;
1289 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001290 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001291 // Conservatively, clear MyStates for all known pointers.
1292 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001293 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001294 case ARCInstKind::AutoreleasepoolPush:
1295 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001296 // These can not be uses of
1297 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001298 default:
1299 break;
1300 }
1301
1302 // Consider any other possible effects of this instruction on each
1303 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001304 for (auto MI = MyStates.top_down_ptr_begin(),
1305 ME = MyStates.top_down_ptr_end();
1306 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001307 const Value *Ptr = MI->first;
1308 if (Ptr == Arg)
1309 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001310 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001311 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1312 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001313
Michael Gottesman16e6a202015-03-06 02:07:12 +00001314 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001315 }
1316
1317 return NestingDetected;
1318}
1319
1320bool
1321ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1322 DenseMap<const BasicBlock *, BBState> &BBStates,
1323 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001324 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001325 bool NestingDetected = false;
1326 BBState &MyStates = BBStates[BB];
1327
1328 // Merge the states from each predecessor to compute the initial state
1329 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001330 BBState::edge_iterator PI(MyStates.pred_begin()),
1331 PE(MyStates.pred_end());
1332 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001333 const BasicBlock *Pred = *PI;
1334 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1335 assert(I != BBStates.end());
1336 MyStates.InitFromPred(I->second);
1337 ++PI;
1338 for (; PI != PE; ++PI) {
1339 Pred = *PI;
1340 I = BBStates.find(Pred);
1341 assert(I != BBStates.end());
1342 MyStates.MergePred(I->second);
1343 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001344 }
John McCalld935e9c2011-06-15 23:37:01 +00001345
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001346 DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
1347 << "Performing Dataflow:\n");
1348
John McCalld935e9c2011-06-15 23:37:01 +00001349 // Visit all the instructions, top-down.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001350 for (Instruction &Inst : *BB) {
1351 DEBUG(dbgs() << " Visiting " << Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001352
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001353 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001354 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001355
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001356 DEBUG(llvm::dbgs() << "\nState Before Checking for CFG Hazards:\n"
1357 << BBStates[BB] << "\n\n");
John McCalld935e9c2011-06-15 23:37:01 +00001358 CheckForCFGHazards(BB, BBStates, MyStates);
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001359 DEBUG(llvm::dbgs() << "Final State:\n" << BBStates[BB] << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001360 return NestingDetected;
1361}
1362
Dan Gohmana53a12c2011-12-12 19:42:25 +00001363static void
1364ComputePostOrders(Function &F,
1365 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001366 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1367 unsigned NoObjCARCExceptionsMDKind,
1368 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001369 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001370 SmallPtrSet<BasicBlock *, 16> Visited;
1371
1372 // Do DFS, computing the PostOrder.
1373 SmallPtrSet<BasicBlock *, 16> OnStack;
1374 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001375
1376 // Functions always have exactly one entry block, and we don't have
1377 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001378 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001379 BBState &MyStates = BBStates[EntryBB];
1380 MyStates.SetAsEntry();
1381 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1382 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001383 Visited.insert(EntryBB);
1384 OnStack.insert(EntryBB);
1385 do {
1386 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001387 BasicBlock *CurrBB = SuccStack.back().first;
1388 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1389 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001390
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001391 while (SuccStack.back().second != SE) {
1392 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001393 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001394 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1395 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001396 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001397 BBState &SuccStates = BBStates[SuccBB];
1398 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001399 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001400 goto dfs_next_succ;
1401 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001402
1403 if (!OnStack.count(SuccBB)) {
1404 BBStates[CurrBB].addSucc(SuccBB);
1405 BBStates[SuccBB].addPred(CurrBB);
1406 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001407 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001408 OnStack.erase(CurrBB);
1409 PostOrder.push_back(CurrBB);
1410 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001411 } while (!SuccStack.empty());
1412
1413 Visited.clear();
1414
Dan Gohmana53a12c2011-12-12 19:42:25 +00001415 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001416 // Functions may have many exits, and there also blocks which we treat
1417 // as exits due to ignored edges.
1418 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001419 for (BasicBlock &ExitBB : F) {
1420 BBState &MyStates = BBStates[&ExitBB];
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001421 if (!MyStates.isExit())
1422 continue;
1423
Dan Gohmandae33492012-04-27 18:56:31 +00001424 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001425
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001426 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1427 Visited.insert(&ExitBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001428 while (!PredStack.empty()) {
1429 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001430 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1431 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001432 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001433 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001434 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001435 goto reverse_dfs_next_succ;
1436 }
1437 }
1438 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1439 }
1440 }
1441}
1442
Michael Gottesman97e3df02013-01-14 00:35:14 +00001443// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001444bool ObjCARCOpt::Visit(Function &F,
1445 DenseMap<const BasicBlock *, BBState> &BBStates,
1446 BlotMapVector<Value *, RRInfo> &Retains,
1447 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001448
1449 // Use reverse-postorder traversals, because we magically know that loops
1450 // will be well behaved, i.e. they won't repeatedly call retain on a single
1451 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1452 // class here because we want the reverse-CFG postorder to consider each
1453 // function exit point, and we want to ignore selected cycle edges.
1454 SmallVector<BasicBlock *, 16> PostOrder;
1455 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001456 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman65cb7372015-03-16 07:02:27 +00001457 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1458 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001459
1460 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001461 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001462 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001463 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1464 I != E; ++I)
1465 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001466
Dan Gohmana53a12c2011-12-12 19:42:25 +00001467 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001468 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001469 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1470 PostOrder.rbegin(), E = PostOrder.rend();
1471 I != E; ++I)
1472 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001473
1474 return TopDownNestingDetected && BottomUpNestingDetected;
1475}
1476
Michael Gottesman97e3df02013-01-14 00:35:14 +00001477/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001478void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001479 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001480 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001481 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001482 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001483 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001484 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001485 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001486
Michael Gottesman89279f82013-04-05 18:10:41 +00001487 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001488
John McCalld935e9c2011-06-15 23:37:01 +00001489 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001490 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001491 Value *MyArg = ArgTy == ParamTy ? Arg :
1492 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001493 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001494 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001495 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001496 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001497
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001498 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001499 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001500 }
Craig Topper46276792014-08-24 23:23:06 +00001501 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001502 Value *MyArg = ArgTy == ParamTy ? Arg :
1503 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001504 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001505 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001506 // Attach a clang.imprecise_release metadata tag, if appropriate.
1507 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman65cb7372015-03-16 07:02:27 +00001508 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001509 Call->setDoesNotThrow();
1510 if (ReleasesToMove.IsTailCallRelease)
1511 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001512
Michael Gottesman89279f82013-04-05 18:10:41 +00001513 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1514 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001515 }
1516
1517 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001518 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001519 Retains.blot(OrigRetain);
1520 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001521 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001522 }
Craig Topper46276792014-08-24 23:23:06 +00001523 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001524 Releases.erase(OrigRelease);
1525 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001526 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001527 }
Michael Gottesman79249972013-04-05 23:46:45 +00001528
John McCalld935e9c2011-06-15 23:37:01 +00001529}
1530
Michael Gottesman67792172015-03-16 07:02:30 +00001531bool ObjCARCOpt::PairUpRetainsAndReleases(
Michael Gottesman0be69202015-03-05 23:28:58 +00001532 DenseMap<const BasicBlock *, BBState> &BBStates,
1533 BlotMapVector<Value *, RRInfo> &Retains,
1534 DenseMap<Value *, RRInfo> &Releases, Module *M,
1535 SmallVectorImpl<Instruction *> &NewRetains,
1536 SmallVectorImpl<Instruction *> &NewReleases,
1537 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1538 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1539 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001540 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001541 // is already incremented, we can similarly ignore possible decrements unless
1542 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001543 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001544 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001545 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001546
1547 // Connect the dots between the top-down-collected RetainsToMove and
1548 // bottom-up-collected ReleasesToMove to form sets of related calls.
1549 // This is an iterative process so that we connect multiple releases
1550 // to multiple retains if needed.
1551 unsigned OldDelta = 0;
1552 unsigned NewDelta = 0;
1553 unsigned OldCount = 0;
1554 unsigned NewCount = 0;
1555 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001556 for (;;) {
1557 for (SmallVectorImpl<Instruction *>::const_iterator
1558 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1559 Instruction *NewRetain = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001560 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001561 assert(It != Retains.end());
1562 const RRInfo &NewRetainRRI = It->second;
1563 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001564 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001565 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00001566 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001567 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001568 if (Jt == Releases.end())
1569 return false;
1570 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001571
1572 // If the release does not have a reference to the retain as well,
1573 // something happened which is unaccounted for. Do not do anything.
1574 //
1575 // This can happen if we catch an additive overflow during path count
1576 // merging.
1577 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1578 return false;
1579
David Blaikie70573dc2014-11-19 07:49:26 +00001580 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001581
1582 // If we overflow when we compute the path count, don't remove/move
1583 // anything.
1584 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001585 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001586 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1587 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001588 assert(PathCount != BBState::OverflowOccurredValue &&
1589 "PathCount at this point can not be "
1590 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001591 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001592
1593 // Merge the ReleaseMetadata and IsTailCallRelease values.
1594 if (FirstRelease) {
1595 ReleasesToMove.ReleaseMetadata =
1596 NewRetainReleaseRRI.ReleaseMetadata;
1597 ReleasesToMove.IsTailCallRelease =
1598 NewRetainReleaseRRI.IsTailCallRelease;
1599 FirstRelease = false;
1600 } else {
1601 if (ReleasesToMove.ReleaseMetadata !=
1602 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001603 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001604 if (ReleasesToMove.IsTailCallRelease !=
1605 NewRetainReleaseRRI.IsTailCallRelease)
1606 ReleasesToMove.IsTailCallRelease = false;
1607 }
1608
1609 // Collect the optimal insertion points.
1610 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001611 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001612 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001613 // If we overflow when we compute the path count, don't
1614 // remove/move anything.
1615 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001616 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001617 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1618 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001619 assert(PathCount != BBState::OverflowOccurredValue &&
1620 "PathCount at this point can not be "
1621 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001622 NewDelta -= PathCount;
1623 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001624 }
1625 NewReleases.push_back(NewRetainRelease);
1626 }
1627 }
1628 }
1629 NewRetains.clear();
1630 if (NewReleases.empty()) break;
1631
1632 // Back the other way.
1633 for (SmallVectorImpl<Instruction *>::const_iterator
1634 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1635 Instruction *NewRelease = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001636 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001637 assert(It != Releases.end());
1638 const RRInfo &NewReleaseRRI = It->second;
1639 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001640 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001641 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001642 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001643 if (Jt == Retains.end())
1644 return false;
1645 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001646
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001647 // If the retain does not have a reference to the release as well,
1648 // something happened which is unaccounted for. Do not do anything.
1649 //
1650 // This can happen if we catch an additive overflow during path count
1651 // merging.
1652 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1653 return false;
1654
David Blaikie70573dc2014-11-19 07:49:26 +00001655 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001656 // If we overflow when we compute the path count, don't remove/move
1657 // anything.
1658 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001659 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001660 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1661 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001662 assert(PathCount != BBState::OverflowOccurredValue &&
1663 "PathCount at this point can not be "
1664 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001665 OldDelta += PathCount;
1666 OldCount += PathCount;
1667
Michael Gottesman9de6f962013-01-22 21:49:00 +00001668 // Collect the optimal insertion points.
1669 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001670 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001671 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001672 // If we overflow when we compute the path count, don't
1673 // remove/move anything.
1674 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001675
1676 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001677 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1678 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001679 assert(PathCount != BBState::OverflowOccurredValue &&
1680 "PathCount at this point can not be "
1681 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001682 NewDelta += PathCount;
1683 NewCount += PathCount;
1684 }
1685 }
1686 NewRetains.push_back(NewReleaseRetain);
1687 }
1688 }
1689 }
1690 NewReleases.clear();
1691 if (NewRetains.empty()) break;
1692 }
1693
Michael Gottesmandd60f9b2015-03-16 07:02:36 +00001694 // We can only remove pointers if we are known safe in both directions.
1695 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001696 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001697 RetainsToMove.ReverseInsertPts.clear();
1698 ReleasesToMove.ReverseInsertPts.clear();
1699 NewCount = 0;
1700 } else {
1701 // Determine whether the new insertion points we computed preserve the
1702 // balance of retain and release calls through the program.
1703 // TODO: If the fully aggressive solution isn't valid, try to find a
1704 // less aggressive solution which is.
1705 if (NewDelta != 0)
1706 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001707
1708 // At this point, we are not going to remove any RR pairs, but we still are
1709 // able to move RR pairs. If one of our pointers is afflicted with
1710 // CFGHazards, we cannot perform such code motion so exit early.
1711 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1712 ReleasesToMove.ReverseInsertPts.size();
1713 if (CFGHazardAfflicted && WillPerformCodeMotion)
1714 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001715 }
1716
1717 // Determine whether the original call points are balanced in the retain and
1718 // release calls through the program. If not, conservatively don't touch
1719 // them.
1720 // TODO: It's theoretically possible to do code motion in this case, as
1721 // long as the existing imbalances are maintained.
1722 if (OldDelta != 0)
1723 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001724
Michael Gottesman9de6f962013-01-22 21:49:00 +00001725 Changed = true;
1726 assert(OldCount != 0 && "Unreachable code?");
1727 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001728 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001729 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001730
1731 // We can move calls!
1732 return true;
1733}
1734
Michael Gottesman97e3df02013-01-14 00:35:14 +00001735/// Identify pairings between the retains and releases, and delete and/or move
1736/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001737bool ObjCARCOpt::PerformCodePlacement(
1738 DenseMap<const BasicBlock *, BBState> &BBStates,
1739 BlotMapVector<Value *, RRInfo> &Retains,
1740 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001741 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1742
John McCalld935e9c2011-06-15 23:37:01 +00001743 bool AnyPairsCompletelyEliminated = false;
1744 RRInfo RetainsToMove;
1745 RRInfo ReleasesToMove;
1746 SmallVector<Instruction *, 4> NewRetains;
1747 SmallVector<Instruction *, 4> NewReleases;
1748 SmallVector<Instruction *, 8> DeadInsts;
1749
Dan Gohman670f9372012-04-13 18:57:48 +00001750 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001751 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1752 E = Retains.end();
1753 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001754 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001755 if (!V) continue; // blotted
1756
1757 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001758
Michael Gottesman89279f82013-04-05 18:10:41 +00001759 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001760
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001761 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001762
Dan Gohman728db492012-01-13 00:39:07 +00001763 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001764 // not being managed by ObjC reference counting, so we can delete pairs
1765 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001766 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001767
Dan Gohman56e1cef2011-08-22 17:29:11 +00001768 // A constant pointer can't be pointing to an object on the heap. It may
1769 // be reference-counted, but it won't be deleted.
1770 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1771 if (const GlobalVariable *GV =
1772 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001773 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001774 if (GV->isConstant())
1775 KnownSafe = true;
1776
John McCalld935e9c2011-06-15 23:37:01 +00001777 // Connect the dots between the top-down-collected RetainsToMove and
1778 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00001779 NewRetains.push_back(Retain);
Michael Gottesman67792172015-03-16 07:02:30 +00001780 bool PerformMoveCalls = PairUpRetainsAndReleases(
1781 BBStates, Retains, Releases, M, NewRetains, NewReleases, DeadInsts,
1782 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1783 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001784
Michael Gottesman9de6f962013-01-22 21:49:00 +00001785 if (PerformMoveCalls) {
1786 // Ok, everything checks out and we're all set. Let's move/delete some
1787 // code!
1788 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1789 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001790 }
1791
Michael Gottesman9de6f962013-01-22 21:49:00 +00001792 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00001793 NewReleases.clear();
1794 NewRetains.clear();
1795 RetainsToMove.clear();
1796 ReleasesToMove.clear();
1797 }
1798
1799 // Now that we're done moving everything, we can delete the newly dead
1800 // instructions, as we no longer need them as insert points.
1801 while (!DeadInsts.empty())
1802 EraseInstruction(DeadInsts.pop_back_val());
1803
1804 return AnyPairsCompletelyEliminated;
1805}
1806
Michael Gottesman97e3df02013-01-14 00:35:14 +00001807/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001808void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001809 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001810
John McCalld935e9c2011-06-15 23:37:01 +00001811 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1812 // itself because it uses AliasAnalysis and we need to do provenance
1813 // queries instead.
1814 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1815 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001816
Michael Gottesman89279f82013-04-05 18:10:41 +00001817 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001818
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001819 ARCInstKind Class = GetBasicARCInstKind(Inst);
1820 if (Class != ARCInstKind::LoadWeak &&
1821 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001822 continue;
1823
1824 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001825 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001826 Inst->eraseFromParent();
1827 continue;
1828 }
1829
1830 // TODO: For now, just look for an earlier available version of this value
1831 // within the same block. Theoretically, we could do memdep-style non-local
1832 // analysis too, but that would want caching. A better approach would be to
1833 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001834 inst_iterator Current = std::prev(I);
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001835 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
John McCalld935e9c2011-06-15 23:37:01 +00001836 for (BasicBlock::iterator B = CurrentBB->begin(),
1837 J = Current.getInstructionIterator();
1838 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001839 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001840 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001841 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001842 case ARCInstKind::LoadWeak:
1843 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001844 // If this is loading from the same pointer, replace this load's value
1845 // with that one.
1846 CallInst *Call = cast<CallInst>(Inst);
1847 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1848 Value *Arg = Call->getArgOperand(0);
1849 Value *EarlierArg = EarlierCall->getArgOperand(0);
1850 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001851 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001852 Changed = true;
1853 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001854 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001855 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001856 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001857 CI->setTailCall();
1858 }
1859 // Zap the fully redundant load.
1860 Call->replaceAllUsesWith(EarlierCall);
1861 Call->eraseFromParent();
1862 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001863 case MayAlias:
1864 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001865 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001866 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001867 break;
1868 }
1869 break;
1870 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001871 case ARCInstKind::StoreWeak:
1872 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001873 // If this is storing to the same pointer and has the same size etc.
1874 // replace this load's value with the stored value.
1875 CallInst *Call = cast<CallInst>(Inst);
1876 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1877 Value *Arg = Call->getArgOperand(0);
1878 Value *EarlierArg = EarlierCall->getArgOperand(0);
1879 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001880 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001881 Changed = true;
1882 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001883 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001884 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001885 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001886 CI->setTailCall();
1887 }
1888 // Zap the fully redundant load.
1889 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1890 Call->eraseFromParent();
1891 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001892 case MayAlias:
1893 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001894 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001895 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001896 break;
1897 }
1898 break;
1899 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001900 case ARCInstKind::MoveWeak:
1901 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001902 // TOOD: Grab the copied value.
1903 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001904 case ARCInstKind::AutoreleasepoolPush:
1905 case ARCInstKind::None:
1906 case ARCInstKind::IntrinsicUser:
1907 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001908 // Weak pointers are only modified through the weak entry points
1909 // (and arbitrary calls, which could call the weak entry points).
1910 break;
1911 default:
1912 // Anything else could modify the weak pointer.
1913 goto clobbered;
1914 }
1915 }
1916 clobbered:;
1917 }
1918
1919 // Then, for each destroyWeak with an alloca operand, check to see if
1920 // the alloca and all its users can be zapped.
1921 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1922 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001923 ARCInstKind Class = GetBasicARCInstKind(Inst);
1924 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001925 continue;
1926
1927 CallInst *Call = cast<CallInst>(Inst);
1928 Value *Arg = Call->getArgOperand(0);
1929 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001930 for (User *U : Alloca->users()) {
1931 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001932 switch (GetBasicARCInstKind(UserInst)) {
1933 case ARCInstKind::InitWeak:
1934 case ARCInstKind::StoreWeak:
1935 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001936 continue;
1937 default:
1938 goto done;
1939 }
1940 }
1941 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001942 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001943 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001944 switch (GetBasicARCInstKind(UserInst)) {
1945 case ARCInstKind::InitWeak:
1946 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001947 // These functions return their second argument.
1948 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1949 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001950 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001951 // No return value.
1952 break;
1953 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001954 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001955 }
John McCalld935e9c2011-06-15 23:37:01 +00001956 UserInst->eraseFromParent();
1957 }
1958 Alloca->eraseFromParent();
1959 done:;
1960 }
1961 }
1962}
1963
Michael Gottesman97e3df02013-01-14 00:35:14 +00001964/// Identify program paths which execute sequences of retains and releases which
1965/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001966bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001967 // Releases, Retains - These are used to store the results of the main flow
1968 // analysis. These use Value* as the key instead of Instruction* so that the
1969 // map stays valid when we get around to rewriting code and calls get
1970 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00001971 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00001972 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00001973
Michael Gottesman740db972013-05-23 02:35:21 +00001974 // This is used during the traversal of the function to track the
1975 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00001976 DenseMap<const BasicBlock *, BBState> BBStates;
1977
1978 // Analyze the CFG of the function, and all instructions.
1979 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1980
1981 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001982 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1983 Releases,
1984 F.getParent());
1985
1986 // Cleanup.
1987 MultiOwnersSet.clear();
1988
1989 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00001990}
1991
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001992/// Check if there is a dependent call earlier that does not have anything in
1993/// between the Retain and the call that can affect the reference count of their
1994/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001995static bool
1996HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00001997 SmallPtrSetImpl<Instruction *> &DepInsts,
1998 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001999 ProvenanceAnalysis &PA) {
2000 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2001 DepInsts, Visited, PA);
2002 if (DepInsts.size() != 1)
2003 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002004
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002005 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002006
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002007 // Check that the pointer is the return value of the call.
2008 if (!Call || Arg != Call)
2009 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002010
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002011 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002012 ARCInstKind Class = GetBasicARCInstKind(Call);
2013 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002014 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002015
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002016 return true;
2017}
2018
Michael Gottesman6908db12013-04-03 23:16:05 +00002019/// Find a dependent retain that precedes the given autorelease for which there
2020/// is nothing in between the two instructions that can affect the ref count of
2021/// Arg.
2022static CallInst *
2023FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2024 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002025 SmallPtrSetImpl<Instruction *> &DepInsts,
2026 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002027 ProvenanceAnalysis &PA) {
2028 FindDependencies(CanChangeRetainCount, Arg,
2029 BB, Autorelease, DepInsts, Visited, PA);
2030 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002031 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002032
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002033 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002034
Michael Gottesman6908db12013-04-03 23:16:05 +00002035 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002036 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002037 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002038 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002039 }
Michael Gottesman79249972013-04-05 23:46:45 +00002040
Michael Gottesman6908db12013-04-03 23:16:05 +00002041 return Retain;
2042}
2043
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002044/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2045/// no instructions dependent on Arg that need a positive ref count in between
2046/// the autorelease and the ret.
2047static CallInst *
2048FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2049 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002050 SmallPtrSetImpl<Instruction *> &DepInsts,
2051 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002052 ProvenanceAnalysis &PA) {
2053 FindDependencies(NeedsPositiveRetainCount, Arg,
2054 BB, Ret, DepInsts, V, PA);
2055 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002056 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002057
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002058 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002059 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002060 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002061 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002062 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002063 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002064 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002065 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002066
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002067 return Autorelease;
2068}
2069
Michael Gottesman97e3df02013-01-14 00:35:14 +00002070/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002071/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002072/// %call = call i8* @something(...)
2073/// %2 = call i8* @objc_retain(i8* %call)
2074/// %3 = call i8* @objc_autorelease(i8* %2)
2075/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002076/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002077/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002078void ObjCARCOpt::OptimizeReturns(Function &F) {
2079 if (!F.getReturnType()->isPointerTy())
2080 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002081
Michael Gottesman89279f82013-04-05 18:10:41 +00002082 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002083
John McCalld935e9c2011-06-15 23:37:01 +00002084 SmallPtrSet<Instruction *, 4> DependingInstructions;
2085 SmallPtrSet<const BasicBlock *, 4> Visited;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002086 for (BasicBlock &BB: F) {
2087 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002088
Michael Gottesman89279f82013-04-05 18:10:41 +00002089 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002090
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002091 if (!Ret)
2092 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002093
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002094 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002095
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002096 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002097 // dependent on Arg such that there are no instructions dependent on Arg
2098 // that need a positive ref count in between the autorelease and Ret.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002099 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath(
2100 Arg, &BB, Ret, DependingInstructions, Visited, PA);
John McCalld935e9c2011-06-15 23:37:01 +00002101 DependingInstructions.clear();
2102 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002103
2104 if (!Autorelease)
2105 continue;
2106
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002107 CallInst *Retain = FindPredecessorRetainWithSafePath(
2108 Arg, &BB, Autorelease, DependingInstructions, Visited, PA);
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002109 DependingInstructions.clear();
2110 Visited.clear();
2111
2112 if (!Retain)
2113 continue;
2114
2115 // Check that there is nothing that can affect the reference count
2116 // between the retain and the call. Note that Retain need not be in BB.
2117 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2118 DependingInstructions,
2119 Visited, PA);
2120 DependingInstructions.clear();
2121 Visited.clear();
2122
2123 if (!HasSafePathToCall)
2124 continue;
2125
2126 // If so, we can zap the retain and autorelease.
2127 Changed = true;
2128 ++NumRets;
2129 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2130 << *Autorelease << "\n");
2131 EraseInstruction(Retain);
2132 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002133 }
2134}
2135
Michael Gottesman9c118152013-04-29 06:16:57 +00002136#ifndef NDEBUG
2137void
2138ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2139 llvm::Statistic &NumRetains =
2140 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2141 llvm::Statistic &NumReleases =
2142 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2143
2144 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2145 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002146 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002147 default:
2148 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002149 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002150 ++NumRetains;
2151 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002152 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002153 ++NumReleases;
2154 break;
2155 }
2156 }
2157}
2158#endif
2159
John McCalld935e9c2011-06-15 23:37:01 +00002160bool ObjCARCOpt::doInitialization(Module &M) {
2161 if (!EnableARCOpts)
2162 return false;
2163
Dan Gohman670f9372012-04-13 18:57:48 +00002164 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002165 Run = ModuleHasARC(M);
2166 if (!Run)
2167 return false;
2168
John McCalld935e9c2011-06-15 23:37:01 +00002169 // Intuitively, objc_retain and others are nocapture, however in practice
2170 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002171 // calls finalizers which can have arbitrary side effects.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002172 MDKindCache.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002173
Michael Gottesman14acfac2013-07-06 01:39:23 +00002174 // Initialize our runtime entry point cache.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002175 EP.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002176
2177 return false;
2178}
2179
2180bool ObjCARCOpt::runOnFunction(Function &F) {
2181 if (!EnableARCOpts)
2182 return false;
2183
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002184 // If nothing in the Module uses ARC, don't do anything.
2185 if (!Run)
2186 return false;
2187
John McCalld935e9c2011-06-15 23:37:01 +00002188 Changed = false;
2189
Michael Gottesman89279f82013-04-05 18:10:41 +00002190 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2191 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002192
Chandler Carruth7b560d42015-09-09 17:55:00 +00002193 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
John McCalld935e9c2011-06-15 23:37:01 +00002194
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002195#ifndef NDEBUG
2196 if (AreStatisticsEnabled()) {
2197 GatherStatistics(F, false);
2198 }
2199#endif
2200
John McCalld935e9c2011-06-15 23:37:01 +00002201 // This pass performs several distinct transformations. As a compile-time aid
2202 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2203 // library functions aren't declared.
2204
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002205 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002206 OptimizeIndividualCalls(F);
2207
2208 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002209 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2210 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2211 (1 << unsigned(ARCInstKind::StoreWeak)) |
2212 (1 << unsigned(ARCInstKind::InitWeak)) |
2213 (1 << unsigned(ARCInstKind::CopyWeak)) |
2214 (1 << unsigned(ARCInstKind::MoveWeak)) |
2215 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002216 OptimizeWeakCalls(F);
2217
2218 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002219 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2220 (1 << unsigned(ARCInstKind::RetainRV)) |
2221 (1 << unsigned(ARCInstKind::RetainBlock))))
2222 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002223 // Run OptimizeSequences until it either stops making changes or
2224 // no retain+release pair nesting is detected.
2225 while (OptimizeSequences(F)) {}
2226
2227 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002228 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2229 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002230 OptimizeReturns(F);
2231
Michael Gottesman9c118152013-04-29 06:16:57 +00002232 // Gather statistics after optimization.
2233#ifndef NDEBUG
2234 if (AreStatisticsEnabled()) {
2235 GatherStatistics(F, true);
2236 }
2237#endif
2238
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002239 DEBUG(dbgs() << "\n");
2240
John McCalld935e9c2011-06-15 23:37:01 +00002241 return Changed;
2242}
2243
2244void ObjCARCOpt::releaseMemory() {
2245 PA.clear();
2246}
2247
Michael Gottesman97e3df02013-01-14 00:35:14 +00002248/// @}
2249///