blob: cef049591ce2f608aaa6c44721da91beb7402dfa [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#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman14acfac2013-07-06 01:39:23 +000029#include "ARCRuntimeEntryPoints.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000030#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000031#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000032#include "ProvenanceAnalysis.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"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000038#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000039#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000040#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000041#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000042#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000043
John McCalld935e9c2011-06-15 23:37:01 +000044using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000045using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000046
Michael Gottesman97e3df02013-01-14 00:35:14 +000047/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
48/// @{
John McCalld935e9c2011-06-15 23:37:01 +000049
50namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000051 /// \brief An associative container with fast insertion-order (deterministic)
52 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000053 template<class KeyT, class ValueT>
54 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000055 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000056 typedef DenseMap<KeyT, size_t> MapTy;
57 MapTy Map;
58
John McCalld935e9c2011-06-15 23:37:01 +000059 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000060 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000061 VectorTy Vector;
62
63 public:
64 typedef typename VectorTy::iterator iterator;
65 typedef typename VectorTy::const_iterator const_iterator;
66 iterator begin() { return Vector.begin(); }
67 iterator end() { return Vector.end(); }
68 const_iterator begin() const { return Vector.begin(); }
69 const_iterator end() const { return Vector.end(); }
70
71#ifdef XDEBUG
72 ~MapVector() {
73 assert(Vector.size() >= Map.size()); // May differ due to blotting.
74 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
75 I != E; ++I) {
76 assert(I->second < Vector.size());
77 assert(Vector[I->second].first == I->first);
78 }
79 for (typename VectorTy::const_iterator I = Vector.begin(),
80 E = Vector.end(); I != E; ++I)
81 assert(!I->first ||
82 (Map.count(I->first) &&
83 Map[I->first] == size_t(I - Vector.begin())));
84 }
85#endif
86
Dan Gohman55b06742012-03-02 01:13:53 +000087 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000088 std::pair<typename MapTy::iterator, bool> Pair =
89 Map.insert(std::make_pair(Arg, size_t(0)));
90 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000091 size_t Num = Vector.size();
92 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000093 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000094 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000095 }
96 return Vector[Pair.first->second].second;
97 }
98
99 std::pair<iterator, bool>
100 insert(const std::pair<KeyT, ValueT> &InsertPair) {
101 std::pair<typename MapTy::iterator, bool> Pair =
102 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
103 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000104 size_t Num = Vector.size();
105 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000106 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000107 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000108 }
109 return std::make_pair(Vector.begin() + Pair.first->second, false);
110 }
111
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000112 iterator find(const KeyT &Key) {
113 typename MapTy::iterator It = Map.find(Key);
114 if (It == Map.end()) return Vector.end();
115 return Vector.begin() + It->second;
116 }
117
Dan Gohman55b06742012-03-02 01:13:53 +0000118 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000119 typename MapTy::const_iterator It = Map.find(Key);
120 if (It == Map.end()) return Vector.end();
121 return Vector.begin() + It->second;
122 }
123
Michael Gottesman97e3df02013-01-14 00:35:14 +0000124 /// This is similar to erase, but instead of removing the element from the
125 /// vector, it just zeros out the key in the vector. This leaves iterators
126 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000127 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000128 typename MapTy::iterator It = Map.find(Key);
129 if (It == Map.end()) return;
130 Vector[It->second].first = KeyT();
131 Map.erase(It);
132 }
133
134 void clear() {
135 Map.clear();
136 Vector.clear();
137 }
138 };
139}
140
Michael Gottesman97e3df02013-01-14 00:35:14 +0000141/// @}
142///
143/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
144/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000145
Michael Gottesman97e3df02013-01-14 00:35:14 +0000146/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
147/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000148static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
149 if (Arg->hasOneUse()) {
150 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
151 return FindSingleUseIdentifiedObject(BC->getOperand(0));
152 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
153 if (GEP->hasAllZeroIndices())
154 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
155 if (IsForwarding(GetBasicInstructionClass(Arg)))
156 return FindSingleUseIdentifiedObject(
157 cast<CallInst>(Arg)->getArgOperand(0));
158 if (!IsObjCIdentifiedObject(Arg))
159 return 0;
160 return Arg;
161 }
162
Dan Gohman41375a32012-05-08 23:39:44 +0000163 // If we found an identifiable object but it has multiple uses, but they are
164 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000165 if (IsObjCIdentifiedObject(Arg)) {
166 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
167 UI != UE; ++UI) {
168 const User *U = *UI;
169 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
170 return 0;
171 }
172
173 return Arg;
174 }
175
176 return 0;
177}
178
Michael Gottesman774d2c02013-01-29 21:00:52 +0000179/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000180///
181/// This differs from regular escape analysis in that a use as an
182/// argument to a call is not considered an escape.
183///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000186
Dan Gohman728db492012-01-13 00:39:07 +0000187 // Walk the def-use chains.
188 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000189 Worklist.push_back(Ptr);
190 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000191 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
192 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000193 Worklist.push_back(*I);
194 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000195
196 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000197 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000198
Dan Gohman728db492012-01-13 00:39:07 +0000199 do {
200 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Michael Gottesman89279f82013-04-05 18:10:41 +0000202 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000203
Dan Gohman728db492012-01-13 00:39:07 +0000204 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
205 UI != UE; ++UI) {
206 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000207
Michael Gottesman89279f82013-04-05 18:10:41 +0000208 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000209
Dan Gohman728db492012-01-13 00:39:07 +0000210 // Special - Use by a call (callee or argument) is not considered
211 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000212 switch (GetBasicInstructionClass(UUser)) {
213 case IC_StoreWeak:
214 case IC_InitWeak:
215 case IC_StoreStrong:
216 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000217 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000218 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000219 // These special functions make copies of their pointer arguments.
220 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000221 }
John McCall20182ac2013-03-22 21:38:36 +0000222 case IC_IntrinsicUser:
223 // Use by the use intrinsic is not an escape.
224 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000225 case IC_User:
226 case IC_None:
227 // Use by an instruction which copies the value is an escape if the
228 // result is an escape.
229 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
230 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000231
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000232 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000233 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
234 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000235 Worklist.push_back(UUser);
236 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000237 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000238 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000239 continue;
240 }
241 // Use by a load is not an escape.
242 if (isa<LoadInst>(UUser))
243 continue;
244 // Use by a store is not an escape if the use is the address.
245 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
246 if (V != SI->getValueOperand())
247 continue;
248 break;
249 default:
250 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000251 continue;
252 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000253 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000254 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000255 return true;
256 }
257 } while (!Worklist.empty());
258
259 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000260 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000261 return false;
262}
263
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000264/// This is a wrapper around getUnderlyingObjCPtr along the lines of
265/// GetUnderlyingObjects except that it returns early when it sees the first
266/// alloca.
267static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
268 SmallPtrSet<const Value *, 4> Visited;
269 SmallVector<const Value *, 4> Worklist;
270 Worklist.push_back(V);
271 do {
272 const Value *P = Worklist.pop_back_val();
273 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000274
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000275 if (isa<AllocaInst>(P))
276 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000277
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000278 if (!Visited.insert(P))
279 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000280
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000281 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
282 Worklist.push_back(SI->getTrueValue());
283 Worklist.push_back(SI->getFalseValue());
284 continue;
285 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000286
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000287 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
288 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
289 Worklist.push_back(PN->getIncomingValue(i));
290 continue;
291 }
292 } while (!Worklist.empty());
293
294 return false;
295}
296
297
Michael Gottesman97e3df02013-01-14 00:35:14 +0000298/// @}
299///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000300/// \defgroup ARCOpt ARC Optimization.
301/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000302
303// TODO: On code like this:
304//
305// objc_retain(%x)
306// stuff_that_cannot_release()
307// objc_autorelease(%x)
308// stuff_that_cannot_release()
309// objc_retain(%x)
310// stuff_that_cannot_release()
311// objc_autorelease(%x)
312//
313// The second retain and autorelease can be deleted.
314
315// TODO: It should be possible to delete
316// objc_autoreleasePoolPush and objc_autoreleasePoolPop
317// pairs if nothing is actually autoreleased between them. Also, autorelease
318// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
319// after inlining) can be turned into plain release calls.
320
321// TODO: Critical-edge splitting. If the optimial insertion point is
322// a critical edge, the current algorithm has to fail, because it doesn't
323// know how to split edges. It should be possible to make the optimizer
324// think in terms of edges, rather than blocks, and then split critical
325// edges on demand.
326
327// TODO: OptimizeSequences could generalized to be Interprocedural.
328
329// TODO: Recognize that a bunch of other objc runtime calls have
330// non-escaping arguments and non-releasing arguments, and may be
331// non-autoreleasing.
332
333// TODO: Sink autorelease calls as far as possible. Unfortunately we
334// usually can't sink them past other calls, which would be the main
335// case where it would be useful.
336
Dan Gohmanb3894012011-08-19 00:26:36 +0000337// TODO: The pointer returned from objc_loadWeakRetained is retained.
338
339// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000340
John McCalld935e9c2011-06-15 23:37:01 +0000341STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
342STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
343STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
344STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000345 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000346STATISTIC(NumRRs, "Number of retain+release paths eliminated");
347STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000348#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000349STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000350 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000351STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000352 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000353STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000354 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000355STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000356 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000357#endif
John McCalld935e9c2011-06-15 23:37:01 +0000358
359namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000360 /// \enum Sequence
361 ///
362 /// \brief A sequence of states that a pointer may go through in which an
363 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000364 enum Sequence {
365 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000366 S_Retain, ///< objc_retain(x).
367 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
368 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000369 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000370 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000371 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000372 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000373
374 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
375 LLVM_ATTRIBUTE_UNUSED;
376 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
377 switch (S) {
378 case S_None:
379 return OS << "S_None";
380 case S_Retain:
381 return OS << "S_Retain";
382 case S_CanRelease:
383 return OS << "S_CanRelease";
384 case S_Use:
385 return OS << "S_Use";
386 case S_Release:
387 return OS << "S_Release";
388 case S_MovableRelease:
389 return OS << "S_MovableRelease";
390 case S_Stop:
391 return OS << "S_Stop";
392 }
393 llvm_unreachable("Unknown sequence type.");
394 }
John McCalld935e9c2011-06-15 23:37:01 +0000395}
396
397static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
398 // The easy cases.
399 if (A == B)
400 return A;
401 if (A == S_None || B == S_None)
402 return S_None;
403
John McCalld935e9c2011-06-15 23:37:01 +0000404 if (A > B) std::swap(A, B);
405 if (TopDown) {
406 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000407 if ((A == S_Retain || A == S_CanRelease) &&
408 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000409 return B;
410 } else {
411 // Choose the side which is further along in the sequence.
412 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000413 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000414 return A;
415 // If both sides are releases, choose the more conservative one.
416 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
417 return A;
418 if (A == S_Release && B == S_MovableRelease)
419 return A;
420 }
421
422 return S_None;
423}
424
425namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000426 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000427 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000428 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000429 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000430 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000431 /// object is known to be positive. Similarly, before an objc_release, the
432 /// reference count of the referenced object is known to be positive. If
433 /// there are retain-release pairs in code regions where the retain count
434 /// is known to be positive, they can be eliminated, regardless of any side
435 /// effects between them.
436 ///
437 /// Also, a retain+release pair nested within another retain+release
438 /// pair all on the known same pointer value can be eliminated, regardless
439 /// of any intervening side effects.
440 ///
441 /// KnownSafe is true when either of these conditions is satisfied.
442 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000443
Michael Gottesman97e3df02013-01-14 00:35:14 +0000444 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000445 bool IsTailCallRelease;
446
Michael Gottesman97e3df02013-01-14 00:35:14 +0000447 /// If the Calls are objc_release calls and they all have a
448 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000449 MDNode *ReleaseMetadata;
450
Michael Gottesman97e3df02013-01-14 00:35:14 +0000451 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000452 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
453 SmallPtrSet<Instruction *, 2> Calls;
454
Michael Gottesman97e3df02013-01-14 00:35:14 +0000455 /// The set of optimal insert positions for moving calls in the opposite
456 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000457 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
458
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000459 /// If this is true, we cannot perform code motion but can still remove
460 /// retain/release pairs.
461 bool CFGHazardAfflicted;
462
John McCalld935e9c2011-06-15 23:37:01 +0000463 RRInfo() :
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000464 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
465 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000466
467 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000468
Michael Gottesman4773a102013-06-21 05:42:08 +0000469 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
470 /// occured, false otherwise.
471 bool Merge(const RRInfo &Other);
472
John McCalld935e9c2011-06-15 23:37:01 +0000473 };
474}
475
476void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000477 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000478 IsTailCallRelease = false;
479 ReleaseMetadata = 0;
480 Calls.clear();
481 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000482 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000483}
484
Michael Gottesman4773a102013-06-21 05:42:08 +0000485bool RRInfo::Merge(const RRInfo &Other) {
486 // Conservatively merge the ReleaseMetadata information.
487 if (ReleaseMetadata != Other.ReleaseMetadata)
488 ReleaseMetadata = 0;
489
490 // Conservatively merge the boolean state.
491 KnownSafe &= Other.KnownSafe;
492 IsTailCallRelease &= Other.IsTailCallRelease;
493 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
494
495 // Merge the call sets.
496 Calls.insert(Other.Calls.begin(), Other.Calls.end());
497
498 // Merge the insert point sets. If there are any differences,
499 // that makes this a partial merge.
500 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
501 for (SmallPtrSet<Instruction *, 2>::const_iterator
502 I = Other.ReverseInsertPts.begin(),
503 E = Other.ReverseInsertPts.end(); I != E; ++I)
504 Partial |= ReverseInsertPts.insert(*I);
505 return Partial;
506}
507
John McCalld935e9c2011-06-15 23:37:01 +0000508namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000509 /// \brief This class summarizes several per-pointer runtime properties which
510 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000511 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000512 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000513 bool KnownPositiveRefCount;
514
Bob Wilson798a7702013-04-09 22:15:51 +0000515 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000516 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000517 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000518
Michael Gottesman97e3df02013-01-14 00:35:14 +0000519 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000520 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000521
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// Unidirectional information about the current sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000523 RRInfo RRI;
524
Michael Gottesmane3943d02013-06-21 19:44:30 +0000525 public:
Dan Gohmandf476e52012-09-04 23:16:20 +0000526 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000527 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000528
Michael Gottesman93132252013-06-21 06:59:02 +0000529
530 bool IsKnownSafe() const {
Michael Gottesman01df4502013-07-06 01:41:35 +0000531 return RRI.KnownSafe;
Michael Gottesman93132252013-06-21 06:59:02 +0000532 }
533
534 void SetKnownSafe(const bool NewValue) {
535 RRI.KnownSafe = NewValue;
536 }
537
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000538 bool IsTailCallRelease() const {
539 return RRI.IsTailCallRelease;
540 }
541
542 void SetTailCallRelease(const bool NewValue) {
543 RRI.IsTailCallRelease = NewValue;
544 }
545
Michael Gottesman9799cf72013-06-21 20:52:49 +0000546 bool IsTrackingImpreciseReleases() const {
Michael Gottesmanf0401182013-06-21 19:12:38 +0000547 return RRI.ReleaseMetadata != 0;
548 }
549
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000550 const MDNode *GetReleaseMetadata() const {
551 return RRI.ReleaseMetadata;
552 }
553
554 void SetReleaseMetadata(MDNode *NewValue) {
555 RRI.ReleaseMetadata = NewValue;
556 }
557
Michael Gottesman2f294592013-06-21 19:12:36 +0000558 bool IsCFGHazardAfflicted() const {
559 return RRI.CFGHazardAfflicted;
560 }
561
562 void SetCFGHazardAfflicted(const bool NewValue) {
563 RRI.CFGHazardAfflicted = NewValue;
564 }
565
Michael Gottesman415ddd72013-02-05 19:32:18 +0000566 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000567 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000568 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000569 }
570
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000571 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000572 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000573 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000574 }
575
Michael Gottesman07beea42013-03-23 05:31:01 +0000576 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000577 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000578 }
579
Michael Gottesman415ddd72013-02-05 19:32:18 +0000580 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000581 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000582 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000583 }
584
Michael Gottesman415ddd72013-02-05 19:32:18 +0000585 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000586 return Seq;
587 }
588
Michael Gottesman415ddd72013-02-05 19:32:18 +0000589 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000590 ResetSequenceProgress(S_None);
591 }
592
Michael Gottesman415ddd72013-02-05 19:32:18 +0000593 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000594 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000595 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000596 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000597 RRI.clear();
598 }
599
600 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000601
602 void InsertCall(Instruction *I) {
603 RRI.Calls.insert(I);
604 }
605
606 void InsertReverseInsertPt(Instruction *I) {
607 RRI.ReverseInsertPts.insert(I);
608 }
609
610 void ClearReverseInsertPts() {
611 RRI.ReverseInsertPts.clear();
612 }
613
614 bool HasReverseInsertPts() const {
615 return !RRI.ReverseInsertPts.empty();
616 }
Michael Gottesmane3943d02013-06-21 19:44:30 +0000617
618 const RRInfo &GetRRInfo() const {
619 return RRI;
620 }
John McCalld935e9c2011-06-15 23:37:01 +0000621 };
622}
623
624void
625PtrState::Merge(const PtrState &Other, bool TopDown) {
626 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000627 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000628
Dan Gohman1736c142011-10-17 18:48:25 +0000629 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000630 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000631 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000632 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000633 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000634 // If we're doing a merge on a path that's previously seen a partial
635 // merge, conservatively drop the sequence, to avoid doing partial
636 // RR elimination. If the branch predicates for the two merge differ,
637 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000638 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000639 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000640 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
641 // point, we know that currently we are not partial. Stash whether or not
642 // the merge operation caused us to undergo a partial merging of reverse
643 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000644 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000645 }
646}
647
648namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000649 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000650 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000651 /// The number of unique control paths from the entry which can reach this
652 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000653 unsigned TopDownPathCount;
654
Michael Gottesman97e3df02013-01-14 00:35:14 +0000655 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000656 unsigned BottomUpPathCount;
657
Michael Gottesman97e3df02013-01-14 00:35:14 +0000658 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000659 typedef MapVector<const Value *, PtrState> MapTy;
660
Michael Gottesman97e3df02013-01-14 00:35:14 +0000661 /// The top-down traversal uses this to record information known about a
662 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000663 MapTy PerPtrTopDown;
664
Michael Gottesman97e3df02013-01-14 00:35:14 +0000665 /// The bottom-up traversal uses this to record information known about a
666 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000667 MapTy PerPtrBottomUp;
668
Michael Gottesman97e3df02013-01-14 00:35:14 +0000669 /// Effective predecessors of the current block ignoring ignorable edges and
670 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000671 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000672 /// Effective successors of the current block ignoring ignorable edges and
673 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000674 SmallVector<BasicBlock *, 2> Succs;
675
John McCalld935e9c2011-06-15 23:37:01 +0000676 public:
677 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
678
679 typedef MapTy::iterator ptr_iterator;
680 typedef MapTy::const_iterator ptr_const_iterator;
681
682 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
683 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
684 ptr_const_iterator top_down_ptr_begin() const {
685 return PerPtrTopDown.begin();
686 }
687 ptr_const_iterator top_down_ptr_end() const {
688 return PerPtrTopDown.end();
689 }
690
691 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
692 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
693 ptr_const_iterator bottom_up_ptr_begin() const {
694 return PerPtrBottomUp.begin();
695 }
696 ptr_const_iterator bottom_up_ptr_end() const {
697 return PerPtrBottomUp.end();
698 }
699
Michael Gottesman97e3df02013-01-14 00:35:14 +0000700 /// Mark this block as being an entry block, which has one path from the
701 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000702 void SetAsEntry() { TopDownPathCount = 1; }
703
Michael Gottesman97e3df02013-01-14 00:35:14 +0000704 /// Mark this block as being an exit block, which has one path to an exit by
705 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000706 void SetAsExit() { BottomUpPathCount = 1; }
707
Michael Gottesman993fbf72013-05-13 19:40:39 +0000708 /// Attempt to find the PtrState object describing the top down state for
709 /// pointer Arg. Return a new initialized PtrState describing the top down
710 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000711 PtrState &getPtrTopDownState(const Value *Arg) {
712 return PerPtrTopDown[Arg];
713 }
714
Michael Gottesman993fbf72013-05-13 19:40:39 +0000715 /// Attempt to find the PtrState object describing the bottom up state for
716 /// pointer Arg. Return a new initialized PtrState describing the bottom up
717 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000718 PtrState &getPtrBottomUpState(const Value *Arg) {
719 return PerPtrBottomUp[Arg];
720 }
721
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000722 /// Attempt to find the PtrState object describing the bottom up state for
723 /// pointer Arg.
724 ptr_iterator findPtrBottomUpState(const Value *Arg) {
725 return PerPtrBottomUp.find(Arg);
726 }
727
John McCalld935e9c2011-06-15 23:37:01 +0000728 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000729 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000730 }
731
732 void clearTopDownPointers() {
733 PerPtrTopDown.clear();
734 }
735
736 void InitFromPred(const BBState &Other);
737 void InitFromSucc(const BBState &Other);
738 void MergePred(const BBState &Other);
739 void MergeSucc(const BBState &Other);
740
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000741 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000742 /// which pass through this block. This is only valid after both the
743 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000744 ///
745 /// Returns true if overflow occured. Returns false if overflow did not
746 /// occur.
747 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000748 assert(TopDownPathCount != 0);
749 assert(BottomUpPathCount != 0);
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000750 unsigned long long Product =
751 (unsigned long long)TopDownPathCount*BottomUpPathCount;
752 PathCount = Product;
753 // Overflow occured if any of the upper bits of Product are set.
754 return Product >> 32;
John McCalld935e9c2011-06-15 23:37:01 +0000755 }
Dan Gohman12130272011-08-12 00:26:31 +0000756
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000757 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000758 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000759 edge_iterator pred_begin() { return Preds.begin(); }
760 edge_iterator pred_end() { return Preds.end(); }
761 edge_iterator succ_begin() { return Succs.begin(); }
762 edge_iterator succ_end() { return Succs.end(); }
763
764 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
765 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
766
767 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000768 };
769}
770
771void BBState::InitFromPred(const BBState &Other) {
772 PerPtrTopDown = Other.PerPtrTopDown;
773 TopDownPathCount = Other.TopDownPathCount;
774}
775
776void BBState::InitFromSucc(const BBState &Other) {
777 PerPtrBottomUp = Other.PerPtrBottomUp;
778 BottomUpPathCount = Other.BottomUpPathCount;
779}
780
Michael Gottesman97e3df02013-01-14 00:35:14 +0000781/// The top-down traversal uses this to merge information about predecessors to
782/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000783void BBState::MergePred(const BBState &Other) {
784 // Other.TopDownPathCount can be 0, in which case it is either dead or a
785 // loop backedge. Loop backedges are special.
786 TopDownPathCount += Other.TopDownPathCount;
787
Michael Gottesman4385edf2013-01-14 01:47:53 +0000788 // Check for overflow. If we have overflow, fall back to conservative
789 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000790 if (TopDownPathCount < Other.TopDownPathCount) {
791 clearTopDownPointers();
792 return;
793 }
794
John McCalld935e9c2011-06-15 23:37:01 +0000795 // For each entry in the other set, if our set has an entry with the same key,
796 // merge the entries. Otherwise, copy the entry and merge it with an empty
797 // entry.
798 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
799 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
800 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
801 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
802 /*TopDown=*/true);
803 }
804
Dan Gohman7e315fc32011-08-11 21:06:32 +0000805 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000806 // same key, force it to merge with an empty entry.
807 for (ptr_iterator MI = top_down_ptr_begin(),
808 ME = top_down_ptr_end(); MI != ME; ++MI)
809 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
810 MI->second.Merge(PtrState(), /*TopDown=*/true);
811}
812
Michael Gottesman97e3df02013-01-14 00:35:14 +0000813/// The bottom-up traversal uses this to merge information about successors to
814/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000815void BBState::MergeSucc(const BBState &Other) {
816 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
817 // loop backedge. Loop backedges are special.
818 BottomUpPathCount += Other.BottomUpPathCount;
819
Michael Gottesman4385edf2013-01-14 01:47:53 +0000820 // Check for overflow. If we have overflow, fall back to conservative
821 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000822 if (BottomUpPathCount < Other.BottomUpPathCount) {
823 clearBottomUpPointers();
824 return;
825 }
826
John McCalld935e9c2011-06-15 23:37:01 +0000827 // For each entry in the other set, if our set has an entry with the
828 // same key, merge the entries. Otherwise, copy the entry and merge
829 // it with an empty entry.
830 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
831 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
832 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
833 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
834 /*TopDown=*/false);
835 }
836
Dan Gohman7e315fc32011-08-11 21:06:32 +0000837 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000838 // with the same key, force it to merge with an empty entry.
839 for (ptr_iterator MI = bottom_up_ptr_begin(),
840 ME = bottom_up_ptr_end(); MI != ME; ++MI)
841 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
842 MI->second.Merge(PtrState(), /*TopDown=*/false);
843}
844
Michael Gottesman81b1d432013-03-26 00:42:04 +0000845// Only enable ARC Annotations if we are building a debug version of
846// libObjCARCOpts.
847#ifndef NDEBUG
848#define ARC_ANNOTATIONS
849#endif
850
851// Define some macros along the lines of DEBUG and some helper functions to make
852// it cleaner to create annotations in the source code and to no-op when not
853// building in debug mode.
854#ifdef ARC_ANNOTATIONS
855
856#include "llvm/Support/CommandLine.h"
857
858/// Enable/disable ARC sequence annotations.
859static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000860EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
861 cl::desc("Enable emission of arc data flow analysis "
862 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000863static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000864DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
865 cl::desc("Disable check for cfg hazards when "
866 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000867static cl::opt<std::string>
868ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
869 cl::init(""),
870 cl::desc("filter out all data flow annotations "
871 "but those that apply to the given "
872 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000873
874/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
875/// instruction so that we can track backwards when post processing via the llvm
876/// arc annotation processor tool. If the function is an
877static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
878 Value *Ptr) {
879 MDString *Hash = 0;
880
881 // If pointer is a result of an instruction and it does not have a source
882 // MDNode it, attach a new MDNode onto it. If pointer is a result of
883 // an instruction and does have a source MDNode attached to it, return a
884 // reference to said Node. Otherwise just return 0.
885 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
886 MDNode *Node;
887 if (!(Node = Inst->getMetadata(NodeId))) {
888 // We do not have any node. Generate and attatch the hash MDString to the
889 // instruction.
890
891 // We just use an MDString to ensure that this metadata gets written out
892 // of line at the module level and to provide a very simple format
893 // encoding the information herein. Both of these makes it simpler to
894 // parse the annotations by a simple external program.
895 std::string Str;
896 raw_string_ostream os(Str);
897 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
898 << Inst->getName() << ")";
899
900 Hash = MDString::get(Inst->getContext(), os.str());
901 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
902 } else {
903 // We have a node. Grab its hash and return it.
904 assert(Node->getNumOperands() == 1 &&
905 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
906 Hash = cast<MDString>(Node->getOperand(0));
907 }
908 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
909 std::string str;
910 raw_string_ostream os(str);
911 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
912 << ")";
913 Hash = MDString::get(Arg->getContext(), os.str());
914 }
915
916 return Hash;
917}
918
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000919static std::string SequenceToString(Sequence A) {
920 std::string str;
921 raw_string_ostream os(str);
922 os << A;
923 return os.str();
924}
925
Michael Gottesman81b1d432013-03-26 00:42:04 +0000926/// Helper function to change a Sequence into a String object using our overload
927/// for raw_ostream so we only have printing code in one location.
928static MDString *SequenceToMDString(LLVMContext &Context,
929 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000930 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000931}
932
933/// A simple function to generate a MDNode which describes the change in state
934/// for Value *Ptr caused by Instruction *Inst.
935static void AppendMDNodeToInstForPtr(unsigned NodeId,
936 Instruction *Inst,
937 Value *Ptr,
938 MDString *PtrSourceMDNodeID,
939 Sequence OldSeq,
940 Sequence NewSeq) {
941 MDNode *Node = 0;
942 Value *tmp[3] = {PtrSourceMDNodeID,
943 SequenceToMDString(Inst->getContext(),
944 OldSeq),
945 SequenceToMDString(Inst->getContext(),
946 NewSeq)};
947 Node = MDNode::get(Inst->getContext(),
948 ArrayRef<Value*>(tmp, 3));
949
950 Inst->setMetadata(NodeId, Node);
951}
952
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000953/// Add to the beginning of the basic block llvm.ptr.annotations which show the
954/// state of a pointer at the entrance to a basic block.
955static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
956 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000957 // If we have a target identifier, make sure that we match it before
958 // continuing.
959 if(!ARCAnnotationTargetIdentifier.empty() &&
960 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
961 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000962
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000963 Module *M = BB->getParent()->getParent();
964 LLVMContext &C = M->getContext();
965 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
966 Type *I8XX = PointerType::getUnqual(I8X);
967 Type *Params[] = {I8XX, I8XX};
968 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
969 ArrayRef<Type*>(Params, 2),
970 /*isVarArg=*/false);
971 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000972
973 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
974
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000975 Value *PtrName;
976 StringRef Tmp = Ptr->getName();
977 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
978 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
979 Tmp + "_STR");
980 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000981 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000982 }
983
984 Value *S;
985 std::string SeqStr = SequenceToString(Seq);
986 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
987 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
988 SeqStr + "_STR");
989 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
990 cast<Constant>(ActualPtrName), SeqStr);
991 }
992
993 Builder.CreateCall2(Callee, PtrName, S);
994}
995
996/// Add to the end of the basic block llvm.ptr.annotations which show the state
997/// of the pointer at the bottom of the basic block.
998static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
999 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001000 // If we have a target identifier, make sure that we match it before emitting
1001 // an annotation.
1002 if(!ARCAnnotationTargetIdentifier.empty() &&
1003 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1004 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001005
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001006 Module *M = BB->getParent()->getParent();
1007 LLVMContext &C = M->getContext();
1008 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1009 Type *I8XX = PointerType::getUnqual(I8X);
1010 Type *Params[] = {I8XX, I8XX};
1011 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
1012 ArrayRef<Type*>(Params, 2),
1013 /*isVarArg=*/false);
1014 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001015
1016 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
1017
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001018 Value *PtrName;
1019 StringRef Tmp = Ptr->getName();
1020 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1021 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1022 Tmp + "_STR");
1023 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +00001024 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001025 }
1026
1027 Value *S;
1028 std::string SeqStr = SequenceToString(Seq);
1029 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1030 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1031 SeqStr + "_STR");
1032 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1033 cast<Constant>(ActualPtrName), SeqStr);
1034 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001035 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001036}
1037
Michael Gottesman81b1d432013-03-26 00:42:04 +00001038/// Adds a source annotation to pointer and a state change annotation to Inst
1039/// referencing the source annotation and the old/new state of pointer.
1040static void GenerateARCAnnotation(unsigned InstMDId,
1041 unsigned PtrMDId,
1042 Instruction *Inst,
1043 Value *Ptr,
1044 Sequence OldSeq,
1045 Sequence NewSeq) {
1046 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001047 // If we have a target identifier, make sure that we match it before
1048 // emitting an annotation.
1049 if(!ARCAnnotationTargetIdentifier.empty() &&
1050 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1051 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001052
Michael Gottesman81b1d432013-03-26 00:42:04 +00001053 // First generate the source annotation on our pointer. This will return an
1054 // MDString* if Ptr actually comes from an instruction implying we can put
1055 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1056 // then we know that our pointer is from an Argument so we put a reference
1057 // to the argument number.
1058 //
1059 // The point of this is to make it easy for the
1060 // llvm-arc-annotation-processor tool to cross reference where the source
1061 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1062 // information via debug info for backends to use (since why would anyone
1063 // need such a thing from LLVM IR besides in non standard cases
1064 // [i.e. this]).
1065 MDString *SourcePtrMDNode =
1066 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1067 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1068 NewSeq);
1069 }
1070}
1071
1072// The actual interface for accessing the above functionality is defined via
1073// some simple macros which are defined below. We do this so that the user does
1074// not need to pass in what metadata id is needed resulting in cleaner code and
1075// additionally since it provides an easy way to conditionally no-op all
1076// annotation support in a non-debug build.
1077
1078/// Use this macro to annotate a sequence state change when processing
1079/// instructions bottom up,
1080#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1081 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1082 ARCAnnotationProvenanceSourceMDKind, (inst), \
1083 const_cast<Value*>(ptr), (old), (new))
1084/// Use this macro to annotate a sequence state change when processing
1085/// instructions top down.
1086#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1087 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1088 ARCAnnotationProvenanceSourceMDKind, (inst), \
1089 const_cast<Value*>(ptr), (old), (new))
1090
Michael Gottesman43e7e002013-04-03 22:41:59 +00001091#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1092 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001093 if (EnableARCAnnotations) { \
1094 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001095 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001096 Value *Ptr = const_cast<Value*>(I->first); \
1097 Sequence Seq = I->second.GetSeq(); \
1098 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1099 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001100 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001101 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001102
Michael Gottesman89279f82013-04-05 18:10:41 +00001103#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001104 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1105 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001106#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1107 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001108 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001109#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1110 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001111 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001112#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1113 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001114 Terminator, top_down)
1115
Michael Gottesman81b1d432013-03-26 00:42:04 +00001116#else // !ARC_ANNOTATION
1117// If annotations are off, noop.
1118#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1119#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001120#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1121#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1122#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1123#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001124#endif // !ARC_ANNOTATION
1125
John McCalld935e9c2011-06-15 23:37:01 +00001126namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001127 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001128 class ObjCARCOpt : public FunctionPass {
1129 bool Changed;
1130 ProvenanceAnalysis PA;
Michael Gottesman14acfac2013-07-06 01:39:23 +00001131 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +00001132
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001133 // This is used to track if a pointer is stored into an alloca.
1134 DenseSet<const Value *> MultiOwnersSet;
1135
Michael Gottesman97e3df02013-01-14 00:35:14 +00001136 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001137 bool Run;
1138
Michael Gottesman97e3df02013-01-14 00:35:14 +00001139 /// Flags which determine whether each of the interesting runtine functions
1140 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001141 unsigned UsedInThisFunction;
1142
Michael Gottesman97e3df02013-01-14 00:35:14 +00001143 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001144 unsigned ImpreciseReleaseMDKind;
1145
Michael Gottesman97e3df02013-01-14 00:35:14 +00001146 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001147 unsigned CopyOnEscapeMDKind;
1148
Michael Gottesman97e3df02013-01-14 00:35:14 +00001149 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001150 unsigned NoObjCARCExceptionsMDKind;
1151
Michael Gottesman81b1d432013-03-26 00:42:04 +00001152#ifdef ARC_ANNOTATIONS
1153 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1154 unsigned ARCAnnotationBottomUpMDKind;
1155 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1156 unsigned ARCAnnotationTopDownMDKind;
1157 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1158 unsigned ARCAnnotationProvenanceSourceMDKind;
1159#endif // ARC_ANNOATIONS
1160
Dan Gohman728db492012-01-13 00:39:07 +00001161 bool IsRetainBlockOptimizable(const Instruction *Inst);
1162
John McCalld935e9c2011-06-15 23:37:01 +00001163 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001164 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1165 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001166 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1167 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001168 void OptimizeIndividualCalls(Function &F);
1169
1170 void CheckForCFGHazards(const BasicBlock *BB,
1171 DenseMap<const BasicBlock *, BBState> &BBStates,
1172 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001173 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001174 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001175 MapVector<Value *, RRInfo> &Retains,
1176 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001177 bool VisitBottomUp(BasicBlock *BB,
1178 DenseMap<const BasicBlock *, BBState> &BBStates,
1179 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001180 bool VisitInstructionTopDown(Instruction *Inst,
1181 DenseMap<Value *, RRInfo> &Releases,
1182 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001183 bool VisitTopDown(BasicBlock *BB,
1184 DenseMap<const BasicBlock *, BBState> &BBStates,
1185 DenseMap<Value *, RRInfo> &Releases);
1186 bool Visit(Function &F,
1187 DenseMap<const BasicBlock *, BBState> &BBStates,
1188 MapVector<Value *, RRInfo> &Retains,
1189 DenseMap<Value *, RRInfo> &Releases);
1190
1191 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1192 MapVector<Value *, RRInfo> &Retains,
1193 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001194 SmallVectorImpl<Instruction *> &DeadInsts,
1195 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001196
Michael Gottesman9de6f962013-01-22 21:49:00 +00001197 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1198 MapVector<Value *, RRInfo> &Retains,
1199 DenseMap<Value *, RRInfo> &Releases,
1200 Module *M,
1201 SmallVector<Instruction *, 4> &NewRetains,
1202 SmallVector<Instruction *, 4> &NewReleases,
1203 SmallVector<Instruction *, 8> &DeadInsts,
1204 RRInfo &RetainsToMove,
1205 RRInfo &ReleasesToMove,
1206 Value *Arg,
1207 bool KnownSafe,
1208 bool &AnyPairsCompletelyEliminated);
1209
John McCalld935e9c2011-06-15 23:37:01 +00001210 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1211 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001212 DenseMap<Value *, RRInfo> &Releases,
1213 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001214
1215 void OptimizeWeakCalls(Function &F);
1216
1217 bool OptimizeSequences(Function &F);
1218
1219 void OptimizeReturns(Function &F);
1220
Michael Gottesman9c118152013-04-29 06:16:57 +00001221#ifndef NDEBUG
1222 void GatherStatistics(Function &F, bool AfterOptimization = false);
1223#endif
1224
John McCalld935e9c2011-06-15 23:37:01 +00001225 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1226 virtual bool doInitialization(Module &M);
1227 virtual bool runOnFunction(Function &F);
1228 virtual void releaseMemory();
1229
1230 public:
1231 static char ID;
1232 ObjCARCOpt() : FunctionPass(ID) {
1233 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1234 }
1235 };
1236}
1237
1238char ObjCARCOpt::ID = 0;
1239INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1240 "objc-arc", "ObjC ARC optimization", false, false)
1241INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1242INITIALIZE_PASS_END(ObjCARCOpt,
1243 "objc-arc", "ObjC ARC optimization", false, false)
1244
1245Pass *llvm::createObjCARCOptPass() {
1246 return new ObjCARCOpt();
1247}
1248
1249void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1250 AU.addRequired<ObjCARCAliasAnalysis>();
1251 AU.addRequired<AliasAnalysis>();
1252 // ARC optimization doesn't currently split critical edges.
1253 AU.setPreservesCFG();
1254}
1255
Dan Gohman728db492012-01-13 00:39:07 +00001256bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1257 // Without the magic metadata tag, we have to assume this might be an
1258 // objc_retainBlock call inserted to convert a block pointer to an id,
1259 // in which case it really is needed.
1260 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1261 return false;
1262
1263 // If the pointer "escapes" (not including being used in a call),
1264 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001265 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001266 return false;
1267
1268 // Otherwise, it's not needed.
1269 return true;
1270}
1271
Michael Gottesman97e3df02013-01-14 00:35:14 +00001272/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1273/// not a return value. Or, if it can be paired with an
1274/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001275bool
1276ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001277 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001278 const Value *Arg = GetObjCArg(RetainRV);
1279 ImmutableCallSite CS(Arg);
1280 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001281 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001282 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001283 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001284 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001285 if (&*I == RetainRV)
1286 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001287 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001288 BasicBlock *RetainRVParent = RetainRV->getParent();
1289 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001290 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001291 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001292 if (&*I == RetainRV)
1293 return false;
1294 }
John McCalld935e9c2011-06-15 23:37:01 +00001295 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001296 }
John McCalld935e9c2011-06-15 23:37:01 +00001297
1298 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1299 // pointer. In this case, we can delete the pair.
1300 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1301 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001302 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001303 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1304 GetObjCArg(I) == Arg) {
1305 Changed = true;
1306 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001307
Michael Gottesman89279f82013-04-05 18:10:41 +00001308 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1309 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001310
John McCalld935e9c2011-06-15 23:37:01 +00001311 EraseInstruction(I);
1312 EraseInstruction(RetainRV);
1313 return true;
1314 }
1315 }
1316
1317 // Turn it to a plain objc_retain.
1318 Changed = true;
1319 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001320
Michael Gottesman89279f82013-04-05 18:10:41 +00001321 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001322 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001323 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001324
Michael Gottesman14acfac2013-07-06 01:39:23 +00001325 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1326 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001327
Michael Gottesman89279f82013-04-05 18:10:41 +00001328 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001329
John McCalld935e9c2011-06-15 23:37:01 +00001330 return false;
1331}
1332
Michael Gottesman97e3df02013-01-14 00:35:14 +00001333/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1334/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001335void
Michael Gottesman556ff612013-01-12 01:25:19 +00001336ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1337 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001338 // Check for a return of the pointer value.
1339 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001340 SmallVector<const Value *, 2> Users;
1341 Users.push_back(Ptr);
1342 do {
1343 Ptr = Users.pop_back_val();
1344 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1345 UI != UE; ++UI) {
1346 const User *I = *UI;
1347 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1348 return;
1349 if (isa<BitCastInst>(I))
1350 Users.push_back(I);
1351 }
1352 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001353
1354 Changed = true;
1355 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001356
Michael Gottesman89279f82013-04-05 18:10:41 +00001357 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001358 "objc_autorelease since its operand is not used as a return "
1359 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001360 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001361
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001362 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001363 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
1364 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001365 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001366 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001367
Michael Gottesman89279f82013-04-05 18:10:41 +00001368 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001369
John McCalld935e9c2011-06-15 23:37:01 +00001370}
1371
Michael Gottesman158fdf62013-03-28 20:11:19 +00001372// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1373// calls.
1374//
1375// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1376// does not escape (following the rules of block escaping), strength reduce the
1377// objc_retainBlock to an objc_retain.
1378//
1379// TODO: If an objc_retainBlock call is dominated period by a previous
1380// objc_retainBlock call, strength reduce the objc_retainBlock to an
1381// objc_retain.
1382bool
1383ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1384 InstructionClass &Class) {
1385 assert(GetBasicInstructionClass(Inst) == Class);
1386 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001387
Michael Gottesman158fdf62013-03-28 20:11:19 +00001388 // If we can not optimize Inst, return false.
1389 if (!IsRetainBlockOptimizable(Inst))
1390 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001391
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001392 Changed = true;
1393 ++NumPeeps;
1394
1395 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1396 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001397 CallInst *RetainBlock = cast<CallInst>(Inst);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001398 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1399 RetainBlock->setCalledFunction(NewDecl);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001400 // Remove copy_on_escape metadata.
1401 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1402 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001403 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001404 return true;
1405}
1406
Michael Gottesman97e3df02013-01-14 00:35:14 +00001407/// Visit each call, one at a time, and make simplifications without doing any
1408/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001409void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001410 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001411 // Reset all the flags in preparation for recomputing them.
1412 UsedInThisFunction = 0;
1413
1414 // Visit all objc_* calls in F.
1415 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1416 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001417
John McCalld935e9c2011-06-15 23:37:01 +00001418 InstructionClass Class = GetBasicInstructionClass(Inst);
1419
Michael Gottesman89279f82013-04-05 18:10:41 +00001420 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001421
John McCalld935e9c2011-06-15 23:37:01 +00001422 switch (Class) {
1423 default: break;
1424
1425 // Delete no-op casts. These function calls have special semantics, but
1426 // the semantics are entirely implemented via lowering in the front-end,
1427 // so by the time they reach the optimizer, they are just no-op calls
1428 // which return their argument.
1429 //
1430 // There are gray areas here, as the ability to cast reference-counted
1431 // pointers to raw void* and back allows code to break ARC assumptions,
1432 // however these are currently considered to be unimportant.
1433 case IC_NoopCast:
1434 Changed = true;
1435 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001436 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001437 EraseInstruction(Inst);
1438 continue;
1439
1440 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1441 case IC_StoreWeak:
1442 case IC_LoadWeak:
1443 case IC_LoadWeakRetained:
1444 case IC_InitWeak:
1445 case IC_DestroyWeak: {
1446 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001447 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001448 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001449 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001450 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1451 Constant::getNullValue(Ty),
1452 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001453 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001454 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1455 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001456 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001457 CI->eraseFromParent();
1458 continue;
1459 }
1460 break;
1461 }
1462 case IC_CopyWeak:
1463 case IC_MoveWeak: {
1464 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001465 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1466 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001467 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001468 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001469 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1470 Constant::getNullValue(Ty),
1471 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001472
1473 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001474 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1475 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001476
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001477 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001478 CI->eraseFromParent();
1479 continue;
1480 }
1481 break;
1482 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001483 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001484 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001485 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001486 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001487 break;
1488 case IC_RetainRV:
1489 if (OptimizeRetainRVCall(F, Inst))
1490 continue;
1491 break;
1492 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001493 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001494 break;
1495 }
1496
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001497 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001498 if (IsAutorelease(Class) && Inst->use_empty()) {
1499 CallInst *Call = cast<CallInst>(Inst);
1500 const Value *Arg = Call->getArgOperand(0);
1501 Arg = FindSingleUseIdentifiedObject(Arg);
1502 if (Arg) {
1503 Changed = true;
1504 ++NumAutoreleases;
1505
1506 // Create the declaration lazily.
1507 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +00001508
Michael Gottesman14acfac2013-07-06 01:39:23 +00001509 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1510 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
1511 Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001512 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001513
Michael Gottesman89279f82013-04-05 18:10:41 +00001514 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1515 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1516 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001517
John McCalld935e9c2011-06-15 23:37:01 +00001518 EraseInstruction(Call);
1519 Inst = NewCall;
1520 Class = IC_Release;
1521 }
1522 }
1523
1524 // For functions which can never be passed stack arguments, add
1525 // a tail keyword.
1526 if (IsAlwaysTail(Class)) {
1527 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001528 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1529 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001530 cast<CallInst>(Inst)->setTailCall();
1531 }
1532
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001533 // Ensure that functions that can never have a "tail" keyword due to the
1534 // semantics of ARC truly do not do so.
1535 if (IsNeverTail(Class)) {
1536 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001537 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001538 "\n");
1539 cast<CallInst>(Inst)->setTailCall(false);
1540 }
1541
John McCalld935e9c2011-06-15 23:37:01 +00001542 // Set nounwind as needed.
1543 if (IsNoThrow(Class)) {
1544 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001545 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1546 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001547 cast<CallInst>(Inst)->setDoesNotThrow();
1548 }
1549
1550 if (!IsNoopOnNull(Class)) {
1551 UsedInThisFunction |= 1 << Class;
1552 continue;
1553 }
1554
1555 const Value *Arg = GetObjCArg(Inst);
1556
1557 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001558 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001559 Changed = true;
1560 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001561 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1562 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001563 EraseInstruction(Inst);
1564 continue;
1565 }
1566
1567 // Keep track of which of retain, release, autorelease, and retain_block
1568 // are actually present in this function.
1569 UsedInThisFunction |= 1 << Class;
1570
1571 // If Arg is a PHI, and one or more incoming values to the
1572 // PHI are null, and the call is control-equivalent to the PHI, and there
1573 // are no relevant side effects between the PHI and the call, the call
1574 // could be pushed up to just those paths with non-null incoming values.
1575 // For now, don't bother splitting critical edges for this.
1576 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1577 Worklist.push_back(std::make_pair(Inst, Arg));
1578 do {
1579 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1580 Inst = Pair.first;
1581 Arg = Pair.second;
1582
1583 const PHINode *PN = dyn_cast<PHINode>(Arg);
1584 if (!PN) continue;
1585
1586 // Determine if the PHI has any null operands, or any incoming
1587 // critical edges.
1588 bool HasNull = false;
1589 bool HasCriticalEdges = false;
1590 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1591 Value *Incoming =
1592 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001593 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001594 HasNull = true;
1595 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1596 .getNumSuccessors() != 1) {
1597 HasCriticalEdges = true;
1598 break;
1599 }
1600 }
1601 // If we have null operands and no critical edges, optimize.
1602 if (!HasCriticalEdges && HasNull) {
1603 SmallPtrSet<Instruction *, 4> DependingInstructions;
1604 SmallPtrSet<const BasicBlock *, 4> Visited;
1605
1606 // Check that there is nothing that cares about the reference
1607 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001608 switch (Class) {
1609 case IC_Retain:
1610 case IC_RetainBlock:
1611 // These can always be moved up.
1612 break;
1613 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001614 // These can't be moved across things that care about the retain
1615 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001616 FindDependencies(NeedsPositiveRetainCount, Arg,
1617 Inst->getParent(), Inst,
1618 DependingInstructions, Visited, PA);
1619 break;
1620 case IC_Autorelease:
1621 // These can't be moved across autorelease pool scope boundaries.
1622 FindDependencies(AutoreleasePoolBoundary, Arg,
1623 Inst->getParent(), Inst,
1624 DependingInstructions, Visited, PA);
1625 break;
1626 case IC_RetainRV:
1627 case IC_AutoreleaseRV:
1628 // Don't move these; the RV optimization depends on the autoreleaseRV
1629 // being tail called, and the retainRV being immediately after a call
1630 // (which might still happen if we get lucky with codegen layout, but
1631 // it's not worth taking the chance).
1632 continue;
1633 default:
1634 llvm_unreachable("Invalid dependence flavor");
1635 }
1636
John McCalld935e9c2011-06-15 23:37:01 +00001637 if (DependingInstructions.size() == 1 &&
1638 *DependingInstructions.begin() == PN) {
1639 Changed = true;
1640 ++NumPartialNoops;
1641 // Clone the call into each predecessor that has a non-null value.
1642 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001643 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001644 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1645 Value *Incoming =
1646 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001647 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001648 CallInst *Clone = cast<CallInst>(CInst->clone());
1649 Value *Op = PN->getIncomingValue(i);
1650 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1651 if (Op->getType() != ParamTy)
1652 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1653 Clone->setArgOperand(0, Op);
1654 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001655
Michael Gottesman89279f82013-04-05 18:10:41 +00001656 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001657 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001658 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001659 Worklist.push_back(std::make_pair(Clone, Incoming));
1660 }
1661 }
1662 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001663 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001664 EraseInstruction(CInst);
1665 continue;
1666 }
1667 }
1668 } while (!Worklist.empty());
1669 }
1670}
1671
Michael Gottesman323964c2013-04-18 05:39:45 +00001672/// If we have a top down pointer in the S_Use state, make sure that there are
1673/// no CFG hazards by checking the states of various bottom up pointers.
1674static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1675 const bool SuccSRRIKnownSafe,
1676 PtrState &S,
1677 bool &SomeSuccHasSame,
1678 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001679 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001680 bool &ShouldContinue) {
1681 switch (SuccSSeq) {
1682 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001683 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001684 S.ClearSequenceProgress();
1685 break;
1686 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001687 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001688 ShouldContinue = true;
1689 break;
1690 }
1691 case S_Use:
1692 SomeSuccHasSame = true;
1693 break;
1694 case S_Stop:
1695 case S_Release:
1696 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001697 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001698 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001699 else
1700 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001701 break;
1702 case S_Retain:
1703 llvm_unreachable("bottom-up pointer in retain state!");
1704 case S_None:
1705 llvm_unreachable("This should have been handled earlier.");
1706 }
1707}
1708
1709/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1710/// there are no CFG hazards by checking the states of various bottom up
1711/// pointers.
1712static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1713 const bool SuccSRRIKnownSafe,
1714 PtrState &S,
1715 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001716 bool &AllSuccsHaveSame,
1717 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001718 switch (SuccSSeq) {
1719 case S_CanRelease:
1720 SomeSuccHasSame = true;
1721 break;
1722 case S_Stop:
1723 case S_Release:
1724 case S_MovableRelease:
1725 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001726 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001727 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001728 else
1729 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001730 break;
1731 case S_Retain:
1732 llvm_unreachable("bottom-up pointer in retain state!");
1733 case S_None:
1734 llvm_unreachable("This should have been handled earlier.");
1735 }
1736}
1737
Michael Gottesman97e3df02013-01-14 00:35:14 +00001738/// Check for critical edges, loop boundaries, irreducible control flow, or
1739/// other CFG structures where moving code across the edge would result in it
1740/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001741void
1742ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1743 DenseMap<const BasicBlock *, BBState> &BBStates,
1744 BBState &MyStates) const {
1745 // If any top-down local-use or possible-dec has a succ which is earlier in
1746 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001747 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001748 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1749 PtrState &S = I->second;
1750 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001751
Michael Gottesman323964c2013-04-18 05:39:45 +00001752 // We only care about S_Retain, S_CanRelease, and S_Use.
1753 if (Seq == S_None)
1754 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001755
Michael Gottesman323964c2013-04-18 05:39:45 +00001756 // Make sure that if extra top down states are added in the future that this
1757 // code is updated to handle it.
1758 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1759 "Unknown top down sequence state.");
1760
1761 const Value *Arg = I->first;
1762 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1763 bool SomeSuccHasSame = false;
1764 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001765 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001766
1767 succ_const_iterator SI(TI), SE(TI, false);
1768
1769 for (; SI != SE; ++SI) {
1770 // If VisitBottomUp has pointer information for this successor, take
1771 // what we know about it.
1772 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1773 BBStates.find(*SI);
1774 assert(BBI != BBStates.end());
1775 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1776 const Sequence SuccSSeq = SuccS.GetSeq();
1777
1778 // If bottom up, the pointer is in an S_None state, clear the sequence
1779 // progress since the sequence in the bottom up state finished
1780 // suggesting a mismatch in between retains/releases. This is true for
1781 // all three cases that we are handling here: S_Retain, S_Use, and
1782 // S_CanRelease.
1783 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001784 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001785 continue;
1786 }
1787
1788 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1789 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001790 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001791
1792 // *NOTE* We do not use Seq from above here since we are allowing for
1793 // S.GetSeq() to change while we are visiting basic blocks.
1794 switch(S.GetSeq()) {
1795 case S_Use: {
1796 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001797 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1798 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001799 ShouldContinue);
1800 if (ShouldContinue)
1801 continue;
1802 break;
1803 }
1804 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001805 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1806 SomeSuccHasSame, AllSuccsHaveSame,
1807 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001808 break;
1809 }
1810 case S_Retain:
1811 case S_None:
1812 case S_Stop:
1813 case S_Release:
1814 case S_MovableRelease:
1815 break;
1816 }
John McCalld935e9c2011-06-15 23:37:01 +00001817 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001818
1819 // If the state at the other end of any of the successor edges
1820 // matches the current state, require all edges to match. This
1821 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001822 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001823 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001824 } else if (NotAllSeqEqualButKnownSafe) {
1825 // If we would have cleared the state foregoing the fact that we are known
1826 // safe, stop code motion. This is because whether or not it is safe to
1827 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1828 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001829 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001830 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001831 }
John McCalld935e9c2011-06-15 23:37:01 +00001832}
1833
1834bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001835ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001836 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001837 MapVector<Value *, RRInfo> &Retains,
1838 BBState &MyStates) {
1839 bool NestingDetected = false;
1840 InstructionClass Class = GetInstructionClass(Inst);
1841 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001842
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001843 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001844
Dan Gohman817a7c62012-03-22 18:24:56 +00001845 switch (Class) {
1846 case IC_Release: {
1847 Arg = GetObjCArg(Inst);
1848
1849 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1850
1851 // If we see two releases in a row on the same pointer. If so, make
1852 // a note, and we'll cicle back to revisit it after we've
1853 // hopefully eliminated the second release, which may allow us to
1854 // eliminate the first release too.
1855 // Theoretically we could implement removal of nested retain+release
1856 // pairs by making PtrState hold a stack of states, but this is
1857 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001858 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001859 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001860 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001861 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001862
Dan Gohman817a7c62012-03-22 18:24:56 +00001863 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001864 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1865 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1866 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001867 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001868 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001869 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001870 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001871 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001872 break;
1873 }
1874 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001875 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1876 // objc_retainBlocks to objc_retains. Thus at this point any
1877 // objc_retainBlocks that we see are not optimizable.
1878 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001879 case IC_Retain:
1880 case IC_RetainRV: {
1881 Arg = GetObjCArg(Inst);
1882
1883 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001884 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001885
Michael Gottesman81b1d432013-03-26 00:42:04 +00001886 Sequence OldSeq = S.GetSeq();
1887 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001888 case S_Stop:
1889 case S_Release:
1890 case S_MovableRelease:
1891 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001892 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1893 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001894 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001895 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001896 // FALL THROUGH
1897 case S_CanRelease:
1898 // Don't do retain+release tracking for IC_RetainRV, because it's
1899 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001900 if (Class != IC_RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001901 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001902 S.ClearSequenceProgress();
1903 break;
1904 case S_None:
1905 break;
1906 case S_Retain:
1907 llvm_unreachable("bottom-up pointer in retain state!");
1908 }
Michael Gottesman79249972013-04-05 23:46:45 +00001909 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001910 // A retain moving bottom up can be a use.
1911 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001912 }
1913 case IC_AutoreleasepoolPop:
1914 // Conservatively, clear MyStates for all known pointers.
1915 MyStates.clearBottomUpPointers();
1916 return NestingDetected;
1917 case IC_AutoreleasepoolPush:
1918 case IC_None:
1919 // These are irrelevant.
1920 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001921 case IC_User:
1922 // If we have a store into an alloca of a pointer we are tracking, the
1923 // pointer has multiple owners implying that we must be more conservative.
1924 //
1925 // This comes up in the context of a pointer being ``KnownSafe''. In the
1926 // presense of a block being initialized, the frontend will emit the
1927 // objc_retain on the original pointer and the release on the pointer loaded
1928 // from the alloca. The optimizer will through the provenance analysis
1929 // realize that the two are related, but since we only require KnownSafe in
1930 // one direction, will match the inner retain on the original pointer with
1931 // the guard release on the original pointer. This is fixed by ensuring that
1932 // in the presense of allocas we only unconditionally remove pointers if
1933 // both our retain and our release are KnownSafe.
1934 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1935 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1936 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1937 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1938 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001939 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001940 }
1941 }
1942 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001943 default:
1944 break;
1945 }
1946
1947 // Consider any other possible effects of this instruction on each
1948 // pointer being tracked.
1949 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1950 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1951 const Value *Ptr = MI->first;
1952 if (Ptr == Arg)
1953 continue; // Handled above.
1954 PtrState &S = MI->second;
1955 Sequence Seq = S.GetSeq();
1956
1957 // Check for possible releases.
1958 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001959 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1960 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001961 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001962 switch (Seq) {
1963 case S_Use:
1964 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001965 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001966 continue;
1967 case S_CanRelease:
1968 case S_Release:
1969 case S_MovableRelease:
1970 case S_Stop:
1971 case S_None:
1972 break;
1973 case S_Retain:
1974 llvm_unreachable("bottom-up pointer in retain state!");
1975 }
1976 }
1977
1978 // Check for possible direct uses.
1979 switch (Seq) {
1980 case S_Release:
1981 case S_MovableRelease:
1982 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001983 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1984 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001985 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001986 // If this is an invoke instruction, we're scanning it as part of
1987 // one of its successor blocks, since we can't insert code after it
1988 // in its own block, and we don't want to split critical edges.
1989 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001990 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001991 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001992 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001993 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001994 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001995 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001996 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1997 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001998 // Non-movable releases depend on any possible objc pointer use.
1999 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002000 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002001 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002002 // As above; handle invoke specially.
2003 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002004 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002005 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002006 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002007 }
2008 break;
2009 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002010 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002011 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2012 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002013 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002014 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2015 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002016 break;
2017 case S_CanRelease:
2018 case S_Use:
2019 case S_None:
2020 break;
2021 case S_Retain:
2022 llvm_unreachable("bottom-up pointer in retain state!");
2023 }
2024 }
2025
2026 return NestingDetected;
2027}
2028
2029bool
John McCalld935e9c2011-06-15 23:37:01 +00002030ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2031 DenseMap<const BasicBlock *, BBState> &BBStates,
2032 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002033
2034 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002035
John McCalld935e9c2011-06-15 23:37:01 +00002036 bool NestingDetected = false;
2037 BBState &MyStates = BBStates[BB];
2038
2039 // Merge the states from each successor to compute the initial state
2040 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002041 BBState::edge_iterator SI(MyStates.succ_begin()),
2042 SE(MyStates.succ_end());
2043 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002044 const BasicBlock *Succ = *SI;
2045 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2046 assert(I != BBStates.end());
2047 MyStates.InitFromSucc(I->second);
2048 ++SI;
2049 for (; SI != SE; ++SI) {
2050 Succ = *SI;
2051 I = BBStates.find(Succ);
2052 assert(I != BBStates.end());
2053 MyStates.MergeSucc(I->second);
2054 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002055 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002056
Michael Gottesman43e7e002013-04-03 22:41:59 +00002057 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002058 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002059 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002060
John McCalld935e9c2011-06-15 23:37:01 +00002061 // Visit all the instructions, bottom-up.
2062 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2063 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002064
2065 // Invoke instructions are visited as part of their successors (below).
2066 if (isa<InvokeInst>(Inst))
2067 continue;
2068
Michael Gottesman89279f82013-04-05 18:10:41 +00002069 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002070
Dan Gohman5c70fad2012-03-23 17:47:54 +00002071 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2072 }
2073
Dan Gohmandae33492012-04-27 18:56:31 +00002074 // If there's a predecessor with an invoke, visit the invoke as if it were
2075 // part of this block, since we can't insert code after an invoke in its own
2076 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002077 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2078 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002079 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002080 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2081 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002082 }
John McCalld935e9c2011-06-15 23:37:01 +00002083
Michael Gottesman43e7e002013-04-03 22:41:59 +00002084 // If ARC Annotations are enabled, output the current state of pointers at the
2085 // top of the basic block.
2086 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002087
Dan Gohman817a7c62012-03-22 18:24:56 +00002088 return NestingDetected;
2089}
John McCalld935e9c2011-06-15 23:37:01 +00002090
Dan Gohman817a7c62012-03-22 18:24:56 +00002091bool
2092ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2093 DenseMap<Value *, RRInfo> &Releases,
2094 BBState &MyStates) {
2095 bool NestingDetected = false;
2096 InstructionClass Class = GetInstructionClass(Inst);
2097 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002098
Dan Gohman817a7c62012-03-22 18:24:56 +00002099 switch (Class) {
2100 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002101 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2102 // objc_retainBlocks to objc_retains. Thus at this point any
2103 // objc_retainBlocks that we see are not optimizable.
2104 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002105 case IC_Retain:
2106 case IC_RetainRV: {
2107 Arg = GetObjCArg(Inst);
2108
2109 PtrState &S = MyStates.getPtrTopDownState(Arg);
2110
2111 // Don't do retain+release tracking for IC_RetainRV, because it's
2112 // better to let it remain as the first instruction after a call.
2113 if (Class != IC_RetainRV) {
2114 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002115 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002116 // hopefully eliminated the second retain, which may allow us to
2117 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002118 // Theoretically we could implement removal of nested retain+release
2119 // pairs by making PtrState hold a stack of states, but this is
2120 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002121 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002122 NestingDetected = true;
2123
Michael Gottesman81b1d432013-03-26 00:42:04 +00002124 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002125 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002126 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002127 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002128 }
John McCalld935e9c2011-06-15 23:37:01 +00002129
Dan Gohmandf476e52012-09-04 23:16:20 +00002130 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002131
2132 // A retain can be a potential use; procede to the generic checking
2133 // code below.
2134 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002135 }
2136 case IC_Release: {
2137 Arg = GetObjCArg(Inst);
2138
2139 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002140 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002141
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002142 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002143
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002144 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002145
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002146 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002147 case S_Retain:
2148 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002149 if (OldSeq == S_Retain || ReleaseMetadata != 0)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002150 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00002151 // FALL THROUGH
2152 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00002153 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002154 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00002155 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00002156 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002157 S.ClearSequenceProgress();
2158 break;
2159 case S_None:
2160 break;
2161 case S_Stop:
2162 case S_Release:
2163 case S_MovableRelease:
2164 llvm_unreachable("top-down pointer in release state!");
2165 }
2166 break;
2167 }
2168 case IC_AutoreleasepoolPop:
2169 // Conservatively, clear MyStates for all known pointers.
2170 MyStates.clearTopDownPointers();
2171 return NestingDetected;
2172 case IC_AutoreleasepoolPush:
2173 case IC_None:
2174 // These are irrelevant.
2175 return NestingDetected;
2176 default:
2177 break;
2178 }
2179
2180 // Consider any other possible effects of this instruction on each
2181 // pointer being tracked.
2182 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2183 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2184 const Value *Ptr = MI->first;
2185 if (Ptr == Arg)
2186 continue; // Handled above.
2187 PtrState &S = MI->second;
2188 Sequence Seq = S.GetSeq();
2189
2190 // Check for possible releases.
2191 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002192 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002193 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002194 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002195 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002196 case S_Retain:
2197 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002198 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002199 assert(!S.HasReverseInsertPts());
2200 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00002201
2202 // One call can't cause a transition from S_Retain to S_CanRelease
2203 // and S_CanRelease to S_Use. If we've made the first transition,
2204 // we're done.
2205 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002206 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002207 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002208 case S_None:
2209 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002210 case S_Stop:
2211 case S_Release:
2212 case S_MovableRelease:
2213 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002214 }
2215 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002216
2217 // Check for possible direct uses.
2218 switch (Seq) {
2219 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002220 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002221 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2222 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002223 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002224 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2225 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002226 break;
2227 case S_Retain:
2228 case S_Use:
2229 case S_None:
2230 break;
2231 case S_Stop:
2232 case S_Release:
2233 case S_MovableRelease:
2234 llvm_unreachable("top-down pointer in release state!");
2235 }
John McCalld935e9c2011-06-15 23:37:01 +00002236 }
2237
2238 return NestingDetected;
2239}
2240
2241bool
2242ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2243 DenseMap<const BasicBlock *, BBState> &BBStates,
2244 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002245 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002246 bool NestingDetected = false;
2247 BBState &MyStates = BBStates[BB];
2248
2249 // Merge the states from each predecessor to compute the initial state
2250 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002251 BBState::edge_iterator PI(MyStates.pred_begin()),
2252 PE(MyStates.pred_end());
2253 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002254 const BasicBlock *Pred = *PI;
2255 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2256 assert(I != BBStates.end());
2257 MyStates.InitFromPred(I->second);
2258 ++PI;
2259 for (; PI != PE; ++PI) {
2260 Pred = *PI;
2261 I = BBStates.find(Pred);
2262 assert(I != BBStates.end());
2263 MyStates.MergePred(I->second);
2264 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002265 }
John McCalld935e9c2011-06-15 23:37:01 +00002266
Michael Gottesman43e7e002013-04-03 22:41:59 +00002267 // If ARC Annotations are enabled, output the current state of pointers at the
2268 // top of the basic block.
2269 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002270
John McCalld935e9c2011-06-15 23:37:01 +00002271 // Visit all the instructions, top-down.
2272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2273 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002274
Michael Gottesman89279f82013-04-05 18:10:41 +00002275 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002276
Dan Gohman817a7c62012-03-22 18:24:56 +00002277 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002278 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002279
Michael Gottesman43e7e002013-04-03 22:41:59 +00002280 // If ARC Annotations are enabled, output the current state of pointers at the
2281 // bottom of the basic block.
2282 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002283
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002284#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002285 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002286#endif
John McCalld935e9c2011-06-15 23:37:01 +00002287 CheckForCFGHazards(BB, BBStates, MyStates);
2288 return NestingDetected;
2289}
2290
Dan Gohmana53a12c2011-12-12 19:42:25 +00002291static void
2292ComputePostOrders(Function &F,
2293 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002294 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2295 unsigned NoObjCARCExceptionsMDKind,
2296 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002297 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002298 SmallPtrSet<BasicBlock *, 16> Visited;
2299
2300 // Do DFS, computing the PostOrder.
2301 SmallPtrSet<BasicBlock *, 16> OnStack;
2302 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002303
2304 // Functions always have exactly one entry block, and we don't have
2305 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002306 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002307 BBState &MyStates = BBStates[EntryBB];
2308 MyStates.SetAsEntry();
2309 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2310 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002311 Visited.insert(EntryBB);
2312 OnStack.insert(EntryBB);
2313 do {
2314 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002315 BasicBlock *CurrBB = SuccStack.back().first;
2316 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2317 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002318
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002319 while (SuccStack.back().second != SE) {
2320 BasicBlock *SuccBB = *SuccStack.back().second++;
2321 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002322 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2323 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002324 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002325 BBState &SuccStates = BBStates[SuccBB];
2326 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002327 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002328 goto dfs_next_succ;
2329 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002330
2331 if (!OnStack.count(SuccBB)) {
2332 BBStates[CurrBB].addSucc(SuccBB);
2333 BBStates[SuccBB].addPred(CurrBB);
2334 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002335 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002336 OnStack.erase(CurrBB);
2337 PostOrder.push_back(CurrBB);
2338 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002339 } while (!SuccStack.empty());
2340
2341 Visited.clear();
2342
Dan Gohmana53a12c2011-12-12 19:42:25 +00002343 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002344 // Functions may have many exits, and there also blocks which we treat
2345 // as exits due to ignored edges.
2346 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2347 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2348 BasicBlock *ExitBB = I;
2349 BBState &MyStates = BBStates[ExitBB];
2350 if (!MyStates.isExit())
2351 continue;
2352
Dan Gohmandae33492012-04-27 18:56:31 +00002353 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002354
2355 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002356 Visited.insert(ExitBB);
2357 while (!PredStack.empty()) {
2358 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002359 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2360 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002361 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002362 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002363 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002364 goto reverse_dfs_next_succ;
2365 }
2366 }
2367 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2368 }
2369 }
2370}
2371
Michael Gottesman97e3df02013-01-14 00:35:14 +00002372// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002373bool
2374ObjCARCOpt::Visit(Function &F,
2375 DenseMap<const BasicBlock *, BBState> &BBStates,
2376 MapVector<Value *, RRInfo> &Retains,
2377 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002378
2379 // Use reverse-postorder traversals, because we magically know that loops
2380 // will be well behaved, i.e. they won't repeatedly call retain on a single
2381 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2382 // class here because we want the reverse-CFG postorder to consider each
2383 // function exit point, and we want to ignore selected cycle edges.
2384 SmallVector<BasicBlock *, 16> PostOrder;
2385 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002386 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2387 NoObjCARCExceptionsMDKind,
2388 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002389
2390 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002391 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002392 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002393 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2394 I != E; ++I)
2395 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002396
Dan Gohmana53a12c2011-12-12 19:42:25 +00002397 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002398 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002399 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2400 PostOrder.rbegin(), E = PostOrder.rend();
2401 I != E; ++I)
2402 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002403
2404 return TopDownNestingDetected && BottomUpNestingDetected;
2405}
2406
Michael Gottesman97e3df02013-01-14 00:35:14 +00002407/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002408void ObjCARCOpt::MoveCalls(Value *Arg,
2409 RRInfo &RetainsToMove,
2410 RRInfo &ReleasesToMove,
2411 MapVector<Value *, RRInfo> &Retains,
2412 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002413 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002414 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002415 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002416 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002417
Michael Gottesman89279f82013-04-05 18:10:41 +00002418 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002419
John McCalld935e9c2011-06-15 23:37:01 +00002420 // Insert the new retain and release calls.
2421 for (SmallPtrSet<Instruction *, 2>::const_iterator
2422 PI = ReleasesToMove.ReverseInsertPts.begin(),
2423 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2424 Instruction *InsertPt = *PI;
2425 Value *MyArg = ArgTy == ParamTy ? Arg :
2426 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002427 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2428 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002429 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002430 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002431
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002432 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002433 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002434 }
2435 for (SmallPtrSet<Instruction *, 2>::const_iterator
2436 PI = RetainsToMove.ReverseInsertPts.begin(),
2437 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002438 Instruction *InsertPt = *PI;
2439 Value *MyArg = ArgTy == ParamTy ? Arg :
2440 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002441 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
2442 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002443 // Attach a clang.imprecise_release metadata tag, if appropriate.
2444 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2445 Call->setMetadata(ImpreciseReleaseMDKind, M);
2446 Call->setDoesNotThrow();
2447 if (ReleasesToMove.IsTailCallRelease)
2448 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002449
Michael Gottesman89279f82013-04-05 18:10:41 +00002450 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2451 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002452 }
2453
2454 // Delete the original retain and release calls.
2455 for (SmallPtrSet<Instruction *, 2>::const_iterator
2456 AI = RetainsToMove.Calls.begin(),
2457 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2458 Instruction *OrigRetain = *AI;
2459 Retains.blot(OrigRetain);
2460 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002461 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002462 }
2463 for (SmallPtrSet<Instruction *, 2>::const_iterator
2464 AI = ReleasesToMove.Calls.begin(),
2465 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2466 Instruction *OrigRelease = *AI;
2467 Releases.erase(OrigRelease);
2468 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002469 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002470 }
Michael Gottesman79249972013-04-05 23:46:45 +00002471
John McCalld935e9c2011-06-15 23:37:01 +00002472}
2473
Michael Gottesman9de6f962013-01-22 21:49:00 +00002474bool
2475ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2476 &BBStates,
2477 MapVector<Value *, RRInfo> &Retains,
2478 DenseMap<Value *, RRInfo> &Releases,
2479 Module *M,
2480 SmallVector<Instruction *, 4> &NewRetains,
2481 SmallVector<Instruction *, 4> &NewReleases,
2482 SmallVector<Instruction *, 8> &DeadInsts,
2483 RRInfo &RetainsToMove,
2484 RRInfo &ReleasesToMove,
2485 Value *Arg,
2486 bool KnownSafe,
2487 bool &AnyPairsCompletelyEliminated) {
2488 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002489 // is already incremented, we can similarly ignore possible decrements unless
2490 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002491 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002492 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002493 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002494
2495 // Connect the dots between the top-down-collected RetainsToMove and
2496 // bottom-up-collected ReleasesToMove to form sets of related calls.
2497 // This is an iterative process so that we connect multiple releases
2498 // to multiple retains if needed.
2499 unsigned OldDelta = 0;
2500 unsigned NewDelta = 0;
2501 unsigned OldCount = 0;
2502 unsigned NewCount = 0;
2503 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002504 for (;;) {
2505 for (SmallVectorImpl<Instruction *>::const_iterator
2506 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2507 Instruction *NewRetain = *NI;
2508 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2509 assert(It != Retains.end());
2510 const RRInfo &NewRetainRRI = It->second;
2511 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002512 MultipleOwners =
2513 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002514 for (SmallPtrSet<Instruction *, 2>::const_iterator
2515 LI = NewRetainRRI.Calls.begin(),
2516 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2517 Instruction *NewRetainRelease = *LI;
2518 DenseMap<Value *, RRInfo>::const_iterator Jt =
2519 Releases.find(NewRetainRelease);
2520 if (Jt == Releases.end())
2521 return false;
2522 const RRInfo &NewRetainReleaseRRI = Jt->second;
2523 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2524 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002525
2526 // If we overflow when we compute the path count, don't remove/move
2527 // anything.
2528 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2529 unsigned PathCount;
2530 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2531 return false;
2532 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002533
2534 // Merge the ReleaseMetadata and IsTailCallRelease values.
2535 if (FirstRelease) {
2536 ReleasesToMove.ReleaseMetadata =
2537 NewRetainReleaseRRI.ReleaseMetadata;
2538 ReleasesToMove.IsTailCallRelease =
2539 NewRetainReleaseRRI.IsTailCallRelease;
2540 FirstRelease = false;
2541 } else {
2542 if (ReleasesToMove.ReleaseMetadata !=
2543 NewRetainReleaseRRI.ReleaseMetadata)
2544 ReleasesToMove.ReleaseMetadata = 0;
2545 if (ReleasesToMove.IsTailCallRelease !=
2546 NewRetainReleaseRRI.IsTailCallRelease)
2547 ReleasesToMove.IsTailCallRelease = false;
2548 }
2549
2550 // Collect the optimal insertion points.
2551 if (!KnownSafe)
2552 for (SmallPtrSet<Instruction *, 2>::const_iterator
2553 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2554 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2555 RI != RE; ++RI) {
2556 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002557 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2558 // If we overflow when we compute the path count, don't
2559 // remove/move anything.
2560 const BBState &RIPBBState = BBStates[RIP->getParent()];
2561 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2562 return false;
2563 NewDelta -= PathCount;
2564 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002565 }
2566 NewReleases.push_back(NewRetainRelease);
2567 }
2568 }
2569 }
2570 NewRetains.clear();
2571 if (NewReleases.empty()) break;
2572
2573 // Back the other way.
2574 for (SmallVectorImpl<Instruction *>::const_iterator
2575 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2576 Instruction *NewRelease = *NI;
2577 DenseMap<Value *, RRInfo>::const_iterator It =
2578 Releases.find(NewRelease);
2579 assert(It != Releases.end());
2580 const RRInfo &NewReleaseRRI = It->second;
2581 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002582 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002583 for (SmallPtrSet<Instruction *, 2>::const_iterator
2584 LI = NewReleaseRRI.Calls.begin(),
2585 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2586 Instruction *NewReleaseRetain = *LI;
2587 MapVector<Value *, RRInfo>::const_iterator Jt =
2588 Retains.find(NewReleaseRetain);
2589 if (Jt == Retains.end())
2590 return false;
2591 const RRInfo &NewReleaseRetainRRI = Jt->second;
2592 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2593 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002594
2595 // If we overflow when we compute the path count, don't remove/move
2596 // anything.
2597 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2598 unsigned PathCount;
2599 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2600 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002601 OldDelta += PathCount;
2602 OldCount += PathCount;
2603
Michael Gottesman9de6f962013-01-22 21:49:00 +00002604 // Collect the optimal insertion points.
2605 if (!KnownSafe)
2606 for (SmallPtrSet<Instruction *, 2>::const_iterator
2607 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2608 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2609 RI != RE; ++RI) {
2610 Instruction *RIP = *RI;
2611 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002612 // If we overflow when we compute the path count, don't
2613 // remove/move anything.
2614 const BBState &RIPBBState = BBStates[RIP->getParent()];
2615 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2616 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002617 NewDelta += PathCount;
2618 NewCount += PathCount;
2619 }
2620 }
2621 NewRetains.push_back(NewReleaseRetain);
2622 }
2623 }
2624 }
2625 NewReleases.clear();
2626 if (NewRetains.empty()) break;
2627 }
2628
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002629 // If the pointer is known incremented in 1 direction and we do not have
2630 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2631 // to be known safe in both directions.
2632 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2633 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2634 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002635 RetainsToMove.ReverseInsertPts.clear();
2636 ReleasesToMove.ReverseInsertPts.clear();
2637 NewCount = 0;
2638 } else {
2639 // Determine whether the new insertion points we computed preserve the
2640 // balance of retain and release calls through the program.
2641 // TODO: If the fully aggressive solution isn't valid, try to find a
2642 // less aggressive solution which is.
2643 if (NewDelta != 0)
2644 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002645
2646 // At this point, we are not going to remove any RR pairs, but we still are
2647 // able to move RR pairs. If one of our pointers is afflicted with
2648 // CFGHazards, we cannot perform such code motion so exit early.
2649 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2650 ReleasesToMove.ReverseInsertPts.size();
2651 if (CFGHazardAfflicted && WillPerformCodeMotion)
2652 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002653 }
2654
2655 // Determine whether the original call points are balanced in the retain and
2656 // release calls through the program. If not, conservatively don't touch
2657 // them.
2658 // TODO: It's theoretically possible to do code motion in this case, as
2659 // long as the existing imbalances are maintained.
2660 if (OldDelta != 0)
2661 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002662
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002663#ifdef ARC_ANNOTATIONS
2664 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002665 if (EnableARCAnnotations)
2666 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002667#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002668
2669 Changed = true;
2670 assert(OldCount != 0 && "Unreachable code?");
2671 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002672 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002673 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002674
2675 // We can move calls!
2676 return true;
2677}
2678
Michael Gottesman97e3df02013-01-14 00:35:14 +00002679/// Identify pairings between the retains and releases, and delete and/or move
2680/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002681bool
2682ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2683 &BBStates,
2684 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002685 DenseMap<Value *, RRInfo> &Releases,
2686 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002687 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2688
John McCalld935e9c2011-06-15 23:37:01 +00002689 bool AnyPairsCompletelyEliminated = false;
2690 RRInfo RetainsToMove;
2691 RRInfo ReleasesToMove;
2692 SmallVector<Instruction *, 4> NewRetains;
2693 SmallVector<Instruction *, 4> NewReleases;
2694 SmallVector<Instruction *, 8> DeadInsts;
2695
Dan Gohman670f9372012-04-13 18:57:48 +00002696 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002697 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002698 E = Retains.end(); I != E; ++I) {
2699 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002700 if (!V) continue; // blotted
2701
2702 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002703
Michael Gottesman89279f82013-04-05 18:10:41 +00002704 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002705
John McCalld935e9c2011-06-15 23:37:01 +00002706 Value *Arg = GetObjCArg(Retain);
2707
Dan Gohman728db492012-01-13 00:39:07 +00002708 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002709 // not being managed by ObjC reference counting, so we can delete pairs
2710 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002711 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002712
Dan Gohman56e1cef2011-08-22 17:29:11 +00002713 // A constant pointer can't be pointing to an object on the heap. It may
2714 // be reference-counted, but it won't be deleted.
2715 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2716 if (const GlobalVariable *GV =
2717 dyn_cast<GlobalVariable>(
2718 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2719 if (GV->isConstant())
2720 KnownSafe = true;
2721
John McCalld935e9c2011-06-15 23:37:01 +00002722 // Connect the dots between the top-down-collected RetainsToMove and
2723 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002724 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002725 bool PerformMoveCalls =
2726 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2727 NewReleases, DeadInsts, RetainsToMove,
2728 ReleasesToMove, Arg, KnownSafe,
2729 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002730
Michael Gottesman9de6f962013-01-22 21:49:00 +00002731 if (PerformMoveCalls) {
2732 // Ok, everything checks out and we're all set. Let's move/delete some
2733 // code!
2734 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2735 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002736 }
2737
Michael Gottesman9de6f962013-01-22 21:49:00 +00002738 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002739 NewReleases.clear();
2740 NewRetains.clear();
2741 RetainsToMove.clear();
2742 ReleasesToMove.clear();
2743 }
2744
2745 // Now that we're done moving everything, we can delete the newly dead
2746 // instructions, as we no longer need them as insert points.
2747 while (!DeadInsts.empty())
2748 EraseInstruction(DeadInsts.pop_back_val());
2749
2750 return AnyPairsCompletelyEliminated;
2751}
2752
Michael Gottesman97e3df02013-01-14 00:35:14 +00002753/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002754void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002755 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002756
John McCalld935e9c2011-06-15 23:37:01 +00002757 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2758 // itself because it uses AliasAnalysis and we need to do provenance
2759 // queries instead.
2760 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2761 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002762
Michael Gottesman89279f82013-04-05 18:10:41 +00002763 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002764
John McCalld935e9c2011-06-15 23:37:01 +00002765 InstructionClass Class = GetBasicInstructionClass(Inst);
2766 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2767 continue;
2768
2769 // Delete objc_loadWeak calls with no users.
2770 if (Class == IC_LoadWeak && Inst->use_empty()) {
2771 Inst->eraseFromParent();
2772 continue;
2773 }
2774
2775 // TODO: For now, just look for an earlier available version of this value
2776 // within the same block. Theoretically, we could do memdep-style non-local
2777 // analysis too, but that would want caching. A better approach would be to
2778 // use the technique that EarlyCSE uses.
2779 inst_iterator Current = llvm::prior(I);
2780 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2781 for (BasicBlock::iterator B = CurrentBB->begin(),
2782 J = Current.getInstructionIterator();
2783 J != B; --J) {
2784 Instruction *EarlierInst = &*llvm::prior(J);
2785 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2786 switch (EarlierClass) {
2787 case IC_LoadWeak:
2788 case IC_LoadWeakRetained: {
2789 // If this is loading from the same pointer, replace this load's value
2790 // with that one.
2791 CallInst *Call = cast<CallInst>(Inst);
2792 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2793 Value *Arg = Call->getArgOperand(0);
2794 Value *EarlierArg = EarlierCall->getArgOperand(0);
2795 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2796 case AliasAnalysis::MustAlias:
2797 Changed = true;
2798 // If the load has a builtin retain, insert a plain retain for it.
2799 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002800 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2801 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002802 CI->setTailCall();
2803 }
2804 // Zap the fully redundant load.
2805 Call->replaceAllUsesWith(EarlierCall);
2806 Call->eraseFromParent();
2807 goto clobbered;
2808 case AliasAnalysis::MayAlias:
2809 case AliasAnalysis::PartialAlias:
2810 goto clobbered;
2811 case AliasAnalysis::NoAlias:
2812 break;
2813 }
2814 break;
2815 }
2816 case IC_StoreWeak:
2817 case IC_InitWeak: {
2818 // If this is storing to the same pointer and has the same size etc.
2819 // replace this load's value with the stored value.
2820 CallInst *Call = cast<CallInst>(Inst);
2821 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2822 Value *Arg = Call->getArgOperand(0);
2823 Value *EarlierArg = EarlierCall->getArgOperand(0);
2824 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2825 case AliasAnalysis::MustAlias:
2826 Changed = true;
2827 // If the load has a builtin retain, insert a plain retain for it.
2828 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002829 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2830 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002831 CI->setTailCall();
2832 }
2833 // Zap the fully redundant load.
2834 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2835 Call->eraseFromParent();
2836 goto clobbered;
2837 case AliasAnalysis::MayAlias:
2838 case AliasAnalysis::PartialAlias:
2839 goto clobbered;
2840 case AliasAnalysis::NoAlias:
2841 break;
2842 }
2843 break;
2844 }
2845 case IC_MoveWeak:
2846 case IC_CopyWeak:
2847 // TOOD: Grab the copied value.
2848 goto clobbered;
2849 case IC_AutoreleasepoolPush:
2850 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002851 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002852 case IC_User:
2853 // Weak pointers are only modified through the weak entry points
2854 // (and arbitrary calls, which could call the weak entry points).
2855 break;
2856 default:
2857 // Anything else could modify the weak pointer.
2858 goto clobbered;
2859 }
2860 }
2861 clobbered:;
2862 }
2863
2864 // Then, for each destroyWeak with an alloca operand, check to see if
2865 // the alloca and all its users can be zapped.
2866 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2867 Instruction *Inst = &*I++;
2868 InstructionClass Class = GetBasicInstructionClass(Inst);
2869 if (Class != IC_DestroyWeak)
2870 continue;
2871
2872 CallInst *Call = cast<CallInst>(Inst);
2873 Value *Arg = Call->getArgOperand(0);
2874 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2875 for (Value::use_iterator UI = Alloca->use_begin(),
2876 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002877 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002878 switch (GetBasicInstructionClass(UserInst)) {
2879 case IC_InitWeak:
2880 case IC_StoreWeak:
2881 case IC_DestroyWeak:
2882 continue;
2883 default:
2884 goto done;
2885 }
2886 }
2887 Changed = true;
2888 for (Value::use_iterator UI = Alloca->use_begin(),
2889 UE = Alloca->use_end(); UI != UE; ) {
2890 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002891 switch (GetBasicInstructionClass(UserInst)) {
2892 case IC_InitWeak:
2893 case IC_StoreWeak:
2894 // These functions return their second argument.
2895 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2896 break;
2897 case IC_DestroyWeak:
2898 // No return value.
2899 break;
2900 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002901 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002902 }
John McCalld935e9c2011-06-15 23:37:01 +00002903 UserInst->eraseFromParent();
2904 }
2905 Alloca->eraseFromParent();
2906 done:;
2907 }
2908 }
2909}
2910
Michael Gottesman97e3df02013-01-14 00:35:14 +00002911/// Identify program paths which execute sequences of retains and releases which
2912/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002913bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002914 // Releases, Retains - These are used to store the results of the main flow
2915 // analysis. These use Value* as the key instead of Instruction* so that the
2916 // map stays valid when we get around to rewriting code and calls get
2917 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002918 DenseMap<Value *, RRInfo> Releases;
2919 MapVector<Value *, RRInfo> Retains;
2920
Michael Gottesman740db972013-05-23 02:35:21 +00002921 // This is used during the traversal of the function to track the
2922 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002923 DenseMap<const BasicBlock *, BBState> BBStates;
2924
2925 // Analyze the CFG of the function, and all instructions.
2926 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2927
2928 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002929 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2930 Releases,
2931 F.getParent());
2932
2933 // Cleanup.
2934 MultiOwnersSet.clear();
2935
2936 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002937}
2938
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002939/// Check if there is a dependent call earlier that does not have anything in
2940/// between the Retain and the call that can affect the reference count of their
2941/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002942static bool
2943HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2944 SmallPtrSet<Instruction *, 4> &DepInsts,
2945 SmallPtrSet<const BasicBlock *, 4> &Visited,
2946 ProvenanceAnalysis &PA) {
2947 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2948 DepInsts, Visited, PA);
2949 if (DepInsts.size() != 1)
2950 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002951
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002952 CallInst *Call =
2953 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002954
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002955 // Check that the pointer is the return value of the call.
2956 if (!Call || Arg != Call)
2957 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002958
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002959 // Check that the call is a regular call.
2960 InstructionClass Class = GetBasicInstructionClass(Call);
2961 if (Class != IC_CallOrUser && Class != IC_Call)
2962 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002963
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002964 return true;
2965}
2966
Michael Gottesman6908db12013-04-03 23:16:05 +00002967/// Find a dependent retain that precedes the given autorelease for which there
2968/// is nothing in between the two instructions that can affect the ref count of
2969/// Arg.
2970static CallInst *
2971FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2972 Instruction *Autorelease,
2973 SmallPtrSet<Instruction *, 4> &DepInsts,
2974 SmallPtrSet<const BasicBlock *, 4> &Visited,
2975 ProvenanceAnalysis &PA) {
2976 FindDependencies(CanChangeRetainCount, Arg,
2977 BB, Autorelease, DepInsts, Visited, PA);
2978 if (DepInsts.size() != 1)
2979 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002980
Michael Gottesman6908db12013-04-03 23:16:05 +00002981 CallInst *Retain =
2982 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002983
Michael Gottesman6908db12013-04-03 23:16:05 +00002984 // Check that we found a retain with the same argument.
2985 if (!Retain ||
2986 !IsRetain(GetBasicInstructionClass(Retain)) ||
2987 GetObjCArg(Retain) != Arg) {
2988 return 0;
2989 }
Michael Gottesman79249972013-04-05 23:46:45 +00002990
Michael Gottesman6908db12013-04-03 23:16:05 +00002991 return Retain;
2992}
2993
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002994/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2995/// no instructions dependent on Arg that need a positive ref count in between
2996/// the autorelease and the ret.
2997static CallInst *
2998FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2999 ReturnInst *Ret,
3000 SmallPtrSet<Instruction *, 4> &DepInsts,
3001 SmallPtrSet<const BasicBlock *, 4> &V,
3002 ProvenanceAnalysis &PA) {
3003 FindDependencies(NeedsPositiveRetainCount, Arg,
3004 BB, Ret, DepInsts, V, PA);
3005 if (DepInsts.size() != 1)
3006 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003007
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003008 CallInst *Autorelease =
3009 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3010 if (!Autorelease)
3011 return 0;
3012 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3013 if (!IsAutorelease(AutoreleaseClass))
3014 return 0;
3015 if (GetObjCArg(Autorelease) != Arg)
3016 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003017
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003018 return Autorelease;
3019}
3020
Michael Gottesman97e3df02013-01-14 00:35:14 +00003021/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003022/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003023/// %call = call i8* @something(...)
3024/// %2 = call i8* @objc_retain(i8* %call)
3025/// %3 = call i8* @objc_autorelease(i8* %2)
3026/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003027/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003028/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003029void ObjCARCOpt::OptimizeReturns(Function &F) {
3030 if (!F.getReturnType()->isPointerTy())
3031 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003032
Michael Gottesman89279f82013-04-05 18:10:41 +00003033 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003034
John McCalld935e9c2011-06-15 23:37:01 +00003035 SmallPtrSet<Instruction *, 4> DependingInstructions;
3036 SmallPtrSet<const BasicBlock *, 4> Visited;
3037 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3038 BasicBlock *BB = FI;
3039 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003040
Michael Gottesman89279f82013-04-05 18:10:41 +00003041 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003042
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003043 if (!Ret)
3044 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003045
John McCalld935e9c2011-06-15 23:37:01 +00003046 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003047
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003048 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003049 // dependent on Arg such that there are no instructions dependent on Arg
3050 // that need a positive ref count in between the autorelease and Ret.
3051 CallInst *Autorelease =
3052 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3053 DependingInstructions, Visited,
3054 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003055 DependingInstructions.clear();
3056 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003057
3058 if (!Autorelease)
3059 continue;
3060
3061 CallInst *Retain =
3062 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3063 DependingInstructions, Visited, PA);
3064 DependingInstructions.clear();
3065 Visited.clear();
3066
3067 if (!Retain)
3068 continue;
3069
3070 // Check that there is nothing that can affect the reference count
3071 // between the retain and the call. Note that Retain need not be in BB.
3072 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3073 DependingInstructions,
3074 Visited, PA);
3075 DependingInstructions.clear();
3076 Visited.clear();
3077
3078 if (!HasSafePathToCall)
3079 continue;
3080
3081 // If so, we can zap the retain and autorelease.
3082 Changed = true;
3083 ++NumRets;
3084 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3085 << *Autorelease << "\n");
3086 EraseInstruction(Retain);
3087 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003088 }
3089}
3090
Michael Gottesman9c118152013-04-29 06:16:57 +00003091#ifndef NDEBUG
3092void
3093ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3094 llvm::Statistic &NumRetains =
3095 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3096 llvm::Statistic &NumReleases =
3097 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3098
3099 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3100 Instruction *Inst = &*I++;
3101 switch (GetBasicInstructionClass(Inst)) {
3102 default:
3103 break;
3104 case IC_Retain:
3105 ++NumRetains;
3106 break;
3107 case IC_Release:
3108 ++NumReleases;
3109 break;
3110 }
3111 }
3112}
3113#endif
3114
John McCalld935e9c2011-06-15 23:37:01 +00003115bool ObjCARCOpt::doInitialization(Module &M) {
3116 if (!EnableARCOpts)
3117 return false;
3118
Dan Gohman670f9372012-04-13 18:57:48 +00003119 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003120 Run = ModuleHasARC(M);
3121 if (!Run)
3122 return false;
3123
John McCalld935e9c2011-06-15 23:37:01 +00003124 // Identify the imprecise release metadata kind.
3125 ImpreciseReleaseMDKind =
3126 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003127 CopyOnEscapeMDKind =
3128 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003129 NoObjCARCExceptionsMDKind =
3130 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003131#ifdef ARC_ANNOTATIONS
3132 ARCAnnotationBottomUpMDKind =
3133 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3134 ARCAnnotationTopDownMDKind =
3135 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3136 ARCAnnotationProvenanceSourceMDKind =
3137 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3138#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003139
John McCalld935e9c2011-06-15 23:37:01 +00003140 // Intuitively, objc_retain and others are nocapture, however in practice
3141 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003142 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003143
Michael Gottesman14acfac2013-07-06 01:39:23 +00003144 // Initialize our runtime entry point cache.
3145 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00003146
3147 return false;
3148}
3149
3150bool ObjCARCOpt::runOnFunction(Function &F) {
3151 if (!EnableARCOpts)
3152 return false;
3153
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003154 // If nothing in the Module uses ARC, don't do anything.
3155 if (!Run)
3156 return false;
3157
John McCalld935e9c2011-06-15 23:37:01 +00003158 Changed = false;
3159
Michael Gottesman89279f82013-04-05 18:10:41 +00003160 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3161 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003162
John McCalld935e9c2011-06-15 23:37:01 +00003163 PA.setAA(&getAnalysis<AliasAnalysis>());
3164
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003165#ifndef NDEBUG
3166 if (AreStatisticsEnabled()) {
3167 GatherStatistics(F, false);
3168 }
3169#endif
3170
John McCalld935e9c2011-06-15 23:37:01 +00003171 // This pass performs several distinct transformations. As a compile-time aid
3172 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3173 // library functions aren't declared.
3174
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003175 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003176 OptimizeIndividualCalls(F);
3177
3178 // Optimizations for weak pointers.
3179 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3180 (1 << IC_LoadWeakRetained) |
3181 (1 << IC_StoreWeak) |
3182 (1 << IC_InitWeak) |
3183 (1 << IC_CopyWeak) |
3184 (1 << IC_MoveWeak) |
3185 (1 << IC_DestroyWeak)))
3186 OptimizeWeakCalls(F);
3187
3188 // Optimizations for retain+release pairs.
3189 if (UsedInThisFunction & ((1 << IC_Retain) |
3190 (1 << IC_RetainRV) |
3191 (1 << IC_RetainBlock)))
3192 if (UsedInThisFunction & (1 << IC_Release))
3193 // Run OptimizeSequences until it either stops making changes or
3194 // no retain+release pair nesting is detected.
3195 while (OptimizeSequences(F)) {}
3196
3197 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003198 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3199 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003200 OptimizeReturns(F);
3201
Michael Gottesman9c118152013-04-29 06:16:57 +00003202 // Gather statistics after optimization.
3203#ifndef NDEBUG
3204 if (AreStatisticsEnabled()) {
3205 GatherStatistics(F, true);
3206 }
3207#endif
3208
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003209 DEBUG(dbgs() << "\n");
3210
John McCalld935e9c2011-06-15 23:37:01 +00003211 return Changed;
3212}
3213
3214void ObjCARCOpt::releaseMemory() {
3215 PA.clear();
3216}
3217
Michael Gottesman97e3df02013-01-14 00:35:14 +00003218/// @}
3219///