blob: 727b4f7c96cc27209ffd9c2b4edd7b4c2bf3b52a [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
16/// redundant weak pointer operations, pattern-matching and replacement of
17/// low-level operations into higher-level operations, and numerous minor
18/// simplifications.
19///
20/// This file also defines a simple ARC-aware AliasAnalysis.
21///
22/// WARNING: This file knows about certain library functions. It recognizes them
23/// by name, and hardwires knowledge of their semantics.
24///
25/// WARNING: This file knows about how certain Objective-C library functions are
26/// used. Naive LLVM IR transformations which would otherwise be
27/// behavior-preserving may break these assumptions.
28///
John McCalld935e9c2011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
Michael Gottesman08904e32013-01-28 03:28:38 +000031#define DEBUG_TYPE "objc-arc-opts"
32#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000033#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000034#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000036#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000037#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000041#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000042#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000043#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000044
John McCalld935e9c2011-06-15 23:37:01 +000045using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000046using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000047
Michael Gottesman97e3df02013-01-14 00:35:14 +000048/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
49/// @{
John McCalld935e9c2011-06-15 23:37:01 +000050
51namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000052 /// \brief An associative container with fast insertion-order (deterministic)
53 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000054 template<class KeyT, class ValueT>
55 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000056 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef DenseMap<KeyT, size_t> MapTy;
58 MapTy Map;
59
John McCalld935e9c2011-06-15 23:37:01 +000060 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000061 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000062 VectorTy Vector;
63
64 public:
65 typedef typename VectorTy::iterator iterator;
66 typedef typename VectorTy::const_iterator const_iterator;
67 iterator begin() { return Vector.begin(); }
68 iterator end() { return Vector.end(); }
69 const_iterator begin() const { return Vector.begin(); }
70 const_iterator end() const { return Vector.end(); }
71
72#ifdef XDEBUG
73 ~MapVector() {
74 assert(Vector.size() >= Map.size()); // May differ due to blotting.
75 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
76 I != E; ++I) {
77 assert(I->second < Vector.size());
78 assert(Vector[I->second].first == I->first);
79 }
80 for (typename VectorTy::const_iterator I = Vector.begin(),
81 E = Vector.end(); I != E; ++I)
82 assert(!I->first ||
83 (Map.count(I->first) &&
84 Map[I->first] == size_t(I - Vector.begin())));
85 }
86#endif
87
Dan Gohman55b06742012-03-02 01:13:53 +000088 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000089 std::pair<typename MapTy::iterator, bool> Pair =
90 Map.insert(std::make_pair(Arg, size_t(0)));
91 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000092 size_t Num = Vector.size();
93 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000094 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000095 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000096 }
97 return Vector[Pair.first->second].second;
98 }
99
100 std::pair<iterator, bool>
101 insert(const std::pair<KeyT, ValueT> &InsertPair) {
102 std::pair<typename MapTy::iterator, bool> Pair =
103 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
104 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000105 size_t Num = Vector.size();
106 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000107 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000108 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000109 }
110 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 }
112
Dan Gohman55b06742012-03-02 01:13:53 +0000113 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000114 typename MapTy::const_iterator It = Map.find(Key);
115 if (It == Map.end()) return Vector.end();
116 return Vector.begin() + It->second;
117 }
118
Michael Gottesman97e3df02013-01-14 00:35:14 +0000119 /// This is similar to erase, but instead of removing the element from the
120 /// vector, it just zeros out the key in the vector. This leaves iterators
121 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000122 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000123 typename MapTy::iterator It = Map.find(Key);
124 if (It == Map.end()) return;
125 Vector[It->second].first = KeyT();
126 Map.erase(It);
127 }
128
129 void clear() {
130 Map.clear();
131 Vector.clear();
132 }
133 };
134}
135
Michael Gottesman97e3df02013-01-14 00:35:14 +0000136/// @}
137///
138/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
139/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000140
Michael Gottesman97e3df02013-01-14 00:35:14 +0000141/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
142/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000143static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
144 if (Arg->hasOneUse()) {
145 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
146 return FindSingleUseIdentifiedObject(BC->getOperand(0));
147 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
148 if (GEP->hasAllZeroIndices())
149 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
150 if (IsForwarding(GetBasicInstructionClass(Arg)))
151 return FindSingleUseIdentifiedObject(
152 cast<CallInst>(Arg)->getArgOperand(0));
153 if (!IsObjCIdentifiedObject(Arg))
154 return 0;
155 return Arg;
156 }
157
Dan Gohman41375a32012-05-08 23:39:44 +0000158 // If we found an identifiable object but it has multiple uses, but they are
159 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000160 if (IsObjCIdentifiedObject(Arg)) {
161 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
162 UI != UE; ++UI) {
163 const User *U = *UI;
164 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
165 return 0;
166 }
167
168 return Arg;
169 }
170
171 return 0;
172}
173
Michael Gottesman774d2c02013-01-29 21:00:52 +0000174/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000175///
176/// This differs from regular escape analysis in that a use as an
177/// argument to a call is not considered an escape.
178///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000179static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000180
Michael Gottesman774d2c02013-01-29 21:00:52 +0000181 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000182
Dan Gohman728db492012-01-13 00:39:07 +0000183 // Walk the def-use chains.
184 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 Worklist.push_back(Ptr);
186 // If Ptr has any operands add them as well.
187 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E; ++I) {
188 Worklist.push_back(*I);
189 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000190
191 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000192 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000193
Dan Gohman728db492012-01-13 00:39:07 +0000194 do {
195 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000196
Michael Gottesman774d2c02013-01-29 21:00:52 +0000197 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000198
Dan Gohman728db492012-01-13 00:39:07 +0000199 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
200 UI != UE; ++UI) {
201 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000202
Michael Gottesman774d2c02013-01-29 21:00:52 +0000203 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000204
Dan Gohman728db492012-01-13 00:39:07 +0000205 // Special - Use by a call (callee or argument) is not considered
206 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000207 switch (GetBasicInstructionClass(UUser)) {
208 case IC_StoreWeak:
209 case IC_InitWeak:
210 case IC_StoreStrong:
211 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000212 case IC_AutoreleaseRV: {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000213 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies pointer arguments. "
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000214 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000215 // These special functions make copies of their pointer arguments.
216 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000217 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 case IC_User:
219 case IC_None:
220 // Use by an instruction which copies the value is an escape if the
221 // result is an escape.
222 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
223 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000224
Michael Gottesmane9145d32013-01-14 19:18:39 +0000225 if (!VisitedSet.insert(UUser)) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000226 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies value. Escapes "
Michael Gottesman4385edf2013-01-14 01:47:53 +0000227 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000228 Worklist.push_back(UUser);
229 } else {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000230 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000231 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000232 continue;
233 }
234 // Use by a load is not an escape.
235 if (isa<LoadInst>(UUser))
236 continue;
237 // Use by a store is not an escape if the use is the address.
238 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
239 if (V != SI->getValueOperand())
240 continue;
241 break;
242 default:
243 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000244 continue;
245 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000246 // Otherwise, conservatively assume an escape.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000247 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000248 return true;
249 }
250 } while (!Worklist.empty());
251
252 // No escapes found.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000253 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000254 return false;
255}
256
Michael Gottesman97e3df02013-01-14 00:35:14 +0000257/// @}
258///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000259/// \defgroup ARCOpt ARC Optimization.
260/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000261
262// TODO: On code like this:
263//
264// objc_retain(%x)
265// stuff_that_cannot_release()
266// objc_autorelease(%x)
267// stuff_that_cannot_release()
268// objc_retain(%x)
269// stuff_that_cannot_release()
270// objc_autorelease(%x)
271//
272// The second retain and autorelease can be deleted.
273
274// TODO: It should be possible to delete
275// objc_autoreleasePoolPush and objc_autoreleasePoolPop
276// pairs if nothing is actually autoreleased between them. Also, autorelease
277// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
278// after inlining) can be turned into plain release calls.
279
280// TODO: Critical-edge splitting. If the optimial insertion point is
281// a critical edge, the current algorithm has to fail, because it doesn't
282// know how to split edges. It should be possible to make the optimizer
283// think in terms of edges, rather than blocks, and then split critical
284// edges on demand.
285
286// TODO: OptimizeSequences could generalized to be Interprocedural.
287
288// TODO: Recognize that a bunch of other objc runtime calls have
289// non-escaping arguments and non-releasing arguments, and may be
290// non-autoreleasing.
291
292// TODO: Sink autorelease calls as far as possible. Unfortunately we
293// usually can't sink them past other calls, which would be the main
294// case where it would be useful.
295
Dan Gohmanb3894012011-08-19 00:26:36 +0000296// TODO: The pointer returned from objc_loadWeakRetained is retained.
297
298// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000299
John McCalld935e9c2011-06-15 23:37:01 +0000300STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
301STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
302STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
303STATISTIC(NumRets, "Number of return value forwarding "
304 "retain+autoreleaes eliminated");
305STATISTIC(NumRRs, "Number of retain+release paths eliminated");
306STATISTIC(NumPeeps, "Number of calls peephole-optimized");
307
308namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000309 /// \enum Sequence
310 ///
311 /// \brief A sequence of states that a pointer may go through in which an
312 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000313 enum Sequence {
314 S_None,
315 S_Retain, ///< objc_retain(x)
316 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
317 S_Use, ///< any use of x
318 S_Stop, ///< like S_Release, but code motion is stopped
319 S_Release, ///< objc_release(x)
320 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
321 };
322}
323
324static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
325 // The easy cases.
326 if (A == B)
327 return A;
328 if (A == S_None || B == S_None)
329 return S_None;
330
John McCalld935e9c2011-06-15 23:37:01 +0000331 if (A > B) std::swap(A, B);
332 if (TopDown) {
333 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000334 if ((A == S_Retain || A == S_CanRelease) &&
335 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000336 return B;
337 } else {
338 // Choose the side which is further along in the sequence.
339 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000340 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000341 return A;
342 // If both sides are releases, choose the more conservative one.
343 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
344 return A;
345 if (A == S_Release && B == S_MovableRelease)
346 return A;
347 }
348
349 return S_None;
350}
351
352namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000353 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000354 /// retain-decrement-use-release sequence or release-use-decrement-retain
355 /// reverese sequence.
356 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000357 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000358 /// object is known to be positive. Similarly, before an objc_release, the
359 /// reference count of the referenced object is known to be positive. If
360 /// there are retain-release pairs in code regions where the retain count
361 /// is known to be positive, they can be eliminated, regardless of any side
362 /// effects between them.
363 ///
364 /// Also, a retain+release pair nested within another retain+release
365 /// pair all on the known same pointer value can be eliminated, regardless
366 /// of any intervening side effects.
367 ///
368 /// KnownSafe is true when either of these conditions is satisfied.
369 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000370
Michael Gottesman97e3df02013-01-14 00:35:14 +0000371 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
372 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +0000373 bool IsRetainBlock;
374
Michael Gottesman97e3df02013-01-14 00:35:14 +0000375 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000376 bool IsTailCallRelease;
377
Michael Gottesman97e3df02013-01-14 00:35:14 +0000378 /// If the Calls are objc_release calls and they all have a
379 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000380 MDNode *ReleaseMetadata;
381
Michael Gottesman97e3df02013-01-14 00:35:14 +0000382 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000383 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
384 SmallPtrSet<Instruction *, 2> Calls;
385
Michael Gottesman97e3df02013-01-14 00:35:14 +0000386 /// The set of optimal insert positions for moving calls in the opposite
387 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000388 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
389
390 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +0000391 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +0000392 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +0000393 ReleaseMetadata(0) {}
394
395 void clear();
396 };
397}
398
399void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000400 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000401 IsRetainBlock = false;
402 IsTailCallRelease = false;
403 ReleaseMetadata = 0;
404 Calls.clear();
405 ReverseInsertPts.clear();
406}
407
408namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000409 /// \brief This class summarizes several per-pointer runtime properties which
410 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000411 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000412 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000413 bool KnownPositiveRefCount;
414
Michael Gottesman97e3df02013-01-14 00:35:14 +0000415 /// True of we've seen an opportunity for partial RR elimination, such as
416 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000417 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000418
Michael Gottesman97e3df02013-01-14 00:35:14 +0000419 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000420 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000421
422 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000423 /// Unidirectional information about the current sequence.
424 ///
John McCalld935e9c2011-06-15 23:37:01 +0000425 /// TODO: Encapsulate this better.
426 RRInfo RRI;
427
Dan Gohmandf476e52012-09-04 23:16:20 +0000428 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000429 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000430
Dan Gohman62079b42012-04-25 00:50:46 +0000431 void SetKnownPositiveRefCount() {
432 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000433 }
434
Dan Gohman62079b42012-04-25 00:50:46 +0000435 void ClearRefCount() {
436 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000437 }
438
John McCalld935e9c2011-06-15 23:37:01 +0000439 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000440 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000441 }
442
443 void SetSeq(Sequence NewSeq) {
444 Seq = NewSeq;
445 }
446
John McCalld935e9c2011-06-15 23:37:01 +0000447 Sequence GetSeq() const {
448 return Seq;
449 }
450
451 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000452 ResetSequenceProgress(S_None);
453 }
454
455 void ResetSequenceProgress(Sequence NewSeq) {
456 Seq = NewSeq;
457 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000458 RRI.clear();
459 }
460
461 void Merge(const PtrState &Other, bool TopDown);
462 };
463}
464
465void
466PtrState::Merge(const PtrState &Other, bool TopDown) {
467 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000468 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000469
470 // We can't merge a plain objc_retain with an objc_retainBlock.
471 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
472 Seq = S_None;
473
Dan Gohman1736c142011-10-17 18:48:25 +0000474 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000475 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000476 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000477 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000478 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000479 // If we're doing a merge on a path that's previously seen a partial
480 // merge, conservatively drop the sequence, to avoid doing partial
481 // RR elimination. If the branch predicates for the two merge differ,
482 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000483 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000484 } else {
485 // Conservatively merge the ReleaseMetadata information.
486 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
487 RRI.ReleaseMetadata = 0;
488
Dan Gohmanb3894012011-08-19 00:26:36 +0000489 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000490 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
491 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000492 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000493
494 // Merge the insert point sets. If there are any differences,
495 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000496 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000497 for (SmallPtrSet<Instruction *, 2>::const_iterator
498 I = Other.RRI.ReverseInsertPts.begin(),
499 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000500 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000501 }
502}
503
504namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000505 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000506 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000507 /// The number of unique control paths from the entry which can reach this
508 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000509 unsigned TopDownPathCount;
510
Michael Gottesman97e3df02013-01-14 00:35:14 +0000511 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000512 unsigned BottomUpPathCount;
513
Michael Gottesman97e3df02013-01-14 00:35:14 +0000514 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000515 typedef MapVector<const Value *, PtrState> MapTy;
516
Michael Gottesman97e3df02013-01-14 00:35:14 +0000517 /// The top-down traversal uses this to record information known about a
518 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000519 MapTy PerPtrTopDown;
520
Michael Gottesman97e3df02013-01-14 00:35:14 +0000521 /// The bottom-up traversal uses this to record information known about a
522 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000523 MapTy PerPtrBottomUp;
524
Michael Gottesman97e3df02013-01-14 00:35:14 +0000525 /// Effective predecessors of the current block ignoring ignorable edges and
526 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000527 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000528 /// Effective successors of the current block ignoring ignorable edges and
529 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000530 SmallVector<BasicBlock *, 2> Succs;
531
John McCalld935e9c2011-06-15 23:37:01 +0000532 public:
533 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
534
535 typedef MapTy::iterator ptr_iterator;
536 typedef MapTy::const_iterator ptr_const_iterator;
537
538 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
539 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
540 ptr_const_iterator top_down_ptr_begin() const {
541 return PerPtrTopDown.begin();
542 }
543 ptr_const_iterator top_down_ptr_end() const {
544 return PerPtrTopDown.end();
545 }
546
547 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
548 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
549 ptr_const_iterator bottom_up_ptr_begin() const {
550 return PerPtrBottomUp.begin();
551 }
552 ptr_const_iterator bottom_up_ptr_end() const {
553 return PerPtrBottomUp.end();
554 }
555
Michael Gottesman97e3df02013-01-14 00:35:14 +0000556 /// Mark this block as being an entry block, which has one path from the
557 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000558 void SetAsEntry() { TopDownPathCount = 1; }
559
Michael Gottesman97e3df02013-01-14 00:35:14 +0000560 /// Mark this block as being an exit block, which has one path to an exit by
561 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000562 void SetAsExit() { BottomUpPathCount = 1; }
563
564 PtrState &getPtrTopDownState(const Value *Arg) {
565 return PerPtrTopDown[Arg];
566 }
567
568 PtrState &getPtrBottomUpState(const Value *Arg) {
569 return PerPtrBottomUp[Arg];
570 }
571
572 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000573 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000574 }
575
576 void clearTopDownPointers() {
577 PerPtrTopDown.clear();
578 }
579
580 void InitFromPred(const BBState &Other);
581 void InitFromSucc(const BBState &Other);
582 void MergePred(const BBState &Other);
583 void MergeSucc(const BBState &Other);
584
Michael Gottesman97e3df02013-01-14 00:35:14 +0000585 /// Return the number of possible unique paths from an entry to an exit
586 /// which pass through this block. This is only valid after both the
587 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000588 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000589 assert(TopDownPathCount != 0);
590 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000591 return TopDownPathCount * BottomUpPathCount;
592 }
Dan Gohman12130272011-08-12 00:26:31 +0000593
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000594 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000595 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000596 edge_iterator pred_begin() { return Preds.begin(); }
597 edge_iterator pred_end() { return Preds.end(); }
598 edge_iterator succ_begin() { return Succs.begin(); }
599 edge_iterator succ_end() { return Succs.end(); }
600
601 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
602 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
603
604 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000605 };
606}
607
608void BBState::InitFromPred(const BBState &Other) {
609 PerPtrTopDown = Other.PerPtrTopDown;
610 TopDownPathCount = Other.TopDownPathCount;
611}
612
613void BBState::InitFromSucc(const BBState &Other) {
614 PerPtrBottomUp = Other.PerPtrBottomUp;
615 BottomUpPathCount = Other.BottomUpPathCount;
616}
617
Michael Gottesman97e3df02013-01-14 00:35:14 +0000618/// The top-down traversal uses this to merge information about predecessors to
619/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000620void BBState::MergePred(const BBState &Other) {
621 // Other.TopDownPathCount can be 0, in which case it is either dead or a
622 // loop backedge. Loop backedges are special.
623 TopDownPathCount += Other.TopDownPathCount;
624
Michael Gottesman4385edf2013-01-14 01:47:53 +0000625 // Check for overflow. If we have overflow, fall back to conservative
626 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000627 if (TopDownPathCount < Other.TopDownPathCount) {
628 clearTopDownPointers();
629 return;
630 }
631
John McCalld935e9c2011-06-15 23:37:01 +0000632 // For each entry in the other set, if our set has an entry with the same key,
633 // merge the entries. Otherwise, copy the entry and merge it with an empty
634 // entry.
635 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
636 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
637 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
638 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
639 /*TopDown=*/true);
640 }
641
Dan Gohman7e315fc32011-08-11 21:06:32 +0000642 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000643 // same key, force it to merge with an empty entry.
644 for (ptr_iterator MI = top_down_ptr_begin(),
645 ME = top_down_ptr_end(); MI != ME; ++MI)
646 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
647 MI->second.Merge(PtrState(), /*TopDown=*/true);
648}
649
Michael Gottesman97e3df02013-01-14 00:35:14 +0000650/// The bottom-up traversal uses this to merge information about successors to
651/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000652void BBState::MergeSucc(const BBState &Other) {
653 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
654 // loop backedge. Loop backedges are special.
655 BottomUpPathCount += Other.BottomUpPathCount;
656
Michael Gottesman4385edf2013-01-14 01:47:53 +0000657 // Check for overflow. If we have overflow, fall back to conservative
658 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000659 if (BottomUpPathCount < Other.BottomUpPathCount) {
660 clearBottomUpPointers();
661 return;
662 }
663
John McCalld935e9c2011-06-15 23:37:01 +0000664 // For each entry in the other set, if our set has an entry with the
665 // same key, merge the entries. Otherwise, copy the entry and merge
666 // it with an empty entry.
667 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
668 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
669 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
670 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
671 /*TopDown=*/false);
672 }
673
Dan Gohman7e315fc32011-08-11 21:06:32 +0000674 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000675 // with the same key, force it to merge with an empty entry.
676 for (ptr_iterator MI = bottom_up_ptr_begin(),
677 ME = bottom_up_ptr_end(); MI != ME; ++MI)
678 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
679 MI->second.Merge(PtrState(), /*TopDown=*/false);
680}
681
682namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000683 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000684 class ObjCARCOpt : public FunctionPass {
685 bool Changed;
686 ProvenanceAnalysis PA;
687
Michael Gottesman97e3df02013-01-14 00:35:14 +0000688 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000689 bool Run;
690
Michael Gottesman97e3df02013-01-14 00:35:14 +0000691 /// Declarations for ObjC runtime functions, for use in creating calls to
692 /// them. These are initialized lazily to avoid cluttering up the Module
693 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000694
Michael Gottesman97e3df02013-01-14 00:35:14 +0000695 /// Declaration for ObjC runtime function
696 /// objc_retainAutoreleasedReturnValue.
697 Constant *RetainRVCallee;
698 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
699 Constant *AutoreleaseRVCallee;
700 /// Declaration for ObjC runtime function objc_release.
701 Constant *ReleaseCallee;
702 /// Declaration for ObjC runtime function objc_retain.
703 Constant *RetainCallee;
704 /// Declaration for ObjC runtime function objc_retainBlock.
705 Constant *RetainBlockCallee;
706 /// Declaration for ObjC runtime function objc_autorelease.
707 Constant *AutoreleaseCallee;
708
709 /// Flags which determine whether each of the interesting runtine functions
710 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000711 unsigned UsedInThisFunction;
712
Michael Gottesman97e3df02013-01-14 00:35:14 +0000713 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000714 unsigned ImpreciseReleaseMDKind;
715
Michael Gottesman97e3df02013-01-14 00:35:14 +0000716 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000717 unsigned CopyOnEscapeMDKind;
718
Michael Gottesman97e3df02013-01-14 00:35:14 +0000719 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000720 unsigned NoObjCARCExceptionsMDKind;
721
John McCalld935e9c2011-06-15 23:37:01 +0000722 Constant *getRetainRVCallee(Module *M);
723 Constant *getAutoreleaseRVCallee(Module *M);
724 Constant *getReleaseCallee(Module *M);
725 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +0000726 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000727 Constant *getAutoreleaseCallee(Module *M);
728
Dan Gohman728db492012-01-13 00:39:07 +0000729 bool IsRetainBlockOptimizable(const Instruction *Inst);
730
John McCalld935e9c2011-06-15 23:37:01 +0000731 void OptimizeRetainCall(Function &F, Instruction *Retain);
732 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000733 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
734 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000735 void OptimizeIndividualCalls(Function &F);
736
737 void CheckForCFGHazards(const BasicBlock *BB,
738 DenseMap<const BasicBlock *, BBState> &BBStates,
739 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +0000740 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +0000741 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +0000742 MapVector<Value *, RRInfo> &Retains,
743 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000744 bool VisitBottomUp(BasicBlock *BB,
745 DenseMap<const BasicBlock *, BBState> &BBStates,
746 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000747 bool VisitInstructionTopDown(Instruction *Inst,
748 DenseMap<Value *, RRInfo> &Releases,
749 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000750 bool VisitTopDown(BasicBlock *BB,
751 DenseMap<const BasicBlock *, BBState> &BBStates,
752 DenseMap<Value *, RRInfo> &Releases);
753 bool Visit(Function &F,
754 DenseMap<const BasicBlock *, BBState> &BBStates,
755 MapVector<Value *, RRInfo> &Retains,
756 DenseMap<Value *, RRInfo> &Releases);
757
758 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
759 MapVector<Value *, RRInfo> &Retains,
760 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +0000761 SmallVectorImpl<Instruction *> &DeadInsts,
762 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000763
Michael Gottesman9de6f962013-01-22 21:49:00 +0000764 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
765 MapVector<Value *, RRInfo> &Retains,
766 DenseMap<Value *, RRInfo> &Releases,
767 Module *M,
768 SmallVector<Instruction *, 4> &NewRetains,
769 SmallVector<Instruction *, 4> &NewReleases,
770 SmallVector<Instruction *, 8> &DeadInsts,
771 RRInfo &RetainsToMove,
772 RRInfo &ReleasesToMove,
773 Value *Arg,
774 bool KnownSafe,
775 bool &AnyPairsCompletelyEliminated);
776
John McCalld935e9c2011-06-15 23:37:01 +0000777 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
778 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +0000779 DenseMap<Value *, RRInfo> &Releases,
780 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000781
782 void OptimizeWeakCalls(Function &F);
783
784 bool OptimizeSequences(Function &F);
785
786 void OptimizeReturns(Function &F);
787
788 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
789 virtual bool doInitialization(Module &M);
790 virtual bool runOnFunction(Function &F);
791 virtual void releaseMemory();
792
793 public:
794 static char ID;
795 ObjCARCOpt() : FunctionPass(ID) {
796 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
797 }
798 };
799}
800
801char ObjCARCOpt::ID = 0;
802INITIALIZE_PASS_BEGIN(ObjCARCOpt,
803 "objc-arc", "ObjC ARC optimization", false, false)
804INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
805INITIALIZE_PASS_END(ObjCARCOpt,
806 "objc-arc", "ObjC ARC optimization", false, false)
807
808Pass *llvm::createObjCARCOptPass() {
809 return new ObjCARCOpt();
810}
811
812void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
813 AU.addRequired<ObjCARCAliasAnalysis>();
814 AU.addRequired<AliasAnalysis>();
815 // ARC optimization doesn't currently split critical edges.
816 AU.setPreservesCFG();
817}
818
Dan Gohman728db492012-01-13 00:39:07 +0000819bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
820 // Without the magic metadata tag, we have to assume this might be an
821 // objc_retainBlock call inserted to convert a block pointer to an id,
822 // in which case it really is needed.
823 if (!Inst->getMetadata(CopyOnEscapeMDKind))
824 return false;
825
826 // If the pointer "escapes" (not including being used in a call),
827 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000828 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +0000829 return false;
830
831 // Otherwise, it's not needed.
832 return true;
833}
834
John McCalld935e9c2011-06-15 23:37:01 +0000835Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
836 if (!RetainRVCallee) {
837 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000838 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000839 Type *Params[] = { I8X };
840 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000841 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000842 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
843 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000844 RetainRVCallee =
845 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000846 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000847 }
848 return RetainRVCallee;
849}
850
851Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
852 if (!AutoreleaseRVCallee) {
853 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000854 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000855 Type *Params[] = { I8X };
856 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000857 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000858 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
859 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000860 AutoreleaseRVCallee =
861 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000862 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000863 }
864 return AutoreleaseRVCallee;
865}
866
867Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
868 if (!ReleaseCallee) {
869 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000870 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000871 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000872 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
873 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000874 ReleaseCallee =
875 M->getOrInsertFunction(
876 "objc_release",
877 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000878 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000879 }
880 return ReleaseCallee;
881}
882
883Constant *ObjCARCOpt::getRetainCallee(Module *M) {
884 if (!RetainCallee) {
885 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000886 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000887 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000888 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
889 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000890 RetainCallee =
891 M->getOrInsertFunction(
892 "objc_retain",
893 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000894 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000895 }
896 return RetainCallee;
897}
898
Dan Gohman6320f522011-07-22 22:29:21 +0000899Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
900 if (!RetainBlockCallee) {
901 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000902 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +0000903 // objc_retainBlock is not nounwind because it calls user copy constructors
904 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +0000905 RetainBlockCallee =
906 M->getOrInsertFunction(
907 "objc_retainBlock",
908 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +0000909 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +0000910 }
911 return RetainBlockCallee;
912}
913
John McCalld935e9c2011-06-15 23:37:01 +0000914Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
915 if (!AutoreleaseCallee) {
916 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000917 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000918 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000919 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
920 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000921 AutoreleaseCallee =
922 M->getOrInsertFunction(
923 "objc_autorelease",
924 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000925 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000926 }
927 return AutoreleaseCallee;
928}
929
Michael Gottesman97e3df02013-01-14 00:35:14 +0000930/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
931/// return value.
John McCalld935e9c2011-06-15 23:37:01 +0000932void
933ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +0000934 ImmutableCallSite CS(GetObjCArg(Retain));
935 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +0000936 if (!Call) return;
937 if (Call->getParent() != Retain->getParent()) return;
938
939 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +0000940 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000941 ++I;
942 while (isNoopInstruction(I)) ++I;
943 if (&*I != Retain)
944 return;
945
946 // Turn it to an objc_retainAutoreleasedReturnValue..
947 Changed = true;
948 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000949
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000950 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +0000951 "objc_retain => objc_retainAutoreleasedReturnValue"
952 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000953 " Old: "
954 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000955
John McCalld935e9c2011-06-15 23:37:01 +0000956 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000957
958 DEBUG(dbgs() << " New: "
959 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000960}
961
Michael Gottesman97e3df02013-01-14 00:35:14 +0000962/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
963/// not a return value. Or, if it can be paired with an
964/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000965bool
966ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000967 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +0000968 const Value *Arg = GetObjCArg(RetainRV);
969 ImmutableCallSite CS(Arg);
970 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000971 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000972 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000973 ++I;
974 while (isNoopInstruction(I)) ++I;
975 if (&*I == RetainRV)
976 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000977 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000978 BasicBlock *RetainRVParent = RetainRV->getParent();
979 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000980 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000981 while (isNoopInstruction(I)) ++I;
982 if (&*I == RetainRV)
983 return false;
984 }
John McCalld935e9c2011-06-15 23:37:01 +0000985 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000986 }
John McCalld935e9c2011-06-15 23:37:01 +0000987
988 // Check for being preceded by an objc_autoreleaseReturnValue on the same
989 // pointer. In this case, we can delete the pair.
990 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
991 if (I != Begin) {
992 do --I; while (I != Begin && isNoopInstruction(I));
993 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
994 GetObjCArg(I) == Arg) {
995 Changed = true;
996 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000997
Michael Gottesman5c32ce92013-01-05 17:55:35 +0000998 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
999 << " Erasing " << *RetainRV
1000 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001001
John McCalld935e9c2011-06-15 23:37:01 +00001002 EraseInstruction(I);
1003 EraseInstruction(RetainRV);
1004 return true;
1005 }
1006 }
1007
1008 // Turn it to a plain objc_retain.
1009 Changed = true;
1010 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001011
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001012 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1013 "objc_retainAutoreleasedReturnValue => "
1014 "objc_retain since the operand is not a return value.\n"
1015 " Old: "
1016 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001017
John McCalld935e9c2011-06-15 23:37:01 +00001018 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001019
1020 DEBUG(dbgs() << " New: "
1021 << *RetainRV << "\n");
1022
John McCalld935e9c2011-06-15 23:37:01 +00001023 return false;
1024}
1025
Michael Gottesman97e3df02013-01-14 00:35:14 +00001026/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1027/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001028void
Michael Gottesman556ff612013-01-12 01:25:19 +00001029ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1030 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001031 // Check for a return of the pointer value.
1032 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001033 SmallVector<const Value *, 2> Users;
1034 Users.push_back(Ptr);
1035 do {
1036 Ptr = Users.pop_back_val();
1037 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1038 UI != UE; ++UI) {
1039 const User *I = *UI;
1040 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1041 return;
1042 if (isa<BitCastInst>(I))
1043 Users.push_back(I);
1044 }
1045 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001046
1047 Changed = true;
1048 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001049
1050 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1051 "objc_autoreleaseReturnValue => "
1052 "objc_autorelease since its operand is not used as a return "
1053 "value.\n"
1054 " Old: "
1055 << *AutoreleaseRV << "\n");
1056
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001057 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1058 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001059 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001060 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001061 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001062
Michael Gottesman1bf69082013-01-06 21:07:11 +00001063 DEBUG(dbgs() << " New: "
1064 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001065
John McCalld935e9c2011-06-15 23:37:01 +00001066}
1067
Michael Gottesman97e3df02013-01-14 00:35:14 +00001068/// Visit each call, one at a time, and make simplifications without doing any
1069/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001070void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1071 // Reset all the flags in preparation for recomputing them.
1072 UsedInThisFunction = 0;
1073
1074 // Visit all objc_* calls in F.
1075 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1076 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001077
John McCalld935e9c2011-06-15 23:37:01 +00001078 InstructionClass Class = GetBasicInstructionClass(Inst);
1079
Michael Gottesmand359e062013-01-18 03:08:39 +00001080 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1081 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001082
John McCalld935e9c2011-06-15 23:37:01 +00001083 switch (Class) {
1084 default: break;
1085
1086 // Delete no-op casts. These function calls have special semantics, but
1087 // the semantics are entirely implemented via lowering in the front-end,
1088 // so by the time they reach the optimizer, they are just no-op calls
1089 // which return their argument.
1090 //
1091 // There are gray areas here, as the ability to cast reference-counted
1092 // pointers to raw void* and back allows code to break ARC assumptions,
1093 // however these are currently considered to be unimportant.
1094 case IC_NoopCast:
1095 Changed = true;
1096 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00001097 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1098 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001099 EraseInstruction(Inst);
1100 continue;
1101
1102 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1103 case IC_StoreWeak:
1104 case IC_LoadWeak:
1105 case IC_LoadWeakRetained:
1106 case IC_InitWeak:
1107 case IC_DestroyWeak: {
1108 CallInst *CI = cast<CallInst>(Inst);
1109 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001110 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001111 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001112 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1113 Constant::getNullValue(Ty),
1114 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001115 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001116 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1117 "pointer-to-weak-pointer is undefined behavior.\n"
1118 " Old = " << *CI <<
1119 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00001120 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001121 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001122 CI->eraseFromParent();
1123 continue;
1124 }
1125 break;
1126 }
1127 case IC_CopyWeak:
1128 case IC_MoveWeak: {
1129 CallInst *CI = cast<CallInst>(Inst);
1130 if (isNullOrUndef(CI->getArgOperand(0)) ||
1131 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001132 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001133 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001134 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1135 Constant::getNullValue(Ty),
1136 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001137
1138 llvm::Value *NewValue = UndefValue::get(CI->getType());
1139 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1140 "pointer-to-weak-pointer is undefined behavior.\n"
1141 " Old = " << *CI <<
1142 "\n New = " <<
1143 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001144
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001145 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001146 CI->eraseFromParent();
1147 continue;
1148 }
1149 break;
1150 }
1151 case IC_Retain:
1152 OptimizeRetainCall(F, Inst);
1153 break;
1154 case IC_RetainRV:
1155 if (OptimizeRetainRVCall(F, Inst))
1156 continue;
1157 break;
1158 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001159 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001160 break;
1161 }
1162
1163 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1164 if (IsAutorelease(Class) && Inst->use_empty()) {
1165 CallInst *Call = cast<CallInst>(Inst);
1166 const Value *Arg = Call->getArgOperand(0);
1167 Arg = FindSingleUseIdentifiedObject(Arg);
1168 if (Arg) {
1169 Changed = true;
1170 ++NumAutoreleases;
1171
1172 // Create the declaration lazily.
1173 LLVMContext &C = Inst->getContext();
1174 CallInst *NewCall =
1175 CallInst::Create(getReleaseCallee(F.getParent()),
1176 Call->getArgOperand(0), "", Call);
1177 NewCall->setMetadata(ImpreciseReleaseMDKind,
1178 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001179
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001180 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1181 "objc_autorelease(x) with objc_release(x) since x is "
1182 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00001183 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001184 "\n New: " <<
1185 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001186
John McCalld935e9c2011-06-15 23:37:01 +00001187 EraseInstruction(Call);
1188 Inst = NewCall;
1189 Class = IC_Release;
1190 }
1191 }
1192
1193 // For functions which can never be passed stack arguments, add
1194 // a tail keyword.
1195 if (IsAlwaysTail(Class)) {
1196 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00001197 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1198 " to function since it can never be passed stack args: " << *Inst <<
1199 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001200 cast<CallInst>(Inst)->setTailCall();
1201 }
1202
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001203 // Ensure that functions that can never have a "tail" keyword due to the
1204 // semantics of ARC truly do not do so.
1205 if (IsNeverTail(Class)) {
1206 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001207 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1208 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001209 "\n");
1210 cast<CallInst>(Inst)->setTailCall(false);
1211 }
1212
John McCalld935e9c2011-06-15 23:37:01 +00001213 // Set nounwind as needed.
1214 if (IsNoThrow(Class)) {
1215 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00001216 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1217 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001218 cast<CallInst>(Inst)->setDoesNotThrow();
1219 }
1220
1221 if (!IsNoopOnNull(Class)) {
1222 UsedInThisFunction |= 1 << Class;
1223 continue;
1224 }
1225
1226 const Value *Arg = GetObjCArg(Inst);
1227
1228 // ARC calls with null are no-ops. Delete them.
1229 if (isNullOrUndef(Arg)) {
1230 Changed = true;
1231 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00001232 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1233 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001234 EraseInstruction(Inst);
1235 continue;
1236 }
1237
1238 // Keep track of which of retain, release, autorelease, and retain_block
1239 // are actually present in this function.
1240 UsedInThisFunction |= 1 << Class;
1241
1242 // If Arg is a PHI, and one or more incoming values to the
1243 // PHI are null, and the call is control-equivalent to the PHI, and there
1244 // are no relevant side effects between the PHI and the call, the call
1245 // could be pushed up to just those paths with non-null incoming values.
1246 // For now, don't bother splitting critical edges for this.
1247 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1248 Worklist.push_back(std::make_pair(Inst, Arg));
1249 do {
1250 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1251 Inst = Pair.first;
1252 Arg = Pair.second;
1253
1254 const PHINode *PN = dyn_cast<PHINode>(Arg);
1255 if (!PN) continue;
1256
1257 // Determine if the PHI has any null operands, or any incoming
1258 // critical edges.
1259 bool HasNull = false;
1260 bool HasCriticalEdges = false;
1261 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1262 Value *Incoming =
1263 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1264 if (isNullOrUndef(Incoming))
1265 HasNull = true;
1266 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1267 .getNumSuccessors() != 1) {
1268 HasCriticalEdges = true;
1269 break;
1270 }
1271 }
1272 // If we have null operands and no critical edges, optimize.
1273 if (!HasCriticalEdges && HasNull) {
1274 SmallPtrSet<Instruction *, 4> DependingInstructions;
1275 SmallPtrSet<const BasicBlock *, 4> Visited;
1276
1277 // Check that there is nothing that cares about the reference
1278 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001279 switch (Class) {
1280 case IC_Retain:
1281 case IC_RetainBlock:
1282 // These can always be moved up.
1283 break;
1284 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001285 // These can't be moved across things that care about the retain
1286 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001287 FindDependencies(NeedsPositiveRetainCount, Arg,
1288 Inst->getParent(), Inst,
1289 DependingInstructions, Visited, PA);
1290 break;
1291 case IC_Autorelease:
1292 // These can't be moved across autorelease pool scope boundaries.
1293 FindDependencies(AutoreleasePoolBoundary, Arg,
1294 Inst->getParent(), Inst,
1295 DependingInstructions, Visited, PA);
1296 break;
1297 case IC_RetainRV:
1298 case IC_AutoreleaseRV:
1299 // Don't move these; the RV optimization depends on the autoreleaseRV
1300 // being tail called, and the retainRV being immediately after a call
1301 // (which might still happen if we get lucky with codegen layout, but
1302 // it's not worth taking the chance).
1303 continue;
1304 default:
1305 llvm_unreachable("Invalid dependence flavor");
1306 }
1307
John McCalld935e9c2011-06-15 23:37:01 +00001308 if (DependingInstructions.size() == 1 &&
1309 *DependingInstructions.begin() == PN) {
1310 Changed = true;
1311 ++NumPartialNoops;
1312 // Clone the call into each predecessor that has a non-null value.
1313 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001314 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001315 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1316 Value *Incoming =
1317 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1318 if (!isNullOrUndef(Incoming)) {
1319 CallInst *Clone = cast<CallInst>(CInst->clone());
1320 Value *Op = PN->getIncomingValue(i);
1321 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1322 if (Op->getType() != ParamTy)
1323 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1324 Clone->setArgOperand(0, Op);
1325 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001326
1327 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1328 << *CInst << "\n"
1329 " And inserting "
1330 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001331 Worklist.push_back(std::make_pair(Clone, Incoming));
1332 }
1333 }
1334 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001335 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001336 EraseInstruction(CInst);
1337 continue;
1338 }
1339 }
1340 } while (!Worklist.empty());
1341 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00001342 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00001343}
1344
Michael Gottesman97e3df02013-01-14 00:35:14 +00001345/// Check for critical edges, loop boundaries, irreducible control flow, or
1346/// other CFG structures where moving code across the edge would result in it
1347/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001348void
1349ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1350 DenseMap<const BasicBlock *, BBState> &BBStates,
1351 BBState &MyStates) const {
1352 // If any top-down local-use or possible-dec has a succ which is earlier in
1353 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001354 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001355 E = MyStates.top_down_ptr_end(); I != E; ++I)
1356 switch (I->second.GetSeq()) {
1357 default: break;
1358 case S_Use: {
1359 const Value *Arg = I->first;
1360 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1361 bool SomeSuccHasSame = false;
1362 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001363 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001364 succ_const_iterator SI(TI), SE(TI, false);
1365
Dan Gohman0155f302012-02-17 18:59:53 +00001366 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001367 Sequence SuccSSeq = S_None;
1368 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001369 // If VisitBottomUp has pointer information for this successor, take
1370 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001371 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1372 BBStates.find(*SI);
1373 assert(BBI != BBStates.end());
1374 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1375 SuccSSeq = SuccS.GetSeq();
1376 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001377 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001378 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001379 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001380 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001381 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001382 break;
1383 }
Dan Gohman12130272011-08-12 00:26:31 +00001384 continue;
1385 }
John McCalld935e9c2011-06-15 23:37:01 +00001386 case S_Use:
1387 SomeSuccHasSame = true;
1388 break;
1389 case S_Stop:
1390 case S_Release:
1391 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001392 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001393 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001394 break;
1395 case S_Retain:
1396 llvm_unreachable("bottom-up pointer in retain state!");
1397 }
Dan Gohman12130272011-08-12 00:26:31 +00001398 }
John McCalld935e9c2011-06-15 23:37:01 +00001399 // If the state at the other end of any of the successor edges
1400 // matches the current state, require all edges to match. This
1401 // guards against loops in the middle of a sequence.
1402 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001403 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001404 break;
John McCalld935e9c2011-06-15 23:37:01 +00001405 }
1406 case S_CanRelease: {
1407 const Value *Arg = I->first;
1408 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1409 bool SomeSuccHasSame = false;
1410 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001411 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001412 succ_const_iterator SI(TI), SE(TI, false);
1413
Dan Gohman0155f302012-02-17 18:59:53 +00001414 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001415 Sequence SuccSSeq = S_None;
1416 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001417 // If VisitBottomUp has pointer information for this successor, take
1418 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001419 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1420 BBStates.find(*SI);
1421 assert(BBI != BBStates.end());
1422 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1423 SuccSSeq = SuccS.GetSeq();
1424 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001425 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001426 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001427 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001428 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001429 break;
1430 }
Dan Gohman12130272011-08-12 00:26:31 +00001431 continue;
1432 }
John McCalld935e9c2011-06-15 23:37:01 +00001433 case S_CanRelease:
1434 SomeSuccHasSame = true;
1435 break;
1436 case S_Stop:
1437 case S_Release:
1438 case S_MovableRelease:
1439 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001440 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001441 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001442 break;
1443 case S_Retain:
1444 llvm_unreachable("bottom-up pointer in retain state!");
1445 }
Dan Gohman12130272011-08-12 00:26:31 +00001446 }
John McCalld935e9c2011-06-15 23:37:01 +00001447 // If the state at the other end of any of the successor edges
1448 // matches the current state, require all edges to match. This
1449 // guards against loops in the middle of a sequence.
1450 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001451 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001452 break;
John McCalld935e9c2011-06-15 23:37:01 +00001453 }
1454 }
1455}
1456
1457bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001458ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001459 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001460 MapVector<Value *, RRInfo> &Retains,
1461 BBState &MyStates) {
1462 bool NestingDetected = false;
1463 InstructionClass Class = GetInstructionClass(Inst);
1464 const Value *Arg = 0;
1465
1466 switch (Class) {
1467 case IC_Release: {
1468 Arg = GetObjCArg(Inst);
1469
1470 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1471
1472 // If we see two releases in a row on the same pointer. If so, make
1473 // a note, and we'll cicle back to revisit it after we've
1474 // hopefully eliminated the second release, which may allow us to
1475 // eliminate the first release too.
1476 // Theoretically we could implement removal of nested retain+release
1477 // pairs by making PtrState hold a stack of states, but this is
1478 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001479 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1480 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
1481 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001482 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001483 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001484
Dan Gohman817a7c62012-03-22 18:24:56 +00001485 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00001486 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00001487 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00001488 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00001489 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1490 S.RRI.Calls.insert(Inst);
1491
Dan Gohmandf476e52012-09-04 23:16:20 +00001492 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001493 break;
1494 }
1495 case IC_RetainBlock:
1496 // An objc_retainBlock call with just a use may need to be kept,
1497 // because it may be copying a block from the stack to the heap.
1498 if (!IsRetainBlockOptimizable(Inst))
1499 break;
1500 // FALLTHROUGH
1501 case IC_Retain:
1502 case IC_RetainRV: {
1503 Arg = GetObjCArg(Inst);
1504
1505 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001506 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001507
1508 switch (S.GetSeq()) {
1509 case S_Stop:
1510 case S_Release:
1511 case S_MovableRelease:
1512 case S_Use:
1513 S.RRI.ReverseInsertPts.clear();
1514 // FALL THROUGH
1515 case S_CanRelease:
1516 // Don't do retain+release tracking for IC_RetainRV, because it's
1517 // better to let it remain as the first instruction after a call.
1518 if (Class != IC_RetainRV) {
1519 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
1520 Retains[Inst] = S.RRI;
1521 }
1522 S.ClearSequenceProgress();
1523 break;
1524 case S_None:
1525 break;
1526 case S_Retain:
1527 llvm_unreachable("bottom-up pointer in retain state!");
1528 }
1529 return NestingDetected;
1530 }
1531 case IC_AutoreleasepoolPop:
1532 // Conservatively, clear MyStates for all known pointers.
1533 MyStates.clearBottomUpPointers();
1534 return NestingDetected;
1535 case IC_AutoreleasepoolPush:
1536 case IC_None:
1537 // These are irrelevant.
1538 return NestingDetected;
1539 default:
1540 break;
1541 }
1542
1543 // Consider any other possible effects of this instruction on each
1544 // pointer being tracked.
1545 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1546 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1547 const Value *Ptr = MI->first;
1548 if (Ptr == Arg)
1549 continue; // Handled above.
1550 PtrState &S = MI->second;
1551 Sequence Seq = S.GetSeq();
1552
1553 // Check for possible releases.
1554 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001555 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001556 switch (Seq) {
1557 case S_Use:
1558 S.SetSeq(S_CanRelease);
1559 continue;
1560 case S_CanRelease:
1561 case S_Release:
1562 case S_MovableRelease:
1563 case S_Stop:
1564 case S_None:
1565 break;
1566 case S_Retain:
1567 llvm_unreachable("bottom-up pointer in retain state!");
1568 }
1569 }
1570
1571 // Check for possible direct uses.
1572 switch (Seq) {
1573 case S_Release:
1574 case S_MovableRelease:
1575 if (CanUse(Inst, Ptr, PA, Class)) {
1576 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001577 // If this is an invoke instruction, we're scanning it as part of
1578 // one of its successor blocks, since we can't insert code after it
1579 // in its own block, and we don't want to split critical edges.
1580 if (isa<InvokeInst>(Inst))
1581 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1582 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001583 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001584 S.SetSeq(S_Use);
1585 } else if (Seq == S_Release &&
1586 (Class == IC_User || Class == IC_CallOrUser)) {
1587 // Non-movable releases depend on any possible objc pointer use.
1588 S.SetSeq(S_Stop);
1589 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001590 // As above; handle invoke specially.
1591 if (isa<InvokeInst>(Inst))
1592 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1593 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001594 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001595 }
1596 break;
1597 case S_Stop:
1598 if (CanUse(Inst, Ptr, PA, Class))
1599 S.SetSeq(S_Use);
1600 break;
1601 case S_CanRelease:
1602 case S_Use:
1603 case S_None:
1604 break;
1605 case S_Retain:
1606 llvm_unreachable("bottom-up pointer in retain state!");
1607 }
1608 }
1609
1610 return NestingDetected;
1611}
1612
1613bool
John McCalld935e9c2011-06-15 23:37:01 +00001614ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1615 DenseMap<const BasicBlock *, BBState> &BBStates,
1616 MapVector<Value *, RRInfo> &Retains) {
1617 bool NestingDetected = false;
1618 BBState &MyStates = BBStates[BB];
1619
1620 // Merge the states from each successor to compute the initial state
1621 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001622 BBState::edge_iterator SI(MyStates.succ_begin()),
1623 SE(MyStates.succ_end());
1624 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001625 const BasicBlock *Succ = *SI;
1626 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1627 assert(I != BBStates.end());
1628 MyStates.InitFromSucc(I->second);
1629 ++SI;
1630 for (; SI != SE; ++SI) {
1631 Succ = *SI;
1632 I = BBStates.find(Succ);
1633 assert(I != BBStates.end());
1634 MyStates.MergeSucc(I->second);
1635 }
Dan Gohman0155f302012-02-17 18:59:53 +00001636 }
John McCalld935e9c2011-06-15 23:37:01 +00001637
1638 // Visit all the instructions, bottom-up.
1639 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1640 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001641
1642 // Invoke instructions are visited as part of their successors (below).
1643 if (isa<InvokeInst>(Inst))
1644 continue;
1645
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001646 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
1647
Dan Gohman5c70fad2012-03-23 17:47:54 +00001648 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1649 }
1650
Dan Gohmandae33492012-04-27 18:56:31 +00001651 // If there's a predecessor with an invoke, visit the invoke as if it were
1652 // part of this block, since we can't insert code after an invoke in its own
1653 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001654 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1655 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001656 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001657 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1658 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001659 }
John McCalld935e9c2011-06-15 23:37:01 +00001660
Dan Gohman817a7c62012-03-22 18:24:56 +00001661 return NestingDetected;
1662}
John McCalld935e9c2011-06-15 23:37:01 +00001663
Dan Gohman817a7c62012-03-22 18:24:56 +00001664bool
1665ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1666 DenseMap<Value *, RRInfo> &Releases,
1667 BBState &MyStates) {
1668 bool NestingDetected = false;
1669 InstructionClass Class = GetInstructionClass(Inst);
1670 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001671
Dan Gohman817a7c62012-03-22 18:24:56 +00001672 switch (Class) {
1673 case IC_RetainBlock:
1674 // An objc_retainBlock call with just a use may need to be kept,
1675 // because it may be copying a block from the stack to the heap.
1676 if (!IsRetainBlockOptimizable(Inst))
1677 break;
1678 // FALLTHROUGH
1679 case IC_Retain:
1680 case IC_RetainRV: {
1681 Arg = GetObjCArg(Inst);
1682
1683 PtrState &S = MyStates.getPtrTopDownState(Arg);
1684
1685 // Don't do retain+release tracking for IC_RetainRV, because it's
1686 // better to let it remain as the first instruction after a call.
1687 if (Class != IC_RetainRV) {
1688 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001689 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001690 // hopefully eliminated the second retain, which may allow us to
1691 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001692 // Theoretically we could implement removal of nested retain+release
1693 // pairs by making PtrState hold a stack of states, but this is
1694 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00001695 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00001696 NestingDetected = true;
1697
Dan Gohman62079b42012-04-25 00:50:46 +00001698 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00001699 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00001700 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00001701 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001702 }
John McCalld935e9c2011-06-15 23:37:01 +00001703
Dan Gohmandf476e52012-09-04 23:16:20 +00001704 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001705
1706 // A retain can be a potential use; procede to the generic checking
1707 // code below.
1708 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001709 }
1710 case IC_Release: {
1711 Arg = GetObjCArg(Inst);
1712
1713 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00001714 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001715
1716 switch (S.GetSeq()) {
1717 case S_Retain:
1718 case S_CanRelease:
1719 S.RRI.ReverseInsertPts.clear();
1720 // FALL THROUGH
1721 case S_Use:
1722 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1723 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1724 Releases[Inst] = S.RRI;
1725 S.ClearSequenceProgress();
1726 break;
1727 case S_None:
1728 break;
1729 case S_Stop:
1730 case S_Release:
1731 case S_MovableRelease:
1732 llvm_unreachable("top-down pointer in release state!");
1733 }
1734 break;
1735 }
1736 case IC_AutoreleasepoolPop:
1737 // Conservatively, clear MyStates for all known pointers.
1738 MyStates.clearTopDownPointers();
1739 return NestingDetected;
1740 case IC_AutoreleasepoolPush:
1741 case IC_None:
1742 // These are irrelevant.
1743 return NestingDetected;
1744 default:
1745 break;
1746 }
1747
1748 // Consider any other possible effects of this instruction on each
1749 // pointer being tracked.
1750 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1751 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1752 const Value *Ptr = MI->first;
1753 if (Ptr == Arg)
1754 continue; // Handled above.
1755 PtrState &S = MI->second;
1756 Sequence Seq = S.GetSeq();
1757
1758 // Check for possible releases.
1759 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001760 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001761 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001762 case S_Retain:
1763 S.SetSeq(S_CanRelease);
1764 assert(S.RRI.ReverseInsertPts.empty());
1765 S.RRI.ReverseInsertPts.insert(Inst);
1766
1767 // One call can't cause a transition from S_Retain to S_CanRelease
1768 // and S_CanRelease to S_Use. If we've made the first transition,
1769 // we're done.
1770 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001771 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001772 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001773 case S_None:
1774 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001775 case S_Stop:
1776 case S_Release:
1777 case S_MovableRelease:
1778 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001779 }
1780 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001781
1782 // Check for possible direct uses.
1783 switch (Seq) {
1784 case S_CanRelease:
1785 if (CanUse(Inst, Ptr, PA, Class))
1786 S.SetSeq(S_Use);
1787 break;
1788 case S_Retain:
1789 case S_Use:
1790 case S_None:
1791 break;
1792 case S_Stop:
1793 case S_Release:
1794 case S_MovableRelease:
1795 llvm_unreachable("top-down pointer in release state!");
1796 }
John McCalld935e9c2011-06-15 23:37:01 +00001797 }
1798
1799 return NestingDetected;
1800}
1801
1802bool
1803ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1804 DenseMap<const BasicBlock *, BBState> &BBStates,
1805 DenseMap<Value *, RRInfo> &Releases) {
1806 bool NestingDetected = false;
1807 BBState &MyStates = BBStates[BB];
1808
1809 // Merge the states from each predecessor to compute the initial state
1810 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001811 BBState::edge_iterator PI(MyStates.pred_begin()),
1812 PE(MyStates.pred_end());
1813 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001814 const BasicBlock *Pred = *PI;
1815 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1816 assert(I != BBStates.end());
1817 MyStates.InitFromPred(I->second);
1818 ++PI;
1819 for (; PI != PE; ++PI) {
1820 Pred = *PI;
1821 I = BBStates.find(Pred);
1822 assert(I != BBStates.end());
1823 MyStates.MergePred(I->second);
1824 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001825 }
John McCalld935e9c2011-06-15 23:37:01 +00001826
1827 // Visit all the instructions, top-down.
1828 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1829 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001830
1831 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
1832
Dan Gohman817a7c62012-03-22 18:24:56 +00001833 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001834 }
1835
1836 CheckForCFGHazards(BB, BBStates, MyStates);
1837 return NestingDetected;
1838}
1839
Dan Gohmana53a12c2011-12-12 19:42:25 +00001840static void
1841ComputePostOrders(Function &F,
1842 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001843 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1844 unsigned NoObjCARCExceptionsMDKind,
1845 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001846 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001847 SmallPtrSet<BasicBlock *, 16> Visited;
1848
1849 // Do DFS, computing the PostOrder.
1850 SmallPtrSet<BasicBlock *, 16> OnStack;
1851 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001852
1853 // Functions always have exactly one entry block, and we don't have
1854 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001855 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001856 BBState &MyStates = BBStates[EntryBB];
1857 MyStates.SetAsEntry();
1858 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1859 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001860 Visited.insert(EntryBB);
1861 OnStack.insert(EntryBB);
1862 do {
1863 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001864 BasicBlock *CurrBB = SuccStack.back().first;
1865 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1866 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001867
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001868 while (SuccStack.back().second != SE) {
1869 BasicBlock *SuccBB = *SuccStack.back().second++;
1870 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00001871 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1872 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001873 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001874 BBState &SuccStates = BBStates[SuccBB];
1875 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001876 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001877 goto dfs_next_succ;
1878 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001879
1880 if (!OnStack.count(SuccBB)) {
1881 BBStates[CurrBB].addSucc(SuccBB);
1882 BBStates[SuccBB].addPred(CurrBB);
1883 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001884 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001885 OnStack.erase(CurrBB);
1886 PostOrder.push_back(CurrBB);
1887 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001888 } while (!SuccStack.empty());
1889
1890 Visited.clear();
1891
Dan Gohmana53a12c2011-12-12 19:42:25 +00001892 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001893 // Functions may have many exits, and there also blocks which we treat
1894 // as exits due to ignored edges.
1895 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1896 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1897 BasicBlock *ExitBB = I;
1898 BBState &MyStates = BBStates[ExitBB];
1899 if (!MyStates.isExit())
1900 continue;
1901
Dan Gohmandae33492012-04-27 18:56:31 +00001902 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001903
1904 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001905 Visited.insert(ExitBB);
1906 while (!PredStack.empty()) {
1907 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001908 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1909 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001910 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001911 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001912 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001913 goto reverse_dfs_next_succ;
1914 }
1915 }
1916 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1917 }
1918 }
1919}
1920
Michael Gottesman97e3df02013-01-14 00:35:14 +00001921// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001922bool
1923ObjCARCOpt::Visit(Function &F,
1924 DenseMap<const BasicBlock *, BBState> &BBStates,
1925 MapVector<Value *, RRInfo> &Retains,
1926 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001927
1928 // Use reverse-postorder traversals, because we magically know that loops
1929 // will be well behaved, i.e. they won't repeatedly call retain on a single
1930 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1931 // class here because we want the reverse-CFG postorder to consider each
1932 // function exit point, and we want to ignore selected cycle edges.
1933 SmallVector<BasicBlock *, 16> PostOrder;
1934 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001935 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1936 NoObjCARCExceptionsMDKind,
1937 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001938
1939 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001940 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001941 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001942 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1943 I != E; ++I)
1944 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001945
Dan Gohmana53a12c2011-12-12 19:42:25 +00001946 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001947 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001948 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1949 PostOrder.rbegin(), E = PostOrder.rend();
1950 I != E; ++I)
1951 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001952
1953 return TopDownNestingDetected && BottomUpNestingDetected;
1954}
1955
Michael Gottesman97e3df02013-01-14 00:35:14 +00001956/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00001957void ObjCARCOpt::MoveCalls(Value *Arg,
1958 RRInfo &RetainsToMove,
1959 RRInfo &ReleasesToMove,
1960 MapVector<Value *, RRInfo> &Retains,
1961 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001962 SmallVectorImpl<Instruction *> &DeadInsts,
1963 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001964 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001965 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00001966
1967 // Insert the new retain and release calls.
1968 for (SmallPtrSet<Instruction *, 2>::const_iterator
1969 PI = ReleasesToMove.ReverseInsertPts.begin(),
1970 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
1971 Instruction *InsertPt = *PI;
1972 Value *MyArg = ArgTy == ParamTy ? Arg :
1973 new BitCastInst(Arg, ParamTy, "", InsertPt);
1974 CallInst *Call =
1975 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00001976 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00001977 MyArg, "", InsertPt);
1978 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00001979 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00001980 Call->setMetadata(CopyOnEscapeMDKind,
1981 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00001982 else
John McCalld935e9c2011-06-15 23:37:01 +00001983 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001984
1985 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
1986 << "\n"
1987 " At insertion point: " << *InsertPt
1988 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001989 }
1990 for (SmallPtrSet<Instruction *, 2>::const_iterator
1991 PI = RetainsToMove.ReverseInsertPts.begin(),
1992 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001993 Instruction *InsertPt = *PI;
1994 Value *MyArg = ArgTy == ParamTy ? Arg :
1995 new BitCastInst(Arg, ParamTy, "", InsertPt);
1996 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
1997 "", InsertPt);
1998 // Attach a clang.imprecise_release metadata tag, if appropriate.
1999 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2000 Call->setMetadata(ImpreciseReleaseMDKind, M);
2001 Call->setDoesNotThrow();
2002 if (ReleasesToMove.IsTailCallRelease)
2003 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002004
2005 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2006 << "\n"
2007 " At insertion point: " << *InsertPt
2008 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002009 }
2010
2011 // Delete the original retain and release calls.
2012 for (SmallPtrSet<Instruction *, 2>::const_iterator
2013 AI = RetainsToMove.Calls.begin(),
2014 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2015 Instruction *OrigRetain = *AI;
2016 Retains.blot(OrigRetain);
2017 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002018 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2019 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002020 }
2021 for (SmallPtrSet<Instruction *, 2>::const_iterator
2022 AI = ReleasesToMove.Calls.begin(),
2023 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2024 Instruction *OrigRelease = *AI;
2025 Releases.erase(OrigRelease);
2026 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002027 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2028 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002029 }
2030}
2031
Michael Gottesman9de6f962013-01-22 21:49:00 +00002032bool
2033ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2034 &BBStates,
2035 MapVector<Value *, RRInfo> &Retains,
2036 DenseMap<Value *, RRInfo> &Releases,
2037 Module *M,
2038 SmallVector<Instruction *, 4> &NewRetains,
2039 SmallVector<Instruction *, 4> &NewReleases,
2040 SmallVector<Instruction *, 8> &DeadInsts,
2041 RRInfo &RetainsToMove,
2042 RRInfo &ReleasesToMove,
2043 Value *Arg,
2044 bool KnownSafe,
2045 bool &AnyPairsCompletelyEliminated) {
2046 // If a pair happens in a region where it is known that the reference count
2047 // is already incremented, we can similarly ignore possible decrements.
2048 bool KnownSafeTD = true, KnownSafeBU = true;
2049
2050 // Connect the dots between the top-down-collected RetainsToMove and
2051 // bottom-up-collected ReleasesToMove to form sets of related calls.
2052 // This is an iterative process so that we connect multiple releases
2053 // to multiple retains if needed.
2054 unsigned OldDelta = 0;
2055 unsigned NewDelta = 0;
2056 unsigned OldCount = 0;
2057 unsigned NewCount = 0;
2058 bool FirstRelease = true;
2059 bool FirstRetain = true;
2060 for (;;) {
2061 for (SmallVectorImpl<Instruction *>::const_iterator
2062 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2063 Instruction *NewRetain = *NI;
2064 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2065 assert(It != Retains.end());
2066 const RRInfo &NewRetainRRI = It->second;
2067 KnownSafeTD &= NewRetainRRI.KnownSafe;
2068 for (SmallPtrSet<Instruction *, 2>::const_iterator
2069 LI = NewRetainRRI.Calls.begin(),
2070 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2071 Instruction *NewRetainRelease = *LI;
2072 DenseMap<Value *, RRInfo>::const_iterator Jt =
2073 Releases.find(NewRetainRelease);
2074 if (Jt == Releases.end())
2075 return false;
2076 const RRInfo &NewRetainReleaseRRI = Jt->second;
2077 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2078 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2079 OldDelta -=
2080 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2081
2082 // Merge the ReleaseMetadata and IsTailCallRelease values.
2083 if (FirstRelease) {
2084 ReleasesToMove.ReleaseMetadata =
2085 NewRetainReleaseRRI.ReleaseMetadata;
2086 ReleasesToMove.IsTailCallRelease =
2087 NewRetainReleaseRRI.IsTailCallRelease;
2088 FirstRelease = false;
2089 } else {
2090 if (ReleasesToMove.ReleaseMetadata !=
2091 NewRetainReleaseRRI.ReleaseMetadata)
2092 ReleasesToMove.ReleaseMetadata = 0;
2093 if (ReleasesToMove.IsTailCallRelease !=
2094 NewRetainReleaseRRI.IsTailCallRelease)
2095 ReleasesToMove.IsTailCallRelease = false;
2096 }
2097
2098 // Collect the optimal insertion points.
2099 if (!KnownSafe)
2100 for (SmallPtrSet<Instruction *, 2>::const_iterator
2101 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2102 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2103 RI != RE; ++RI) {
2104 Instruction *RIP = *RI;
2105 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2106 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2107 }
2108 NewReleases.push_back(NewRetainRelease);
2109 }
2110 }
2111 }
2112 NewRetains.clear();
2113 if (NewReleases.empty()) break;
2114
2115 // Back the other way.
2116 for (SmallVectorImpl<Instruction *>::const_iterator
2117 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2118 Instruction *NewRelease = *NI;
2119 DenseMap<Value *, RRInfo>::const_iterator It =
2120 Releases.find(NewRelease);
2121 assert(It != Releases.end());
2122 const RRInfo &NewReleaseRRI = It->second;
2123 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2124 for (SmallPtrSet<Instruction *, 2>::const_iterator
2125 LI = NewReleaseRRI.Calls.begin(),
2126 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2127 Instruction *NewReleaseRetain = *LI;
2128 MapVector<Value *, RRInfo>::const_iterator Jt =
2129 Retains.find(NewReleaseRetain);
2130 if (Jt == Retains.end())
2131 return false;
2132 const RRInfo &NewReleaseRetainRRI = Jt->second;
2133 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2134 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2135 unsigned PathCount =
2136 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2137 OldDelta += PathCount;
2138 OldCount += PathCount;
2139
2140 // Merge the IsRetainBlock values.
2141 if (FirstRetain) {
2142 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2143 FirstRetain = false;
2144 } else if (ReleasesToMove.IsRetainBlock !=
2145 NewReleaseRetainRRI.IsRetainBlock)
2146 // It's not possible to merge the sequences if one uses
2147 // objc_retain and the other uses objc_retainBlock.
2148 return false;
2149
2150 // Collect the optimal insertion points.
2151 if (!KnownSafe)
2152 for (SmallPtrSet<Instruction *, 2>::const_iterator
2153 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2154 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2155 RI != RE; ++RI) {
2156 Instruction *RIP = *RI;
2157 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2158 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2159 NewDelta += PathCount;
2160 NewCount += PathCount;
2161 }
2162 }
2163 NewRetains.push_back(NewReleaseRetain);
2164 }
2165 }
2166 }
2167 NewReleases.clear();
2168 if (NewRetains.empty()) break;
2169 }
2170
2171 // If the pointer is known incremented or nested, we can safely delete the
2172 // pair regardless of what's between them.
2173 if (KnownSafeTD || KnownSafeBU) {
2174 RetainsToMove.ReverseInsertPts.clear();
2175 ReleasesToMove.ReverseInsertPts.clear();
2176 NewCount = 0;
2177 } else {
2178 // Determine whether the new insertion points we computed preserve the
2179 // balance of retain and release calls through the program.
2180 // TODO: If the fully aggressive solution isn't valid, try to find a
2181 // less aggressive solution which is.
2182 if (NewDelta != 0)
2183 return false;
2184 }
2185
2186 // Determine whether the original call points are balanced in the retain and
2187 // release calls through the program. If not, conservatively don't touch
2188 // them.
2189 // TODO: It's theoretically possible to do code motion in this case, as
2190 // long as the existing imbalances are maintained.
2191 if (OldDelta != 0)
2192 return false;
2193
2194 Changed = true;
2195 assert(OldCount != 0 && "Unreachable code?");
2196 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002197 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002198 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002199
2200 // We can move calls!
2201 return true;
2202}
2203
Michael Gottesman97e3df02013-01-14 00:35:14 +00002204/// Identify pairings between the retains and releases, and delete and/or move
2205/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002206bool
2207ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2208 &BBStates,
2209 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002210 DenseMap<Value *, RRInfo> &Releases,
2211 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00002212 bool AnyPairsCompletelyEliminated = false;
2213 RRInfo RetainsToMove;
2214 RRInfo ReleasesToMove;
2215 SmallVector<Instruction *, 4> NewRetains;
2216 SmallVector<Instruction *, 4> NewReleases;
2217 SmallVector<Instruction *, 8> DeadInsts;
2218
Dan Gohman670f9372012-04-13 18:57:48 +00002219 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002220 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002221 E = Retains.end(); I != E; ++I) {
2222 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002223 if (!V) continue; // blotted
2224
2225 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002226
2227 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2228 << "\n");
2229
John McCalld935e9c2011-06-15 23:37:01 +00002230 Value *Arg = GetObjCArg(Retain);
2231
Dan Gohman728db492012-01-13 00:39:07 +00002232 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002233 // not being managed by ObjC reference counting, so we can delete pairs
2234 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002235 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002236
Dan Gohman56e1cef2011-08-22 17:29:11 +00002237 // A constant pointer can't be pointing to an object on the heap. It may
2238 // be reference-counted, but it won't be deleted.
2239 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2240 if (const GlobalVariable *GV =
2241 dyn_cast<GlobalVariable>(
2242 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2243 if (GV->isConstant())
2244 KnownSafe = true;
2245
John McCalld935e9c2011-06-15 23:37:01 +00002246 // Connect the dots between the top-down-collected RetainsToMove and
2247 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002248 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002249 bool PerformMoveCalls =
2250 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2251 NewReleases, DeadInsts, RetainsToMove,
2252 ReleasesToMove, Arg, KnownSafe,
2253 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002254
Michael Gottesman9de6f962013-01-22 21:49:00 +00002255 if (PerformMoveCalls) {
2256 // Ok, everything checks out and we're all set. Let's move/delete some
2257 // code!
2258 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2259 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002260 }
2261
Michael Gottesman9de6f962013-01-22 21:49:00 +00002262 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002263 NewReleases.clear();
2264 NewRetains.clear();
2265 RetainsToMove.clear();
2266 ReleasesToMove.clear();
2267 }
2268
2269 // Now that we're done moving everything, we can delete the newly dead
2270 // instructions, as we no longer need them as insert points.
2271 while (!DeadInsts.empty())
2272 EraseInstruction(DeadInsts.pop_back_val());
2273
2274 return AnyPairsCompletelyEliminated;
2275}
2276
Michael Gottesman97e3df02013-01-14 00:35:14 +00002277/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002278void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2279 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2280 // itself because it uses AliasAnalysis and we need to do provenance
2281 // queries instead.
2282 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2283 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002284
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002285 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00002286 "\n");
2287
John McCalld935e9c2011-06-15 23:37:01 +00002288 InstructionClass Class = GetBasicInstructionClass(Inst);
2289 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2290 continue;
2291
2292 // Delete objc_loadWeak calls with no users.
2293 if (Class == IC_LoadWeak && Inst->use_empty()) {
2294 Inst->eraseFromParent();
2295 continue;
2296 }
2297
2298 // TODO: For now, just look for an earlier available version of this value
2299 // within the same block. Theoretically, we could do memdep-style non-local
2300 // analysis too, but that would want caching. A better approach would be to
2301 // use the technique that EarlyCSE uses.
2302 inst_iterator Current = llvm::prior(I);
2303 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2304 for (BasicBlock::iterator B = CurrentBB->begin(),
2305 J = Current.getInstructionIterator();
2306 J != B; --J) {
2307 Instruction *EarlierInst = &*llvm::prior(J);
2308 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2309 switch (EarlierClass) {
2310 case IC_LoadWeak:
2311 case IC_LoadWeakRetained: {
2312 // If this is loading from the same pointer, replace this load's value
2313 // with that one.
2314 CallInst *Call = cast<CallInst>(Inst);
2315 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2316 Value *Arg = Call->getArgOperand(0);
2317 Value *EarlierArg = EarlierCall->getArgOperand(0);
2318 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2319 case AliasAnalysis::MustAlias:
2320 Changed = true;
2321 // If the load has a builtin retain, insert a plain retain for it.
2322 if (Class == IC_LoadWeakRetained) {
2323 CallInst *CI =
2324 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2325 "", Call);
2326 CI->setTailCall();
2327 }
2328 // Zap the fully redundant load.
2329 Call->replaceAllUsesWith(EarlierCall);
2330 Call->eraseFromParent();
2331 goto clobbered;
2332 case AliasAnalysis::MayAlias:
2333 case AliasAnalysis::PartialAlias:
2334 goto clobbered;
2335 case AliasAnalysis::NoAlias:
2336 break;
2337 }
2338 break;
2339 }
2340 case IC_StoreWeak:
2341 case IC_InitWeak: {
2342 // If this is storing to the same pointer and has the same size etc.
2343 // replace this load's value with the stored value.
2344 CallInst *Call = cast<CallInst>(Inst);
2345 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2346 Value *Arg = Call->getArgOperand(0);
2347 Value *EarlierArg = EarlierCall->getArgOperand(0);
2348 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2349 case AliasAnalysis::MustAlias:
2350 Changed = true;
2351 // If the load has a builtin retain, insert a plain retain for it.
2352 if (Class == IC_LoadWeakRetained) {
2353 CallInst *CI =
2354 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2355 "", Call);
2356 CI->setTailCall();
2357 }
2358 // Zap the fully redundant load.
2359 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2360 Call->eraseFromParent();
2361 goto clobbered;
2362 case AliasAnalysis::MayAlias:
2363 case AliasAnalysis::PartialAlias:
2364 goto clobbered;
2365 case AliasAnalysis::NoAlias:
2366 break;
2367 }
2368 break;
2369 }
2370 case IC_MoveWeak:
2371 case IC_CopyWeak:
2372 // TOOD: Grab the copied value.
2373 goto clobbered;
2374 case IC_AutoreleasepoolPush:
2375 case IC_None:
2376 case IC_User:
2377 // Weak pointers are only modified through the weak entry points
2378 // (and arbitrary calls, which could call the weak entry points).
2379 break;
2380 default:
2381 // Anything else could modify the weak pointer.
2382 goto clobbered;
2383 }
2384 }
2385 clobbered:;
2386 }
2387
2388 // Then, for each destroyWeak with an alloca operand, check to see if
2389 // the alloca and all its users can be zapped.
2390 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2391 Instruction *Inst = &*I++;
2392 InstructionClass Class = GetBasicInstructionClass(Inst);
2393 if (Class != IC_DestroyWeak)
2394 continue;
2395
2396 CallInst *Call = cast<CallInst>(Inst);
2397 Value *Arg = Call->getArgOperand(0);
2398 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2399 for (Value::use_iterator UI = Alloca->use_begin(),
2400 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002401 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002402 switch (GetBasicInstructionClass(UserInst)) {
2403 case IC_InitWeak:
2404 case IC_StoreWeak:
2405 case IC_DestroyWeak:
2406 continue;
2407 default:
2408 goto done;
2409 }
2410 }
2411 Changed = true;
2412 for (Value::use_iterator UI = Alloca->use_begin(),
2413 UE = Alloca->use_end(); UI != UE; ) {
2414 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002415 switch (GetBasicInstructionClass(UserInst)) {
2416 case IC_InitWeak:
2417 case IC_StoreWeak:
2418 // These functions return their second argument.
2419 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2420 break;
2421 case IC_DestroyWeak:
2422 // No return value.
2423 break;
2424 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002425 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002426 }
John McCalld935e9c2011-06-15 23:37:01 +00002427 UserInst->eraseFromParent();
2428 }
2429 Alloca->eraseFromParent();
2430 done:;
2431 }
2432 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002433
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002434 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002435
John McCalld935e9c2011-06-15 23:37:01 +00002436}
2437
Michael Gottesman97e3df02013-01-14 00:35:14 +00002438/// Identify program paths which execute sequences of retains and releases which
2439/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002440bool ObjCARCOpt::OptimizeSequences(Function &F) {
2441 /// Releases, Retains - These are used to store the results of the main flow
2442 /// analysis. These use Value* as the key instead of Instruction* so that the
2443 /// map stays valid when we get around to rewriting code and calls get
2444 /// replaced by arguments.
2445 DenseMap<Value *, RRInfo> Releases;
2446 MapVector<Value *, RRInfo> Retains;
2447
Michael Gottesman97e3df02013-01-14 00:35:14 +00002448 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002449 /// states for each identified object at each block.
2450 DenseMap<const BasicBlock *, BBState> BBStates;
2451
2452 // Analyze the CFG of the function, and all instructions.
2453 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2454
2455 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002456 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2457 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002458}
2459
Michael Gottesman97e3df02013-01-14 00:35:14 +00002460/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002461/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002462/// %call = call i8* @something(...)
2463/// %2 = call i8* @objc_retain(i8* %call)
2464/// %3 = call i8* @objc_autorelease(i8* %2)
2465/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002466/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002467/// And delete the retain and autorelease.
2468///
2469/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002470/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002471/// %3 = call i8* @objc_autorelease(i8* %2)
2472/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002473/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002474/// convert the autorelease to autoreleaseRV.
2475void ObjCARCOpt::OptimizeReturns(Function &F) {
2476 if (!F.getReturnType()->isPointerTy())
2477 return;
2478
2479 SmallPtrSet<Instruction *, 4> DependingInstructions;
2480 SmallPtrSet<const BasicBlock *, 4> Visited;
2481 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2482 BasicBlock *BB = FI;
2483 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002484
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002485 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002486
John McCalld935e9c2011-06-15 23:37:01 +00002487 if (!Ret) continue;
2488
2489 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2490 FindDependencies(NeedsPositiveRetainCount, Arg,
2491 BB, Ret, DependingInstructions, Visited, PA);
2492 if (DependingInstructions.size() != 1)
2493 goto next_block;
2494
2495 {
2496 CallInst *Autorelease =
2497 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2498 if (!Autorelease)
2499 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00002500 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002501 if (!IsAutorelease(AutoreleaseClass))
2502 goto next_block;
2503 if (GetObjCArg(Autorelease) != Arg)
2504 goto next_block;
2505
2506 DependingInstructions.clear();
2507 Visited.clear();
2508
2509 // Check that there is nothing that can affect the reference
2510 // count between the autorelease and the retain.
2511 FindDependencies(CanChangeRetainCount, Arg,
2512 BB, Autorelease, DependingInstructions, Visited, PA);
2513 if (DependingInstructions.size() != 1)
2514 goto next_block;
2515
2516 {
2517 CallInst *Retain =
2518 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2519
2520 // Check that we found a retain with the same argument.
2521 if (!Retain ||
2522 !IsRetain(GetBasicInstructionClass(Retain)) ||
2523 GetObjCArg(Retain) != Arg)
2524 goto next_block;
2525
2526 DependingInstructions.clear();
2527 Visited.clear();
2528
2529 // Convert the autorelease to an autoreleaseRV, since it's
2530 // returning the value.
2531 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002532 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
2533 "=> autoreleaseRV since it's returning a value.\n"
2534 " In: " << *Autorelease
2535 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002536 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002537 DEBUG(dbgs() << " Out: " << *Autorelease
2538 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002539 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00002540 AutoreleaseClass = IC_AutoreleaseRV;
2541 }
2542
2543 // Check that there is nothing that can affect the reference
2544 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00002545 // Note that Retain need not be in BB.
2546 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00002547 DependingInstructions, Visited, PA);
2548 if (DependingInstructions.size() != 1)
2549 goto next_block;
2550
2551 {
2552 CallInst *Call =
2553 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2554
2555 // Check that the pointer is the return value of the call.
2556 if (!Call || Arg != Call)
2557 goto next_block;
2558
2559 // Check that the call is a regular call.
2560 InstructionClass Class = GetBasicInstructionClass(Call);
2561 if (Class != IC_CallOrUser && Class != IC_Call)
2562 goto next_block;
2563
2564 // If so, we can zap the retain and autorelease.
2565 Changed = true;
2566 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002567 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
2568 << "\n Erasing: "
2569 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002570 EraseInstruction(Retain);
2571 EraseInstruction(Autorelease);
2572 }
2573 }
2574 }
2575
2576 next_block:
2577 DependingInstructions.clear();
2578 Visited.clear();
2579 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002580
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002581 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002582
John McCalld935e9c2011-06-15 23:37:01 +00002583}
2584
2585bool ObjCARCOpt::doInitialization(Module &M) {
2586 if (!EnableARCOpts)
2587 return false;
2588
Dan Gohman670f9372012-04-13 18:57:48 +00002589 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002590 Run = ModuleHasARC(M);
2591 if (!Run)
2592 return false;
2593
John McCalld935e9c2011-06-15 23:37:01 +00002594 // Identify the imprecise release metadata kind.
2595 ImpreciseReleaseMDKind =
2596 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002597 CopyOnEscapeMDKind =
2598 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002599 NoObjCARCExceptionsMDKind =
2600 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00002601
John McCalld935e9c2011-06-15 23:37:01 +00002602 // Intuitively, objc_retain and others are nocapture, however in practice
2603 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002604 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002605
2606 // These are initialized lazily.
2607 RetainRVCallee = 0;
2608 AutoreleaseRVCallee = 0;
2609 ReleaseCallee = 0;
2610 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002611 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002612 AutoreleaseCallee = 0;
2613
2614 return false;
2615}
2616
2617bool ObjCARCOpt::runOnFunction(Function &F) {
2618 if (!EnableARCOpts)
2619 return false;
2620
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002621 // If nothing in the Module uses ARC, don't do anything.
2622 if (!Run)
2623 return false;
2624
John McCalld935e9c2011-06-15 23:37:01 +00002625 Changed = false;
2626
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002627 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
2628
John McCalld935e9c2011-06-15 23:37:01 +00002629 PA.setAA(&getAnalysis<AliasAnalysis>());
2630
2631 // This pass performs several distinct transformations. As a compile-time aid
2632 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2633 // library functions aren't declared.
2634
2635 // Preliminary optimizations. This also computs UsedInThisFunction.
2636 OptimizeIndividualCalls(F);
2637
2638 // Optimizations for weak pointers.
2639 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2640 (1 << IC_LoadWeakRetained) |
2641 (1 << IC_StoreWeak) |
2642 (1 << IC_InitWeak) |
2643 (1 << IC_CopyWeak) |
2644 (1 << IC_MoveWeak) |
2645 (1 << IC_DestroyWeak)))
2646 OptimizeWeakCalls(F);
2647
2648 // Optimizations for retain+release pairs.
2649 if (UsedInThisFunction & ((1 << IC_Retain) |
2650 (1 << IC_RetainRV) |
2651 (1 << IC_RetainBlock)))
2652 if (UsedInThisFunction & (1 << IC_Release))
2653 // Run OptimizeSequences until it either stops making changes or
2654 // no retain+release pair nesting is detected.
2655 while (OptimizeSequences(F)) {}
2656
2657 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00002658 if (UsedInThisFunction & ((1 << IC_Autorelease) |
2659 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00002660 OptimizeReturns(F);
2661
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002662 DEBUG(dbgs() << "\n");
2663
John McCalld935e9c2011-06-15 23:37:01 +00002664 return Changed;
2665}
2666
2667void ObjCARCOpt::releaseMemory() {
2668 PA.clear();
2669}
2670
Michael Gottesman97e3df02013-01-14 00:35:14 +00002671/// @}
2672///