blob: 3cfe2aa06c469ba21b1992373a8cf21bd2a5b194 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000033#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000034#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000037#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000038#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000039#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000040
John McCalld935e9c2011-06-15 23:37:01 +000041using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000042using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000043
Michael Gottesman97e3df02013-01-14 00:35:14 +000044/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
45/// @{
John McCalld935e9c2011-06-15 23:37:01 +000046
47namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000048 /// \brief An associative container with fast insertion-order (deterministic)
49 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000050 template<class KeyT, class ValueT>
51 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000052 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000053 typedef DenseMap<KeyT, size_t> MapTy;
54 MapTy Map;
55
John McCalld935e9c2011-06-15 23:37:01 +000056 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000057 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000058 VectorTy Vector;
59
60 public:
61 typedef typename VectorTy::iterator iterator;
62 typedef typename VectorTy::const_iterator const_iterator;
63 iterator begin() { return Vector.begin(); }
64 iterator end() { return Vector.end(); }
65 const_iterator begin() const { return Vector.begin(); }
66 const_iterator end() const { return Vector.end(); }
67
68#ifdef XDEBUG
69 ~MapVector() {
70 assert(Vector.size() >= Map.size()); // May differ due to blotting.
71 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
72 I != E; ++I) {
73 assert(I->second < Vector.size());
74 assert(Vector[I->second].first == I->first);
75 }
76 for (typename VectorTy::const_iterator I = Vector.begin(),
77 E = Vector.end(); I != E; ++I)
78 assert(!I->first ||
79 (Map.count(I->first) &&
80 Map[I->first] == size_t(I - Vector.begin())));
81 }
82#endif
83
Dan Gohman55b06742012-03-02 01:13:53 +000084 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000085 std::pair<typename MapTy::iterator, bool> Pair =
86 Map.insert(std::make_pair(Arg, size_t(0)));
87 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000088 size_t Num = Vector.size();
89 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000090 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000091 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000092 }
93 return Vector[Pair.first->second].second;
94 }
95
96 std::pair<iterator, bool>
97 insert(const std::pair<KeyT, ValueT> &InsertPair) {
98 std::pair<typename MapTy::iterator, bool> Pair =
99 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
100 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000101 size_t Num = Vector.size();
102 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000103 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000104 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000105 }
106 return std::make_pair(Vector.begin() + Pair.first->second, false);
107 }
108
Dan Gohman55b06742012-03-02 01:13:53 +0000109 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000110 typename MapTy::const_iterator It = Map.find(Key);
111 if (It == Map.end()) return Vector.end();
112 return Vector.begin() + It->second;
113 }
114
Michael Gottesman97e3df02013-01-14 00:35:14 +0000115 /// This is similar to erase, but instead of removing the element from the
116 /// vector, it just zeros out the key in the vector. This leaves iterators
117 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000118 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000119 typename MapTy::iterator It = Map.find(Key);
120 if (It == Map.end()) return;
121 Vector[It->second].first = KeyT();
122 Map.erase(It);
123 }
124
125 void clear() {
126 Map.clear();
127 Vector.clear();
128 }
129 };
130}
131
Michael Gottesman97e3df02013-01-14 00:35:14 +0000132/// @}
133///
134/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
135/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000136
Michael Gottesman97e3df02013-01-14 00:35:14 +0000137/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
138/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000139static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
140 if (Arg->hasOneUse()) {
141 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
142 return FindSingleUseIdentifiedObject(BC->getOperand(0));
143 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
144 if (GEP->hasAllZeroIndices())
145 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
146 if (IsForwarding(GetBasicInstructionClass(Arg)))
147 return FindSingleUseIdentifiedObject(
148 cast<CallInst>(Arg)->getArgOperand(0));
149 if (!IsObjCIdentifiedObject(Arg))
150 return 0;
151 return Arg;
152 }
153
Dan Gohman41375a32012-05-08 23:39:44 +0000154 // If we found an identifiable object but it has multiple uses, but they are
155 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000156 if (IsObjCIdentifiedObject(Arg)) {
157 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
158 UI != UE; ++UI) {
159 const User *U = *UI;
160 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
161 return 0;
162 }
163
164 return Arg;
165 }
166
167 return 0;
168}
169
Michael Gottesman774d2c02013-01-29 21:00:52 +0000170/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000171///
172/// This differs from regular escape analysis in that a use as an
173/// argument to a call is not considered an escape.
174///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000175static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000176 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000177
Dan Gohman728db492012-01-13 00:39:07 +0000178 // Walk the def-use chains.
179 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000180 Worklist.push_back(Ptr);
181 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000182 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
183 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184 Worklist.push_back(*I);
185 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000186
187 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000188 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000189
Dan Gohman728db492012-01-13 00:39:07 +0000190 do {
191 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000192
Michael Gottesman774d2c02013-01-29 21:00:52 +0000193 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000194
Dan Gohman728db492012-01-13 00:39:07 +0000195 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
196 UI != UE; ++UI) {
197 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000198
Michael Gottesman774d2c02013-01-29 21:00:52 +0000199 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000200
Dan Gohman728db492012-01-13 00:39:07 +0000201 // Special - Use by a call (callee or argument) is not considered
202 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000203 switch (GetBasicInstructionClass(UUser)) {
204 case IC_StoreWeak:
205 case IC_InitWeak:
206 case IC_StoreStrong:
207 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000208 case IC_AutoreleaseRV: {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000209 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies pointer "
210 "arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 // These special functions make copies of their pointer arguments.
212 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000213 }
John McCall20182ac2013-03-22 21:38:36 +0000214 case IC_IntrinsicUser:
215 // Use by the use intrinsic is not an escape.
216 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000217 case IC_User:
218 case IC_None:
219 // Use by an instruction which copies the value is an escape if the
220 // result is an escape.
221 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
222 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000223
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000224 if (VisitedSet.insert(UUser)) {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000225 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies value. "
226 "Ptr escapes if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000227 Worklist.push_back(UUser);
228 } else {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000229 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Already visited node."
230 "\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 Gottesman23cda0c2013-01-29 21:07:53 +0000247 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000248 return true;
249 }
250 } while (!Worklist.empty());
251
252 // No escapes found.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000253 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Ptr 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,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000315 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.
Michael Gottesman386241c2013-01-29 21:39:02 +0000318 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000319 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000320 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000321 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000322
323 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
324 LLVM_ATTRIBUTE_UNUSED;
325 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
326 switch (S) {
327 case S_None:
328 return OS << "S_None";
329 case S_Retain:
330 return OS << "S_Retain";
331 case S_CanRelease:
332 return OS << "S_CanRelease";
333 case S_Use:
334 return OS << "S_Use";
335 case S_Release:
336 return OS << "S_Release";
337 case S_MovableRelease:
338 return OS << "S_MovableRelease";
339 case S_Stop:
340 return OS << "S_Stop";
341 }
342 llvm_unreachable("Unknown sequence type.");
343 }
John McCalld935e9c2011-06-15 23:37:01 +0000344}
345
346static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
347 // The easy cases.
348 if (A == B)
349 return A;
350 if (A == S_None || B == S_None)
351 return S_None;
352
John McCalld935e9c2011-06-15 23:37:01 +0000353 if (A > B) std::swap(A, B);
354 if (TopDown) {
355 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000356 if ((A == S_Retain || A == S_CanRelease) &&
357 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000358 return B;
359 } else {
360 // Choose the side which is further along in the sequence.
361 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000362 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000363 return A;
364 // If both sides are releases, choose the more conservative one.
365 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
366 return A;
367 if (A == S_Release && B == S_MovableRelease)
368 return A;
369 }
370
371 return S_None;
372}
373
374namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000375 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000376 /// retain-decrement-use-release sequence or release-use-decrement-retain
377 /// reverese sequence.
378 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000379 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000380 /// object is known to be positive. Similarly, before an objc_release, the
381 /// reference count of the referenced object is known to be positive. If
382 /// there are retain-release pairs in code regions where the retain count
383 /// is known to be positive, they can be eliminated, regardless of any side
384 /// effects between them.
385 ///
386 /// Also, a retain+release pair nested within another retain+release
387 /// pair all on the known same pointer value can be eliminated, regardless
388 /// of any intervening side effects.
389 ///
390 /// KnownSafe is true when either of these conditions is satisfied.
391 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000392
Michael Gottesman97e3df02013-01-14 00:35:14 +0000393 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
394 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +0000395 bool IsRetainBlock;
396
Michael Gottesman97e3df02013-01-14 00:35:14 +0000397 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000398 bool IsTailCallRelease;
399
Michael Gottesman97e3df02013-01-14 00:35:14 +0000400 /// If the Calls are objc_release calls and they all have a
401 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000402 MDNode *ReleaseMetadata;
403
Michael Gottesman97e3df02013-01-14 00:35:14 +0000404 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000405 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
406 SmallPtrSet<Instruction *, 2> Calls;
407
Michael Gottesman97e3df02013-01-14 00:35:14 +0000408 /// The set of optimal insert positions for moving calls in the opposite
409 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000410 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
411
412 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +0000413 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +0000414 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +0000415 ReleaseMetadata(0) {}
416
417 void clear();
418 };
419}
420
421void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000422 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000423 IsRetainBlock = false;
424 IsTailCallRelease = false;
425 ReleaseMetadata = 0;
426 Calls.clear();
427 ReverseInsertPts.clear();
428}
429
430namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000431 /// \brief This class summarizes several per-pointer runtime properties which
432 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000433 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000434 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000435 bool KnownPositiveRefCount;
436
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// True of we've seen an opportunity for partial RR elimination, such as
438 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000439 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000440
Michael Gottesman97e3df02013-01-14 00:35:14 +0000441 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000442 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000443
444 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000445 /// Unidirectional information about the current sequence.
446 ///
John McCalld935e9c2011-06-15 23:37:01 +0000447 /// TODO: Encapsulate this better.
448 RRInfo RRI;
449
Dan Gohmandf476e52012-09-04 23:16:20 +0000450 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000451 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000452
Michael Gottesman415ddd72013-02-05 19:32:18 +0000453 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000454 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000455 }
456
Michael Gottesman415ddd72013-02-05 19:32:18 +0000457 void ClearRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000458 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000459 }
460
Michael Gottesman07beea42013-03-23 05:31:01 +0000461 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000462 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000463 }
464
Michael Gottesman415ddd72013-02-05 19:32:18 +0000465 void SetSeq(Sequence NewSeq) {
John McCalld935e9c2011-06-15 23:37:01 +0000466 Seq = NewSeq;
467 }
468
Michael Gottesman415ddd72013-02-05 19:32:18 +0000469 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000470 return Seq;
471 }
472
Michael Gottesman415ddd72013-02-05 19:32:18 +0000473 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000474 ResetSequenceProgress(S_None);
475 }
476
Michael Gottesman415ddd72013-02-05 19:32:18 +0000477 void ResetSequenceProgress(Sequence NewSeq) {
Dan Gohman62079b42012-04-25 00:50:46 +0000478 Seq = NewSeq;
479 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000480 RRI.clear();
481 }
482
483 void Merge(const PtrState &Other, bool TopDown);
484 };
485}
486
487void
488PtrState::Merge(const PtrState &Other, bool TopDown) {
489 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000490 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000491
492 // We can't merge a plain objc_retain with an objc_retainBlock.
493 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
494 Seq = S_None;
495
Dan Gohman1736c142011-10-17 18:48:25 +0000496 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000497 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000498 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000499 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000500 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000501 // If we're doing a merge on a path that's previously seen a partial
502 // merge, conservatively drop the sequence, to avoid doing partial
503 // RR elimination. If the branch predicates for the two merge differ,
504 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000505 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000506 } else {
507 // Conservatively merge the ReleaseMetadata information.
508 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
509 RRI.ReleaseMetadata = 0;
510
Dan Gohmanb3894012011-08-19 00:26:36 +0000511 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000512 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
513 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000514 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000515
516 // Merge the insert point sets. If there are any differences,
517 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000518 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000519 for (SmallPtrSet<Instruction *, 2>::const_iterator
520 I = Other.RRI.ReverseInsertPts.begin(),
521 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000522 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000523 }
524}
525
526namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000527 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000528 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000529 /// The number of unique control paths from the entry which can reach this
530 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000531 unsigned TopDownPathCount;
532
Michael Gottesman97e3df02013-01-14 00:35:14 +0000533 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000534 unsigned BottomUpPathCount;
535
Michael Gottesman97e3df02013-01-14 00:35:14 +0000536 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000537 typedef MapVector<const Value *, PtrState> MapTy;
538
Michael Gottesman97e3df02013-01-14 00:35:14 +0000539 /// The top-down traversal uses this to record information known about a
540 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000541 MapTy PerPtrTopDown;
542
Michael Gottesman97e3df02013-01-14 00:35:14 +0000543 /// The bottom-up traversal uses this to record information known about a
544 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000545 MapTy PerPtrBottomUp;
546
Michael Gottesman97e3df02013-01-14 00:35:14 +0000547 /// Effective predecessors of the current block ignoring ignorable edges and
548 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000549 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000550 /// Effective successors of the current block ignoring ignorable edges and
551 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000552 SmallVector<BasicBlock *, 2> Succs;
553
John McCalld935e9c2011-06-15 23:37:01 +0000554 public:
555 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
556
557 typedef MapTy::iterator ptr_iterator;
558 typedef MapTy::const_iterator ptr_const_iterator;
559
560 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
561 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
562 ptr_const_iterator top_down_ptr_begin() const {
563 return PerPtrTopDown.begin();
564 }
565 ptr_const_iterator top_down_ptr_end() const {
566 return PerPtrTopDown.end();
567 }
568
569 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
570 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
571 ptr_const_iterator bottom_up_ptr_begin() const {
572 return PerPtrBottomUp.begin();
573 }
574 ptr_const_iterator bottom_up_ptr_end() const {
575 return PerPtrBottomUp.end();
576 }
577
Michael Gottesman97e3df02013-01-14 00:35:14 +0000578 /// Mark this block as being an entry block, which has one path from the
579 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000580 void SetAsEntry() { TopDownPathCount = 1; }
581
Michael Gottesman97e3df02013-01-14 00:35:14 +0000582 /// Mark this block as being an exit block, which has one path to an exit by
583 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000584 void SetAsExit() { BottomUpPathCount = 1; }
585
586 PtrState &getPtrTopDownState(const Value *Arg) {
587 return PerPtrTopDown[Arg];
588 }
589
590 PtrState &getPtrBottomUpState(const Value *Arg) {
591 return PerPtrBottomUp[Arg];
592 }
593
594 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000595 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000596 }
597
598 void clearTopDownPointers() {
599 PerPtrTopDown.clear();
600 }
601
602 void InitFromPred(const BBState &Other);
603 void InitFromSucc(const BBState &Other);
604 void MergePred(const BBState &Other);
605 void MergeSucc(const BBState &Other);
606
Michael Gottesman97e3df02013-01-14 00:35:14 +0000607 /// Return the number of possible unique paths from an entry to an exit
608 /// which pass through this block. This is only valid after both the
609 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000610 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000611 assert(TopDownPathCount != 0);
612 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000613 return TopDownPathCount * BottomUpPathCount;
614 }
Dan Gohman12130272011-08-12 00:26:31 +0000615
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000616 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000617 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000618 edge_iterator pred_begin() { return Preds.begin(); }
619 edge_iterator pred_end() { return Preds.end(); }
620 edge_iterator succ_begin() { return Succs.begin(); }
621 edge_iterator succ_end() { return Succs.end(); }
622
623 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
624 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
625
626 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000627 };
628}
629
630void BBState::InitFromPred(const BBState &Other) {
631 PerPtrTopDown = Other.PerPtrTopDown;
632 TopDownPathCount = Other.TopDownPathCount;
633}
634
635void BBState::InitFromSucc(const BBState &Other) {
636 PerPtrBottomUp = Other.PerPtrBottomUp;
637 BottomUpPathCount = Other.BottomUpPathCount;
638}
639
Michael Gottesman97e3df02013-01-14 00:35:14 +0000640/// The top-down traversal uses this to merge information about predecessors to
641/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000642void BBState::MergePred(const BBState &Other) {
643 // Other.TopDownPathCount can be 0, in which case it is either dead or a
644 // loop backedge. Loop backedges are special.
645 TopDownPathCount += Other.TopDownPathCount;
646
Michael Gottesman4385edf2013-01-14 01:47:53 +0000647 // Check for overflow. If we have overflow, fall back to conservative
648 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000649 if (TopDownPathCount < Other.TopDownPathCount) {
650 clearTopDownPointers();
651 return;
652 }
653
John McCalld935e9c2011-06-15 23:37:01 +0000654 // For each entry in the other set, if our set has an entry with the same key,
655 // merge the entries. Otherwise, copy the entry and merge it with an empty
656 // entry.
657 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
658 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
659 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
660 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
661 /*TopDown=*/true);
662 }
663
Dan Gohman7e315fc32011-08-11 21:06:32 +0000664 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000665 // same key, force it to merge with an empty entry.
666 for (ptr_iterator MI = top_down_ptr_begin(),
667 ME = top_down_ptr_end(); MI != ME; ++MI)
668 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
669 MI->second.Merge(PtrState(), /*TopDown=*/true);
670}
671
Michael Gottesman97e3df02013-01-14 00:35:14 +0000672/// The bottom-up traversal uses this to merge information about successors to
673/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000674void BBState::MergeSucc(const BBState &Other) {
675 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
676 // loop backedge. Loop backedges are special.
677 BottomUpPathCount += Other.BottomUpPathCount;
678
Michael Gottesman4385edf2013-01-14 01:47:53 +0000679 // Check for overflow. If we have overflow, fall back to conservative
680 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000681 if (BottomUpPathCount < Other.BottomUpPathCount) {
682 clearBottomUpPointers();
683 return;
684 }
685
John McCalld935e9c2011-06-15 23:37:01 +0000686 // For each entry in the other set, if our set has an entry with the
687 // same key, merge the entries. Otherwise, copy the entry and merge
688 // it with an empty entry.
689 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
690 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
691 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
692 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
693 /*TopDown=*/false);
694 }
695
Dan Gohman7e315fc32011-08-11 21:06:32 +0000696 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000697 // with the same key, force it to merge with an empty entry.
698 for (ptr_iterator MI = bottom_up_ptr_begin(),
699 ME = bottom_up_ptr_end(); MI != ME; ++MI)
700 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
701 MI->second.Merge(PtrState(), /*TopDown=*/false);
702}
703
704namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000705 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000706 class ObjCARCOpt : public FunctionPass {
707 bool Changed;
708 ProvenanceAnalysis PA;
709
Michael Gottesman97e3df02013-01-14 00:35:14 +0000710 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000711 bool Run;
712
Michael Gottesman97e3df02013-01-14 00:35:14 +0000713 /// Declarations for ObjC runtime functions, for use in creating calls to
714 /// them. These are initialized lazily to avoid cluttering up the Module
715 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000716
Michael Gottesman97e3df02013-01-14 00:35:14 +0000717 /// Declaration for ObjC runtime function
718 /// objc_retainAutoreleasedReturnValue.
719 Constant *RetainRVCallee;
720 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
721 Constant *AutoreleaseRVCallee;
722 /// Declaration for ObjC runtime function objc_release.
723 Constant *ReleaseCallee;
724 /// Declaration for ObjC runtime function objc_retain.
725 Constant *RetainCallee;
726 /// Declaration for ObjC runtime function objc_retainBlock.
727 Constant *RetainBlockCallee;
728 /// Declaration for ObjC runtime function objc_autorelease.
729 Constant *AutoreleaseCallee;
730
731 /// Flags which determine whether each of the interesting runtine functions
732 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000733 unsigned UsedInThisFunction;
734
Michael Gottesman97e3df02013-01-14 00:35:14 +0000735 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000736 unsigned ImpreciseReleaseMDKind;
737
Michael Gottesman97e3df02013-01-14 00:35:14 +0000738 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000739 unsigned CopyOnEscapeMDKind;
740
Michael Gottesman97e3df02013-01-14 00:35:14 +0000741 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000742 unsigned NoObjCARCExceptionsMDKind;
743
John McCalld935e9c2011-06-15 23:37:01 +0000744 Constant *getRetainRVCallee(Module *M);
745 Constant *getAutoreleaseRVCallee(Module *M);
746 Constant *getReleaseCallee(Module *M);
747 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +0000748 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000749 Constant *getAutoreleaseCallee(Module *M);
750
Dan Gohman728db492012-01-13 00:39:07 +0000751 bool IsRetainBlockOptimizable(const Instruction *Inst);
752
John McCalld935e9c2011-06-15 23:37:01 +0000753 void OptimizeRetainCall(Function &F, Instruction *Retain);
754 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000755 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
756 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000757 void OptimizeIndividualCalls(Function &F);
758
759 void CheckForCFGHazards(const BasicBlock *BB,
760 DenseMap<const BasicBlock *, BBState> &BBStates,
761 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +0000762 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +0000763 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +0000764 MapVector<Value *, RRInfo> &Retains,
765 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000766 bool VisitBottomUp(BasicBlock *BB,
767 DenseMap<const BasicBlock *, BBState> &BBStates,
768 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000769 bool VisitInstructionTopDown(Instruction *Inst,
770 DenseMap<Value *, RRInfo> &Releases,
771 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000772 bool VisitTopDown(BasicBlock *BB,
773 DenseMap<const BasicBlock *, BBState> &BBStates,
774 DenseMap<Value *, RRInfo> &Releases);
775 bool Visit(Function &F,
776 DenseMap<const BasicBlock *, BBState> &BBStates,
777 MapVector<Value *, RRInfo> &Retains,
778 DenseMap<Value *, RRInfo> &Releases);
779
780 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
781 MapVector<Value *, RRInfo> &Retains,
782 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +0000783 SmallVectorImpl<Instruction *> &DeadInsts,
784 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000785
Michael Gottesman9de6f962013-01-22 21:49:00 +0000786 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
787 MapVector<Value *, RRInfo> &Retains,
788 DenseMap<Value *, RRInfo> &Releases,
789 Module *M,
790 SmallVector<Instruction *, 4> &NewRetains,
791 SmallVector<Instruction *, 4> &NewReleases,
792 SmallVector<Instruction *, 8> &DeadInsts,
793 RRInfo &RetainsToMove,
794 RRInfo &ReleasesToMove,
795 Value *Arg,
796 bool KnownSafe,
797 bool &AnyPairsCompletelyEliminated);
798
John McCalld935e9c2011-06-15 23:37:01 +0000799 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
800 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +0000801 DenseMap<Value *, RRInfo> &Releases,
802 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000803
804 void OptimizeWeakCalls(Function &F);
805
806 bool OptimizeSequences(Function &F);
807
808 void OptimizeReturns(Function &F);
809
810 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
811 virtual bool doInitialization(Module &M);
812 virtual bool runOnFunction(Function &F);
813 virtual void releaseMemory();
814
815 public:
816 static char ID;
817 ObjCARCOpt() : FunctionPass(ID) {
818 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
819 }
820 };
821}
822
823char ObjCARCOpt::ID = 0;
824INITIALIZE_PASS_BEGIN(ObjCARCOpt,
825 "objc-arc", "ObjC ARC optimization", false, false)
826INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
827INITIALIZE_PASS_END(ObjCARCOpt,
828 "objc-arc", "ObjC ARC optimization", false, false)
829
830Pass *llvm::createObjCARCOptPass() {
831 return new ObjCARCOpt();
832}
833
834void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
835 AU.addRequired<ObjCARCAliasAnalysis>();
836 AU.addRequired<AliasAnalysis>();
837 // ARC optimization doesn't currently split critical edges.
838 AU.setPreservesCFG();
839}
840
Dan Gohman728db492012-01-13 00:39:07 +0000841bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
842 // Without the magic metadata tag, we have to assume this might be an
843 // objc_retainBlock call inserted to convert a block pointer to an id,
844 // in which case it really is needed.
845 if (!Inst->getMetadata(CopyOnEscapeMDKind))
846 return false;
847
848 // If the pointer "escapes" (not including being used in a call),
849 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000850 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +0000851 return false;
852
853 // Otherwise, it's not needed.
854 return true;
855}
856
John McCalld935e9c2011-06-15 23:37:01 +0000857Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
858 if (!RetainRVCallee) {
859 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000860 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000861 Type *Params[] = { I8X };
862 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000863 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000864 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
865 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000866 RetainRVCallee =
867 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000868 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000869 }
870 return RetainRVCallee;
871}
872
873Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
874 if (!AutoreleaseRVCallee) {
875 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000876 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000877 Type *Params[] = { I8X };
878 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000879 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000880 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
881 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000882 AutoreleaseRVCallee =
883 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000884 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000885 }
886 return AutoreleaseRVCallee;
887}
888
889Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
890 if (!ReleaseCallee) {
891 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000892 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000893 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000894 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
895 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000896 ReleaseCallee =
897 M->getOrInsertFunction(
898 "objc_release",
899 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000900 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000901 }
902 return ReleaseCallee;
903}
904
905Constant *ObjCARCOpt::getRetainCallee(Module *M) {
906 if (!RetainCallee) {
907 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000908 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000909 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000910 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
911 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000912 RetainCallee =
913 M->getOrInsertFunction(
914 "objc_retain",
915 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000916 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000917 }
918 return RetainCallee;
919}
920
Dan Gohman6320f522011-07-22 22:29:21 +0000921Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
922 if (!RetainBlockCallee) {
923 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000924 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +0000925 // objc_retainBlock is not nounwind because it calls user copy constructors
926 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +0000927 RetainBlockCallee =
928 M->getOrInsertFunction(
929 "objc_retainBlock",
930 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +0000931 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +0000932 }
933 return RetainBlockCallee;
934}
935
John McCalld935e9c2011-06-15 23:37:01 +0000936Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
937 if (!AutoreleaseCallee) {
938 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000939 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000940 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000941 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
942 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000943 AutoreleaseCallee =
944 M->getOrInsertFunction(
945 "objc_autorelease",
946 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000947 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000948 }
949 return AutoreleaseCallee;
950}
951
Michael Gottesman97e3df02013-01-14 00:35:14 +0000952/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
953/// return value.
John McCalld935e9c2011-06-15 23:37:01 +0000954void
955ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +0000956 ImmutableCallSite CS(GetObjCArg(Retain));
957 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +0000958 if (!Call) return;
959 if (Call->getParent() != Retain->getParent()) return;
960
961 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +0000962 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000963 ++I;
964 while (isNoopInstruction(I)) ++I;
965 if (&*I != Retain)
966 return;
967
968 // Turn it to an objc_retainAutoreleasedReturnValue..
969 Changed = true;
970 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000971
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000972 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +0000973 "objc_retain => objc_retainAutoreleasedReturnValue"
974 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000975 " Old: "
976 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000977
John McCalld935e9c2011-06-15 23:37:01 +0000978 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000979
980 DEBUG(dbgs() << " New: "
981 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000982}
983
Michael Gottesman97e3df02013-01-14 00:35:14 +0000984/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
985/// not a return value. Or, if it can be paired with an
986/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000987bool
988ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000989 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +0000990 const Value *Arg = GetObjCArg(RetainRV);
991 ImmutableCallSite CS(Arg);
992 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000993 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000994 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000995 ++I;
996 while (isNoopInstruction(I)) ++I;
997 if (&*I == RetainRV)
998 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000999 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001000 BasicBlock *RetainRVParent = RetainRV->getParent();
1001 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001002 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001003 while (isNoopInstruction(I)) ++I;
1004 if (&*I == RetainRV)
1005 return false;
1006 }
John McCalld935e9c2011-06-15 23:37:01 +00001007 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001008 }
John McCalld935e9c2011-06-15 23:37:01 +00001009
1010 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1011 // pointer. In this case, we can delete the pair.
1012 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1013 if (I != Begin) {
1014 do --I; while (I != Begin && isNoopInstruction(I));
1015 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1016 GetObjCArg(I) == Arg) {
1017 Changed = true;
1018 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001019
Michael Gottesman5c32ce92013-01-05 17:55:35 +00001020 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1021 << " Erasing " << *RetainRV
1022 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001023
John McCalld935e9c2011-06-15 23:37:01 +00001024 EraseInstruction(I);
1025 EraseInstruction(RetainRV);
1026 return true;
1027 }
1028 }
1029
1030 // Turn it to a plain objc_retain.
1031 Changed = true;
1032 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001033
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001034 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1035 "objc_retainAutoreleasedReturnValue => "
1036 "objc_retain since the operand is not a return value.\n"
1037 " Old: "
1038 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001039
John McCalld935e9c2011-06-15 23:37:01 +00001040 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001041
1042 DEBUG(dbgs() << " New: "
1043 << *RetainRV << "\n");
1044
John McCalld935e9c2011-06-15 23:37:01 +00001045 return false;
1046}
1047
Michael Gottesman97e3df02013-01-14 00:35:14 +00001048/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1049/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001050void
Michael Gottesman556ff612013-01-12 01:25:19 +00001051ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1052 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001053 // Check for a return of the pointer value.
1054 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001055 SmallVector<const Value *, 2> Users;
1056 Users.push_back(Ptr);
1057 do {
1058 Ptr = Users.pop_back_val();
1059 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1060 UI != UE; ++UI) {
1061 const User *I = *UI;
1062 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1063 return;
1064 if (isa<BitCastInst>(I))
1065 Users.push_back(I);
1066 }
1067 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001068
1069 Changed = true;
1070 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001071
1072 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1073 "objc_autoreleaseReturnValue => "
1074 "objc_autorelease since its operand is not used as a return "
1075 "value.\n"
1076 " Old: "
1077 << *AutoreleaseRV << "\n");
1078
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001079 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1080 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001081 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001082 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001083 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001084
Michael Gottesman1bf69082013-01-06 21:07:11 +00001085 DEBUG(dbgs() << " New: "
1086 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001087
John McCalld935e9c2011-06-15 23:37:01 +00001088}
1089
Michael Gottesman97e3df02013-01-14 00:35:14 +00001090/// Visit each call, one at a time, and make simplifications without doing any
1091/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001092void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1093 // Reset all the flags in preparation for recomputing them.
1094 UsedInThisFunction = 0;
1095
1096 // Visit all objc_* calls in F.
1097 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1098 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001099
John McCalld935e9c2011-06-15 23:37:01 +00001100 InstructionClass Class = GetBasicInstructionClass(Inst);
1101
Michael Gottesmand359e062013-01-18 03:08:39 +00001102 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1103 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001104
John McCalld935e9c2011-06-15 23:37:01 +00001105 switch (Class) {
1106 default: break;
1107
1108 // Delete no-op casts. These function calls have special semantics, but
1109 // the semantics are entirely implemented via lowering in the front-end,
1110 // so by the time they reach the optimizer, they are just no-op calls
1111 // which return their argument.
1112 //
1113 // There are gray areas here, as the ability to cast reference-counted
1114 // pointers to raw void* and back allows code to break ARC assumptions,
1115 // however these are currently considered to be unimportant.
1116 case IC_NoopCast:
1117 Changed = true;
1118 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00001119 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1120 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001121 EraseInstruction(Inst);
1122 continue;
1123
1124 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1125 case IC_StoreWeak:
1126 case IC_LoadWeak:
1127 case IC_LoadWeakRetained:
1128 case IC_InitWeak:
1129 case IC_DestroyWeak: {
1130 CallInst *CI = cast<CallInst>(Inst);
1131 if (isNullOrUndef(CI->getArgOperand(0))) {
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 Gottesman10426b52013-01-07 21:26:07 +00001137 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001138 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1139 "pointer-to-weak-pointer is undefined behavior.\n"
1140 " Old = " << *CI <<
1141 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00001142 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001143 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001144 CI->eraseFromParent();
1145 continue;
1146 }
1147 break;
1148 }
1149 case IC_CopyWeak:
1150 case IC_MoveWeak: {
1151 CallInst *CI = cast<CallInst>(Inst);
1152 if (isNullOrUndef(CI->getArgOperand(0)) ||
1153 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001154 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001155 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001156 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1157 Constant::getNullValue(Ty),
1158 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001159
1160 llvm::Value *NewValue = UndefValue::get(CI->getType());
1161 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1162 "pointer-to-weak-pointer is undefined behavior.\n"
1163 " Old = " << *CI <<
1164 "\n New = " <<
1165 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001166
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001167 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001168 CI->eraseFromParent();
1169 continue;
1170 }
1171 break;
1172 }
1173 case IC_Retain:
1174 OptimizeRetainCall(F, Inst);
1175 break;
1176 case IC_RetainRV:
1177 if (OptimizeRetainRVCall(F, Inst))
1178 continue;
1179 break;
1180 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001181 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001182 break;
1183 }
1184
1185 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1186 if (IsAutorelease(Class) && Inst->use_empty()) {
1187 CallInst *Call = cast<CallInst>(Inst);
1188 const Value *Arg = Call->getArgOperand(0);
1189 Arg = FindSingleUseIdentifiedObject(Arg);
1190 if (Arg) {
1191 Changed = true;
1192 ++NumAutoreleases;
1193
1194 // Create the declaration lazily.
1195 LLVMContext &C = Inst->getContext();
1196 CallInst *NewCall =
1197 CallInst::Create(getReleaseCallee(F.getParent()),
1198 Call->getArgOperand(0), "", Call);
1199 NewCall->setMetadata(ImpreciseReleaseMDKind,
1200 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001201
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001202 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1203 "objc_autorelease(x) with objc_release(x) since x is "
1204 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00001205 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001206 "\n New: " <<
1207 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001208
John McCalld935e9c2011-06-15 23:37:01 +00001209 EraseInstruction(Call);
1210 Inst = NewCall;
1211 Class = IC_Release;
1212 }
1213 }
1214
1215 // For functions which can never be passed stack arguments, add
1216 // a tail keyword.
1217 if (IsAlwaysTail(Class)) {
1218 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00001219 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1220 " to function since it can never be passed stack args: " << *Inst <<
1221 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001222 cast<CallInst>(Inst)->setTailCall();
1223 }
1224
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001225 // Ensure that functions that can never have a "tail" keyword due to the
1226 // semantics of ARC truly do not do so.
1227 if (IsNeverTail(Class)) {
1228 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001229 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1230 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001231 "\n");
1232 cast<CallInst>(Inst)->setTailCall(false);
1233 }
1234
John McCalld935e9c2011-06-15 23:37:01 +00001235 // Set nounwind as needed.
1236 if (IsNoThrow(Class)) {
1237 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00001238 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1239 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001240 cast<CallInst>(Inst)->setDoesNotThrow();
1241 }
1242
1243 if (!IsNoopOnNull(Class)) {
1244 UsedInThisFunction |= 1 << Class;
1245 continue;
1246 }
1247
1248 const Value *Arg = GetObjCArg(Inst);
1249
1250 // ARC calls with null are no-ops. Delete them.
1251 if (isNullOrUndef(Arg)) {
1252 Changed = true;
1253 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00001254 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1255 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001256 EraseInstruction(Inst);
1257 continue;
1258 }
1259
1260 // Keep track of which of retain, release, autorelease, and retain_block
1261 // are actually present in this function.
1262 UsedInThisFunction |= 1 << Class;
1263
1264 // If Arg is a PHI, and one or more incoming values to the
1265 // PHI are null, and the call is control-equivalent to the PHI, and there
1266 // are no relevant side effects between the PHI and the call, the call
1267 // could be pushed up to just those paths with non-null incoming values.
1268 // For now, don't bother splitting critical edges for this.
1269 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1270 Worklist.push_back(std::make_pair(Inst, Arg));
1271 do {
1272 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1273 Inst = Pair.first;
1274 Arg = Pair.second;
1275
1276 const PHINode *PN = dyn_cast<PHINode>(Arg);
1277 if (!PN) continue;
1278
1279 // Determine if the PHI has any null operands, or any incoming
1280 // critical edges.
1281 bool HasNull = false;
1282 bool HasCriticalEdges = false;
1283 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1284 Value *Incoming =
1285 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1286 if (isNullOrUndef(Incoming))
1287 HasNull = true;
1288 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1289 .getNumSuccessors() != 1) {
1290 HasCriticalEdges = true;
1291 break;
1292 }
1293 }
1294 // If we have null operands and no critical edges, optimize.
1295 if (!HasCriticalEdges && HasNull) {
1296 SmallPtrSet<Instruction *, 4> DependingInstructions;
1297 SmallPtrSet<const BasicBlock *, 4> Visited;
1298
1299 // Check that there is nothing that cares about the reference
1300 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001301 switch (Class) {
1302 case IC_Retain:
1303 case IC_RetainBlock:
1304 // These can always be moved up.
1305 break;
1306 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001307 // These can't be moved across things that care about the retain
1308 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001309 FindDependencies(NeedsPositiveRetainCount, Arg,
1310 Inst->getParent(), Inst,
1311 DependingInstructions, Visited, PA);
1312 break;
1313 case IC_Autorelease:
1314 // These can't be moved across autorelease pool scope boundaries.
1315 FindDependencies(AutoreleasePoolBoundary, Arg,
1316 Inst->getParent(), Inst,
1317 DependingInstructions, Visited, PA);
1318 break;
1319 case IC_RetainRV:
1320 case IC_AutoreleaseRV:
1321 // Don't move these; the RV optimization depends on the autoreleaseRV
1322 // being tail called, and the retainRV being immediately after a call
1323 // (which might still happen if we get lucky with codegen layout, but
1324 // it's not worth taking the chance).
1325 continue;
1326 default:
1327 llvm_unreachable("Invalid dependence flavor");
1328 }
1329
John McCalld935e9c2011-06-15 23:37:01 +00001330 if (DependingInstructions.size() == 1 &&
1331 *DependingInstructions.begin() == PN) {
1332 Changed = true;
1333 ++NumPartialNoops;
1334 // Clone the call into each predecessor that has a non-null value.
1335 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001336 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1338 Value *Incoming =
1339 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1340 if (!isNullOrUndef(Incoming)) {
1341 CallInst *Clone = cast<CallInst>(CInst->clone());
1342 Value *Op = PN->getIncomingValue(i);
1343 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1344 if (Op->getType() != ParamTy)
1345 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1346 Clone->setArgOperand(0, Op);
1347 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001348
1349 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1350 << *CInst << "\n"
1351 " And inserting "
1352 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001353 Worklist.push_back(std::make_pair(Clone, Incoming));
1354 }
1355 }
1356 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001357 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001358 EraseInstruction(CInst);
1359 continue;
1360 }
1361 }
1362 } while (!Worklist.empty());
1363 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00001364 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00001365}
1366
Michael Gottesman97e3df02013-01-14 00:35:14 +00001367/// Check for critical edges, loop boundaries, irreducible control flow, or
1368/// other CFG structures where moving code across the edge would result in it
1369/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001370void
1371ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1372 DenseMap<const BasicBlock *, BBState> &BBStates,
1373 BBState &MyStates) const {
1374 // If any top-down local-use or possible-dec has a succ which is earlier in
1375 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001376 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001377 E = MyStates.top_down_ptr_end(); I != E; ++I)
1378 switch (I->second.GetSeq()) {
1379 default: break;
1380 case S_Use: {
1381 const Value *Arg = I->first;
1382 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1383 bool SomeSuccHasSame = false;
1384 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001385 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001386 succ_const_iterator SI(TI), SE(TI, false);
1387
Dan Gohman0155f302012-02-17 18:59:53 +00001388 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001389 Sequence SuccSSeq = S_None;
1390 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001391 // If VisitBottomUp has pointer information for this successor, take
1392 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001393 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1394 BBStates.find(*SI);
1395 assert(BBI != BBStates.end());
1396 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1397 SuccSSeq = SuccS.GetSeq();
1398 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001399 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001400 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001401 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001402 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001403 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001404 break;
1405 }
Dan Gohman12130272011-08-12 00:26:31 +00001406 continue;
1407 }
John McCalld935e9c2011-06-15 23:37:01 +00001408 case S_Use:
1409 SomeSuccHasSame = true;
1410 break;
1411 case S_Stop:
1412 case S_Release:
1413 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001414 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001415 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001416 break;
1417 case S_Retain:
1418 llvm_unreachable("bottom-up pointer in retain state!");
1419 }
Dan Gohman12130272011-08-12 00:26:31 +00001420 }
John McCalld935e9c2011-06-15 23:37:01 +00001421 // If the state at the other end of any of the successor edges
1422 // matches the current state, require all edges to match. This
1423 // guards against loops in the middle of a sequence.
1424 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001425 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001426 break;
John McCalld935e9c2011-06-15 23:37:01 +00001427 }
1428 case S_CanRelease: {
1429 const Value *Arg = I->first;
1430 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1431 bool SomeSuccHasSame = false;
1432 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001433 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001434 succ_const_iterator SI(TI), SE(TI, false);
1435
Dan Gohman0155f302012-02-17 18:59:53 +00001436 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001437 Sequence SuccSSeq = S_None;
1438 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001439 // If VisitBottomUp has pointer information for this successor, take
1440 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001441 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1442 BBStates.find(*SI);
1443 assert(BBI != BBStates.end());
1444 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1445 SuccSSeq = SuccS.GetSeq();
1446 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001447 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001448 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001449 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001450 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001451 break;
1452 }
Dan Gohman12130272011-08-12 00:26:31 +00001453 continue;
1454 }
John McCalld935e9c2011-06-15 23:37:01 +00001455 case S_CanRelease:
1456 SomeSuccHasSame = true;
1457 break;
1458 case S_Stop:
1459 case S_Release:
1460 case S_MovableRelease:
1461 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001462 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001463 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001464 break;
1465 case S_Retain:
1466 llvm_unreachable("bottom-up pointer in retain state!");
1467 }
Dan Gohman12130272011-08-12 00:26:31 +00001468 }
John McCalld935e9c2011-06-15 23:37:01 +00001469 // If the state at the other end of any of the successor edges
1470 // matches the current state, require all edges to match. This
1471 // guards against loops in the middle of a sequence.
1472 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001473 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001474 break;
John McCalld935e9c2011-06-15 23:37:01 +00001475 }
1476 }
1477}
1478
1479bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001480ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001481 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001482 MapVector<Value *, RRInfo> &Retains,
1483 BBState &MyStates) {
1484 bool NestingDetected = false;
1485 InstructionClass Class = GetInstructionClass(Inst);
1486 const Value *Arg = 0;
1487
1488 switch (Class) {
1489 case IC_Release: {
1490 Arg = GetObjCArg(Inst);
1491
1492 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1493
1494 // If we see two releases in a row on the same pointer. If so, make
1495 // a note, and we'll cicle back to revisit it after we've
1496 // hopefully eliminated the second release, which may allow us to
1497 // eliminate the first release too.
1498 // Theoretically we could implement removal of nested retain+release
1499 // pairs by making PtrState hold a stack of states, but this is
1500 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001501 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1502 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
1503 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001504 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001505 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001506
Dan Gohman817a7c62012-03-22 18:24:56 +00001507 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00001508 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00001509 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001510 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001511 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1512 S.RRI.Calls.insert(Inst);
1513
Dan Gohmandf476e52012-09-04 23:16:20 +00001514 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001515 break;
1516 }
1517 case IC_RetainBlock:
1518 // An objc_retainBlock call with just a use may need to be kept,
1519 // because it may be copying a block from the stack to the heap.
1520 if (!IsRetainBlockOptimizable(Inst))
1521 break;
1522 // FALLTHROUGH
1523 case IC_Retain:
1524 case IC_RetainRV: {
1525 Arg = GetObjCArg(Inst);
1526
1527 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001528 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001529
1530 switch (S.GetSeq()) {
1531 case S_Stop:
1532 case S_Release:
1533 case S_MovableRelease:
1534 case S_Use:
1535 S.RRI.ReverseInsertPts.clear();
1536 // FALL THROUGH
1537 case S_CanRelease:
1538 // Don't do retain+release tracking for IC_RetainRV, because it's
1539 // better to let it remain as the first instruction after a call.
1540 if (Class != IC_RetainRV) {
1541 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
1542 Retains[Inst] = S.RRI;
1543 }
1544 S.ClearSequenceProgress();
1545 break;
1546 case S_None:
1547 break;
1548 case S_Retain:
1549 llvm_unreachable("bottom-up pointer in retain state!");
1550 }
1551 return NestingDetected;
1552 }
1553 case IC_AutoreleasepoolPop:
1554 // Conservatively, clear MyStates for all known pointers.
1555 MyStates.clearBottomUpPointers();
1556 return NestingDetected;
1557 case IC_AutoreleasepoolPush:
1558 case IC_None:
1559 // These are irrelevant.
1560 return NestingDetected;
1561 default:
1562 break;
1563 }
1564
1565 // Consider any other possible effects of this instruction on each
1566 // pointer being tracked.
1567 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1568 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1569 const Value *Ptr = MI->first;
1570 if (Ptr == Arg)
1571 continue; // Handled above.
1572 PtrState &S = MI->second;
1573 Sequence Seq = S.GetSeq();
1574
1575 // Check for possible releases.
1576 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001577 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001578 switch (Seq) {
1579 case S_Use:
1580 S.SetSeq(S_CanRelease);
1581 continue;
1582 case S_CanRelease:
1583 case S_Release:
1584 case S_MovableRelease:
1585 case S_Stop:
1586 case S_None:
1587 break;
1588 case S_Retain:
1589 llvm_unreachable("bottom-up pointer in retain state!");
1590 }
1591 }
1592
1593 // Check for possible direct uses.
1594 switch (Seq) {
1595 case S_Release:
1596 case S_MovableRelease:
1597 if (CanUse(Inst, Ptr, PA, Class)) {
1598 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001599 // If this is an invoke instruction, we're scanning it as part of
1600 // one of its successor blocks, since we can't insert code after it
1601 // in its own block, and we don't want to split critical edges.
1602 if (isa<InvokeInst>(Inst))
1603 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1604 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001605 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001606 S.SetSeq(S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001607 } else if (Seq == S_Release && IsUser(Class)) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001608 // Non-movable releases depend on any possible objc pointer use.
1609 S.SetSeq(S_Stop);
1610 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001611 // As above; handle invoke specially.
1612 if (isa<InvokeInst>(Inst))
1613 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1614 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001615 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001616 }
1617 break;
1618 case S_Stop:
1619 if (CanUse(Inst, Ptr, PA, Class))
1620 S.SetSeq(S_Use);
1621 break;
1622 case S_CanRelease:
1623 case S_Use:
1624 case S_None:
1625 break;
1626 case S_Retain:
1627 llvm_unreachable("bottom-up pointer in retain state!");
1628 }
1629 }
1630
1631 return NestingDetected;
1632}
1633
1634bool
John McCalld935e9c2011-06-15 23:37:01 +00001635ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1636 DenseMap<const BasicBlock *, BBState> &BBStates,
1637 MapVector<Value *, RRInfo> &Retains) {
1638 bool NestingDetected = false;
1639 BBState &MyStates = BBStates[BB];
1640
1641 // Merge the states from each successor to compute the initial state
1642 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001643 BBState::edge_iterator SI(MyStates.succ_begin()),
1644 SE(MyStates.succ_end());
1645 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001646 const BasicBlock *Succ = *SI;
1647 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1648 assert(I != BBStates.end());
1649 MyStates.InitFromSucc(I->second);
1650 ++SI;
1651 for (; SI != SE; ++SI) {
1652 Succ = *SI;
1653 I = BBStates.find(Succ);
1654 assert(I != BBStates.end());
1655 MyStates.MergeSucc(I->second);
1656 }
Dan Gohman0155f302012-02-17 18:59:53 +00001657 }
John McCalld935e9c2011-06-15 23:37:01 +00001658
1659 // Visit all the instructions, bottom-up.
1660 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1661 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001662
1663 // Invoke instructions are visited as part of their successors (below).
1664 if (isa<InvokeInst>(Inst))
1665 continue;
1666
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001667 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
1668
Dan Gohman5c70fad2012-03-23 17:47:54 +00001669 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1670 }
1671
Dan Gohmandae33492012-04-27 18:56:31 +00001672 // If there's a predecessor with an invoke, visit the invoke as if it were
1673 // part of this block, since we can't insert code after an invoke in its own
1674 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001675 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1676 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001677 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001678 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1679 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001680 }
John McCalld935e9c2011-06-15 23:37:01 +00001681
Dan Gohman817a7c62012-03-22 18:24:56 +00001682 return NestingDetected;
1683}
John McCalld935e9c2011-06-15 23:37:01 +00001684
Dan Gohman817a7c62012-03-22 18:24:56 +00001685bool
1686ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1687 DenseMap<Value *, RRInfo> &Releases,
1688 BBState &MyStates) {
1689 bool NestingDetected = false;
1690 InstructionClass Class = GetInstructionClass(Inst);
1691 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001692
Dan Gohman817a7c62012-03-22 18:24:56 +00001693 switch (Class) {
1694 case IC_RetainBlock:
1695 // An objc_retainBlock call with just a use may need to be kept,
1696 // because it may be copying a block from the stack to the heap.
1697 if (!IsRetainBlockOptimizable(Inst))
1698 break;
1699 // FALLTHROUGH
1700 case IC_Retain:
1701 case IC_RetainRV: {
1702 Arg = GetObjCArg(Inst);
1703
1704 PtrState &S = MyStates.getPtrTopDownState(Arg);
1705
1706 // Don't do retain+release tracking for IC_RetainRV, because it's
1707 // better to let it remain as the first instruction after a call.
1708 if (Class != IC_RetainRV) {
1709 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001710 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001711 // hopefully eliminated the second retain, which may allow us to
1712 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001713 // Theoretically we could implement removal of nested retain+release
1714 // pairs by making PtrState hold a stack of states, but this is
1715 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00001716 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00001717 NestingDetected = true;
1718
Dan Gohman62079b42012-04-25 00:50:46 +00001719 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00001720 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Michael Gottesman07beea42013-03-23 05:31:01 +00001721 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001722 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001723 }
John McCalld935e9c2011-06-15 23:37:01 +00001724
Dan Gohmandf476e52012-09-04 23:16:20 +00001725 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001726
1727 // A retain can be a potential use; procede to the generic checking
1728 // code below.
1729 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001730 }
1731 case IC_Release: {
1732 Arg = GetObjCArg(Inst);
1733
1734 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00001735 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001736
1737 switch (S.GetSeq()) {
1738 case S_Retain:
1739 case S_CanRelease:
1740 S.RRI.ReverseInsertPts.clear();
1741 // FALL THROUGH
1742 case S_Use:
1743 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1744 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1745 Releases[Inst] = S.RRI;
1746 S.ClearSequenceProgress();
1747 break;
1748 case S_None:
1749 break;
1750 case S_Stop:
1751 case S_Release:
1752 case S_MovableRelease:
1753 llvm_unreachable("top-down pointer in release state!");
1754 }
1755 break;
1756 }
1757 case IC_AutoreleasepoolPop:
1758 // Conservatively, clear MyStates for all known pointers.
1759 MyStates.clearTopDownPointers();
1760 return NestingDetected;
1761 case IC_AutoreleasepoolPush:
1762 case IC_None:
1763 // These are irrelevant.
1764 return NestingDetected;
1765 default:
1766 break;
1767 }
1768
1769 // Consider any other possible effects of this instruction on each
1770 // pointer being tracked.
1771 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1772 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1773 const Value *Ptr = MI->first;
1774 if (Ptr == Arg)
1775 continue; // Handled above.
1776 PtrState &S = MI->second;
1777 Sequence Seq = S.GetSeq();
1778
1779 // Check for possible releases.
1780 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001781 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001782 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001783 case S_Retain:
1784 S.SetSeq(S_CanRelease);
1785 assert(S.RRI.ReverseInsertPts.empty());
1786 S.RRI.ReverseInsertPts.insert(Inst);
1787
1788 // One call can't cause a transition from S_Retain to S_CanRelease
1789 // and S_CanRelease to S_Use. If we've made the first transition,
1790 // we're done.
1791 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001792 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001793 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001794 case S_None:
1795 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001796 case S_Stop:
1797 case S_Release:
1798 case S_MovableRelease:
1799 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001800 }
1801 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001802
1803 // Check for possible direct uses.
1804 switch (Seq) {
1805 case S_CanRelease:
1806 if (CanUse(Inst, Ptr, PA, Class))
1807 S.SetSeq(S_Use);
1808 break;
1809 case S_Retain:
1810 case S_Use:
1811 case S_None:
1812 break;
1813 case S_Stop:
1814 case S_Release:
1815 case S_MovableRelease:
1816 llvm_unreachable("top-down pointer in release state!");
1817 }
John McCalld935e9c2011-06-15 23:37:01 +00001818 }
1819
1820 return NestingDetected;
1821}
1822
1823bool
1824ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1825 DenseMap<const BasicBlock *, BBState> &BBStates,
1826 DenseMap<Value *, RRInfo> &Releases) {
1827 bool NestingDetected = false;
1828 BBState &MyStates = BBStates[BB];
1829
1830 // Merge the states from each predecessor to compute the initial state
1831 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001832 BBState::edge_iterator PI(MyStates.pred_begin()),
1833 PE(MyStates.pred_end());
1834 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001835 const BasicBlock *Pred = *PI;
1836 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1837 assert(I != BBStates.end());
1838 MyStates.InitFromPred(I->second);
1839 ++PI;
1840 for (; PI != PE; ++PI) {
1841 Pred = *PI;
1842 I = BBStates.find(Pred);
1843 assert(I != BBStates.end());
1844 MyStates.MergePred(I->second);
1845 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001846 }
John McCalld935e9c2011-06-15 23:37:01 +00001847
1848 // Visit all the instructions, top-down.
1849 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1850 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001851
1852 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
1853
Dan Gohman817a7c62012-03-22 18:24:56 +00001854 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001855 }
1856
1857 CheckForCFGHazards(BB, BBStates, MyStates);
1858 return NestingDetected;
1859}
1860
Dan Gohmana53a12c2011-12-12 19:42:25 +00001861static void
1862ComputePostOrders(Function &F,
1863 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001864 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1865 unsigned NoObjCARCExceptionsMDKind,
1866 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001867 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001868 SmallPtrSet<BasicBlock *, 16> Visited;
1869
1870 // Do DFS, computing the PostOrder.
1871 SmallPtrSet<BasicBlock *, 16> OnStack;
1872 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001873
1874 // Functions always have exactly one entry block, and we don't have
1875 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001876 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001877 BBState &MyStates = BBStates[EntryBB];
1878 MyStates.SetAsEntry();
1879 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1880 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001881 Visited.insert(EntryBB);
1882 OnStack.insert(EntryBB);
1883 do {
1884 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001885 BasicBlock *CurrBB = SuccStack.back().first;
1886 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1887 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001888
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001889 while (SuccStack.back().second != SE) {
1890 BasicBlock *SuccBB = *SuccStack.back().second++;
1891 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00001892 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1893 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001894 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001895 BBState &SuccStates = BBStates[SuccBB];
1896 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001897 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001898 goto dfs_next_succ;
1899 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001900
1901 if (!OnStack.count(SuccBB)) {
1902 BBStates[CurrBB].addSucc(SuccBB);
1903 BBStates[SuccBB].addPred(CurrBB);
1904 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001905 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001906 OnStack.erase(CurrBB);
1907 PostOrder.push_back(CurrBB);
1908 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001909 } while (!SuccStack.empty());
1910
1911 Visited.clear();
1912
Dan Gohmana53a12c2011-12-12 19:42:25 +00001913 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001914 // Functions may have many exits, and there also blocks which we treat
1915 // as exits due to ignored edges.
1916 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1917 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1918 BasicBlock *ExitBB = I;
1919 BBState &MyStates = BBStates[ExitBB];
1920 if (!MyStates.isExit())
1921 continue;
1922
Dan Gohmandae33492012-04-27 18:56:31 +00001923 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001924
1925 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001926 Visited.insert(ExitBB);
1927 while (!PredStack.empty()) {
1928 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001929 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1930 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001931 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001932 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001933 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001934 goto reverse_dfs_next_succ;
1935 }
1936 }
1937 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1938 }
1939 }
1940}
1941
Michael Gottesman97e3df02013-01-14 00:35:14 +00001942// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001943bool
1944ObjCARCOpt::Visit(Function &F,
1945 DenseMap<const BasicBlock *, BBState> &BBStates,
1946 MapVector<Value *, RRInfo> &Retains,
1947 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001948
1949 // Use reverse-postorder traversals, because we magically know that loops
1950 // will be well behaved, i.e. they won't repeatedly call retain on a single
1951 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1952 // class here because we want the reverse-CFG postorder to consider each
1953 // function exit point, and we want to ignore selected cycle edges.
1954 SmallVector<BasicBlock *, 16> PostOrder;
1955 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001956 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1957 NoObjCARCExceptionsMDKind,
1958 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001959
1960 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001961 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001962 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001963 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1964 I != E; ++I)
1965 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001966
Dan Gohmana53a12c2011-12-12 19:42:25 +00001967 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001968 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001969 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1970 PostOrder.rbegin(), E = PostOrder.rend();
1971 I != E; ++I)
1972 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001973
1974 return TopDownNestingDetected && BottomUpNestingDetected;
1975}
1976
Michael Gottesman97e3df02013-01-14 00:35:14 +00001977/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00001978void ObjCARCOpt::MoveCalls(Value *Arg,
1979 RRInfo &RetainsToMove,
1980 RRInfo &ReleasesToMove,
1981 MapVector<Value *, RRInfo> &Retains,
1982 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001983 SmallVectorImpl<Instruction *> &DeadInsts,
1984 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001985 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001986 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00001987
1988 // Insert the new retain and release calls.
1989 for (SmallPtrSet<Instruction *, 2>::const_iterator
1990 PI = ReleasesToMove.ReverseInsertPts.begin(),
1991 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
1992 Instruction *InsertPt = *PI;
1993 Value *MyArg = ArgTy == ParamTy ? Arg :
1994 new BitCastInst(Arg, ParamTy, "", InsertPt);
1995 CallInst *Call =
1996 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00001997 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00001998 MyArg, "", InsertPt);
1999 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00002000 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00002001 Call->setMetadata(CopyOnEscapeMDKind,
2002 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00002003 else
John McCalld935e9c2011-06-15 23:37:01 +00002004 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002005
2006 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2007 << "\n"
2008 " At insertion point: " << *InsertPt
2009 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002010 }
2011 for (SmallPtrSet<Instruction *, 2>::const_iterator
2012 PI = RetainsToMove.ReverseInsertPts.begin(),
2013 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002014 Instruction *InsertPt = *PI;
2015 Value *MyArg = ArgTy == ParamTy ? Arg :
2016 new BitCastInst(Arg, ParamTy, "", InsertPt);
2017 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2018 "", InsertPt);
2019 // Attach a clang.imprecise_release metadata tag, if appropriate.
2020 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2021 Call->setMetadata(ImpreciseReleaseMDKind, M);
2022 Call->setDoesNotThrow();
2023 if (ReleasesToMove.IsTailCallRelease)
2024 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002025
2026 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2027 << "\n"
2028 " At insertion point: " << *InsertPt
2029 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002030 }
2031
2032 // Delete the original retain and release calls.
2033 for (SmallPtrSet<Instruction *, 2>::const_iterator
2034 AI = RetainsToMove.Calls.begin(),
2035 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2036 Instruction *OrigRetain = *AI;
2037 Retains.blot(OrigRetain);
2038 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002039 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2040 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002041 }
2042 for (SmallPtrSet<Instruction *, 2>::const_iterator
2043 AI = ReleasesToMove.Calls.begin(),
2044 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2045 Instruction *OrigRelease = *AI;
2046 Releases.erase(OrigRelease);
2047 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002048 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2049 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002050 }
2051}
2052
Michael Gottesman9de6f962013-01-22 21:49:00 +00002053bool
2054ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2055 &BBStates,
2056 MapVector<Value *, RRInfo> &Retains,
2057 DenseMap<Value *, RRInfo> &Releases,
2058 Module *M,
2059 SmallVector<Instruction *, 4> &NewRetains,
2060 SmallVector<Instruction *, 4> &NewReleases,
2061 SmallVector<Instruction *, 8> &DeadInsts,
2062 RRInfo &RetainsToMove,
2063 RRInfo &ReleasesToMove,
2064 Value *Arg,
2065 bool KnownSafe,
2066 bool &AnyPairsCompletelyEliminated) {
2067 // If a pair happens in a region where it is known that the reference count
2068 // is already incremented, we can similarly ignore possible decrements.
2069 bool KnownSafeTD = true, KnownSafeBU = true;
2070
2071 // Connect the dots between the top-down-collected RetainsToMove and
2072 // bottom-up-collected ReleasesToMove to form sets of related calls.
2073 // This is an iterative process so that we connect multiple releases
2074 // to multiple retains if needed.
2075 unsigned OldDelta = 0;
2076 unsigned NewDelta = 0;
2077 unsigned OldCount = 0;
2078 unsigned NewCount = 0;
2079 bool FirstRelease = true;
2080 bool FirstRetain = true;
2081 for (;;) {
2082 for (SmallVectorImpl<Instruction *>::const_iterator
2083 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2084 Instruction *NewRetain = *NI;
2085 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2086 assert(It != Retains.end());
2087 const RRInfo &NewRetainRRI = It->second;
2088 KnownSafeTD &= NewRetainRRI.KnownSafe;
2089 for (SmallPtrSet<Instruction *, 2>::const_iterator
2090 LI = NewRetainRRI.Calls.begin(),
2091 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2092 Instruction *NewRetainRelease = *LI;
2093 DenseMap<Value *, RRInfo>::const_iterator Jt =
2094 Releases.find(NewRetainRelease);
2095 if (Jt == Releases.end())
2096 return false;
2097 const RRInfo &NewRetainReleaseRRI = Jt->second;
2098 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2099 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2100 OldDelta -=
2101 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2102
2103 // Merge the ReleaseMetadata and IsTailCallRelease values.
2104 if (FirstRelease) {
2105 ReleasesToMove.ReleaseMetadata =
2106 NewRetainReleaseRRI.ReleaseMetadata;
2107 ReleasesToMove.IsTailCallRelease =
2108 NewRetainReleaseRRI.IsTailCallRelease;
2109 FirstRelease = false;
2110 } else {
2111 if (ReleasesToMove.ReleaseMetadata !=
2112 NewRetainReleaseRRI.ReleaseMetadata)
2113 ReleasesToMove.ReleaseMetadata = 0;
2114 if (ReleasesToMove.IsTailCallRelease !=
2115 NewRetainReleaseRRI.IsTailCallRelease)
2116 ReleasesToMove.IsTailCallRelease = false;
2117 }
2118
2119 // Collect the optimal insertion points.
2120 if (!KnownSafe)
2121 for (SmallPtrSet<Instruction *, 2>::const_iterator
2122 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2123 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2124 RI != RE; ++RI) {
2125 Instruction *RIP = *RI;
2126 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2127 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2128 }
2129 NewReleases.push_back(NewRetainRelease);
2130 }
2131 }
2132 }
2133 NewRetains.clear();
2134 if (NewReleases.empty()) break;
2135
2136 // Back the other way.
2137 for (SmallVectorImpl<Instruction *>::const_iterator
2138 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2139 Instruction *NewRelease = *NI;
2140 DenseMap<Value *, RRInfo>::const_iterator It =
2141 Releases.find(NewRelease);
2142 assert(It != Releases.end());
2143 const RRInfo &NewReleaseRRI = It->second;
2144 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2145 for (SmallPtrSet<Instruction *, 2>::const_iterator
2146 LI = NewReleaseRRI.Calls.begin(),
2147 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2148 Instruction *NewReleaseRetain = *LI;
2149 MapVector<Value *, RRInfo>::const_iterator Jt =
2150 Retains.find(NewReleaseRetain);
2151 if (Jt == Retains.end())
2152 return false;
2153 const RRInfo &NewReleaseRetainRRI = Jt->second;
2154 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2155 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2156 unsigned PathCount =
2157 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2158 OldDelta += PathCount;
2159 OldCount += PathCount;
2160
2161 // Merge the IsRetainBlock values.
2162 if (FirstRetain) {
2163 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2164 FirstRetain = false;
2165 } else if (ReleasesToMove.IsRetainBlock !=
2166 NewReleaseRetainRRI.IsRetainBlock)
2167 // It's not possible to merge the sequences if one uses
2168 // objc_retain and the other uses objc_retainBlock.
2169 return false;
2170
2171 // Collect the optimal insertion points.
2172 if (!KnownSafe)
2173 for (SmallPtrSet<Instruction *, 2>::const_iterator
2174 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2175 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2176 RI != RE; ++RI) {
2177 Instruction *RIP = *RI;
2178 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2179 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2180 NewDelta += PathCount;
2181 NewCount += PathCount;
2182 }
2183 }
2184 NewRetains.push_back(NewReleaseRetain);
2185 }
2186 }
2187 }
2188 NewReleases.clear();
2189 if (NewRetains.empty()) break;
2190 }
2191
2192 // If the pointer is known incremented or nested, we can safely delete the
2193 // pair regardless of what's between them.
2194 if (KnownSafeTD || KnownSafeBU) {
2195 RetainsToMove.ReverseInsertPts.clear();
2196 ReleasesToMove.ReverseInsertPts.clear();
2197 NewCount = 0;
2198 } else {
2199 // Determine whether the new insertion points we computed preserve the
2200 // balance of retain and release calls through the program.
2201 // TODO: If the fully aggressive solution isn't valid, try to find a
2202 // less aggressive solution which is.
2203 if (NewDelta != 0)
2204 return false;
2205 }
2206
2207 // Determine whether the original call points are balanced in the retain and
2208 // release calls through the program. If not, conservatively don't touch
2209 // them.
2210 // TODO: It's theoretically possible to do code motion in this case, as
2211 // long as the existing imbalances are maintained.
2212 if (OldDelta != 0)
2213 return false;
2214
2215 Changed = true;
2216 assert(OldCount != 0 && "Unreachable code?");
2217 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002218 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002219 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002220
2221 // We can move calls!
2222 return true;
2223}
2224
Michael Gottesman97e3df02013-01-14 00:35:14 +00002225/// Identify pairings between the retains and releases, and delete and/or move
2226/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002227bool
2228ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2229 &BBStates,
2230 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002231 DenseMap<Value *, RRInfo> &Releases,
2232 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00002233 bool AnyPairsCompletelyEliminated = false;
2234 RRInfo RetainsToMove;
2235 RRInfo ReleasesToMove;
2236 SmallVector<Instruction *, 4> NewRetains;
2237 SmallVector<Instruction *, 4> NewReleases;
2238 SmallVector<Instruction *, 8> DeadInsts;
2239
Dan Gohman670f9372012-04-13 18:57:48 +00002240 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002241 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002242 E = Retains.end(); I != E; ++I) {
2243 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002244 if (!V) continue; // blotted
2245
2246 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002247
2248 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2249 << "\n");
2250
John McCalld935e9c2011-06-15 23:37:01 +00002251 Value *Arg = GetObjCArg(Retain);
2252
Dan Gohman728db492012-01-13 00:39:07 +00002253 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002254 // not being managed by ObjC reference counting, so we can delete pairs
2255 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002256 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002257
Dan Gohman56e1cef2011-08-22 17:29:11 +00002258 // A constant pointer can't be pointing to an object on the heap. It may
2259 // be reference-counted, but it won't be deleted.
2260 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2261 if (const GlobalVariable *GV =
2262 dyn_cast<GlobalVariable>(
2263 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2264 if (GV->isConstant())
2265 KnownSafe = true;
2266
John McCalld935e9c2011-06-15 23:37:01 +00002267 // Connect the dots between the top-down-collected RetainsToMove and
2268 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002269 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002270 bool PerformMoveCalls =
2271 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2272 NewReleases, DeadInsts, RetainsToMove,
2273 ReleasesToMove, Arg, KnownSafe,
2274 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002275
Michael Gottesman9de6f962013-01-22 21:49:00 +00002276 if (PerformMoveCalls) {
2277 // Ok, everything checks out and we're all set. Let's move/delete some
2278 // code!
2279 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2280 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002281 }
2282
Michael Gottesman9de6f962013-01-22 21:49:00 +00002283 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002284 NewReleases.clear();
2285 NewRetains.clear();
2286 RetainsToMove.clear();
2287 ReleasesToMove.clear();
2288 }
2289
2290 // Now that we're done moving everything, we can delete the newly dead
2291 // instructions, as we no longer need them as insert points.
2292 while (!DeadInsts.empty())
2293 EraseInstruction(DeadInsts.pop_back_val());
2294
2295 return AnyPairsCompletelyEliminated;
2296}
2297
Michael Gottesman97e3df02013-01-14 00:35:14 +00002298/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002299void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2300 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2301 // itself because it uses AliasAnalysis and we need to do provenance
2302 // queries instead.
2303 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2304 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002305
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002306 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00002307 "\n");
2308
John McCalld935e9c2011-06-15 23:37:01 +00002309 InstructionClass Class = GetBasicInstructionClass(Inst);
2310 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2311 continue;
2312
2313 // Delete objc_loadWeak calls with no users.
2314 if (Class == IC_LoadWeak && Inst->use_empty()) {
2315 Inst->eraseFromParent();
2316 continue;
2317 }
2318
2319 // TODO: For now, just look for an earlier available version of this value
2320 // within the same block. Theoretically, we could do memdep-style non-local
2321 // analysis too, but that would want caching. A better approach would be to
2322 // use the technique that EarlyCSE uses.
2323 inst_iterator Current = llvm::prior(I);
2324 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2325 for (BasicBlock::iterator B = CurrentBB->begin(),
2326 J = Current.getInstructionIterator();
2327 J != B; --J) {
2328 Instruction *EarlierInst = &*llvm::prior(J);
2329 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2330 switch (EarlierClass) {
2331 case IC_LoadWeak:
2332 case IC_LoadWeakRetained: {
2333 // If this is loading from the same pointer, replace this load's value
2334 // with that one.
2335 CallInst *Call = cast<CallInst>(Inst);
2336 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2337 Value *Arg = Call->getArgOperand(0);
2338 Value *EarlierArg = EarlierCall->getArgOperand(0);
2339 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2340 case AliasAnalysis::MustAlias:
2341 Changed = true;
2342 // If the load has a builtin retain, insert a plain retain for it.
2343 if (Class == IC_LoadWeakRetained) {
2344 CallInst *CI =
2345 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2346 "", Call);
2347 CI->setTailCall();
2348 }
2349 // Zap the fully redundant load.
2350 Call->replaceAllUsesWith(EarlierCall);
2351 Call->eraseFromParent();
2352 goto clobbered;
2353 case AliasAnalysis::MayAlias:
2354 case AliasAnalysis::PartialAlias:
2355 goto clobbered;
2356 case AliasAnalysis::NoAlias:
2357 break;
2358 }
2359 break;
2360 }
2361 case IC_StoreWeak:
2362 case IC_InitWeak: {
2363 // If this is storing to the same pointer and has the same size etc.
2364 // replace this load's value with the stored value.
2365 CallInst *Call = cast<CallInst>(Inst);
2366 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2367 Value *Arg = Call->getArgOperand(0);
2368 Value *EarlierArg = EarlierCall->getArgOperand(0);
2369 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2370 case AliasAnalysis::MustAlias:
2371 Changed = true;
2372 // If the load has a builtin retain, insert a plain retain for it.
2373 if (Class == IC_LoadWeakRetained) {
2374 CallInst *CI =
2375 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2376 "", Call);
2377 CI->setTailCall();
2378 }
2379 // Zap the fully redundant load.
2380 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2381 Call->eraseFromParent();
2382 goto clobbered;
2383 case AliasAnalysis::MayAlias:
2384 case AliasAnalysis::PartialAlias:
2385 goto clobbered;
2386 case AliasAnalysis::NoAlias:
2387 break;
2388 }
2389 break;
2390 }
2391 case IC_MoveWeak:
2392 case IC_CopyWeak:
2393 // TOOD: Grab the copied value.
2394 goto clobbered;
2395 case IC_AutoreleasepoolPush:
2396 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002397 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002398 case IC_User:
2399 // Weak pointers are only modified through the weak entry points
2400 // (and arbitrary calls, which could call the weak entry points).
2401 break;
2402 default:
2403 // Anything else could modify the weak pointer.
2404 goto clobbered;
2405 }
2406 }
2407 clobbered:;
2408 }
2409
2410 // Then, for each destroyWeak with an alloca operand, check to see if
2411 // the alloca and all its users can be zapped.
2412 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2413 Instruction *Inst = &*I++;
2414 InstructionClass Class = GetBasicInstructionClass(Inst);
2415 if (Class != IC_DestroyWeak)
2416 continue;
2417
2418 CallInst *Call = cast<CallInst>(Inst);
2419 Value *Arg = Call->getArgOperand(0);
2420 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2421 for (Value::use_iterator UI = Alloca->use_begin(),
2422 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002423 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002424 switch (GetBasicInstructionClass(UserInst)) {
2425 case IC_InitWeak:
2426 case IC_StoreWeak:
2427 case IC_DestroyWeak:
2428 continue;
2429 default:
2430 goto done;
2431 }
2432 }
2433 Changed = true;
2434 for (Value::use_iterator UI = Alloca->use_begin(),
2435 UE = Alloca->use_end(); UI != UE; ) {
2436 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002437 switch (GetBasicInstructionClass(UserInst)) {
2438 case IC_InitWeak:
2439 case IC_StoreWeak:
2440 // These functions return their second argument.
2441 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2442 break;
2443 case IC_DestroyWeak:
2444 // No return value.
2445 break;
2446 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002447 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002448 }
John McCalld935e9c2011-06-15 23:37:01 +00002449 UserInst->eraseFromParent();
2450 }
2451 Alloca->eraseFromParent();
2452 done:;
2453 }
2454 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002455
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002456 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002457
John McCalld935e9c2011-06-15 23:37:01 +00002458}
2459
Michael Gottesman97e3df02013-01-14 00:35:14 +00002460/// Identify program paths which execute sequences of retains and releases which
2461/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002462bool ObjCARCOpt::OptimizeSequences(Function &F) {
2463 /// Releases, Retains - These are used to store the results of the main flow
2464 /// analysis. These use Value* as the key instead of Instruction* so that the
2465 /// map stays valid when we get around to rewriting code and calls get
2466 /// replaced by arguments.
2467 DenseMap<Value *, RRInfo> Releases;
2468 MapVector<Value *, RRInfo> Retains;
2469
Michael Gottesman97e3df02013-01-14 00:35:14 +00002470 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002471 /// states for each identified object at each block.
2472 DenseMap<const BasicBlock *, BBState> BBStates;
2473
2474 // Analyze the CFG of the function, and all instructions.
2475 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2476
2477 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002478 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2479 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002480}
2481
Michael Gottesman97e3df02013-01-14 00:35:14 +00002482/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002483/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002484/// %call = call i8* @something(...)
2485/// %2 = call i8* @objc_retain(i8* %call)
2486/// %3 = call i8* @objc_autorelease(i8* %2)
2487/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002488/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002489/// And delete the retain and autorelease.
2490///
2491/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002492/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002493/// %3 = call i8* @objc_autorelease(i8* %2)
2494/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002495/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002496/// convert the autorelease to autoreleaseRV.
2497void ObjCARCOpt::OptimizeReturns(Function &F) {
2498 if (!F.getReturnType()->isPointerTy())
2499 return;
2500
2501 SmallPtrSet<Instruction *, 4> DependingInstructions;
2502 SmallPtrSet<const BasicBlock *, 4> Visited;
2503 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2504 BasicBlock *BB = FI;
2505 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002506
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002507 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002508
John McCalld935e9c2011-06-15 23:37:01 +00002509 if (!Ret) continue;
2510
2511 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2512 FindDependencies(NeedsPositiveRetainCount, Arg,
2513 BB, Ret, DependingInstructions, Visited, PA);
2514 if (DependingInstructions.size() != 1)
2515 goto next_block;
2516
2517 {
2518 CallInst *Autorelease =
2519 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2520 if (!Autorelease)
2521 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00002522 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002523 if (!IsAutorelease(AutoreleaseClass))
2524 goto next_block;
2525 if (GetObjCArg(Autorelease) != Arg)
2526 goto next_block;
2527
2528 DependingInstructions.clear();
2529 Visited.clear();
2530
2531 // Check that there is nothing that can affect the reference
2532 // count between the autorelease and the retain.
2533 FindDependencies(CanChangeRetainCount, Arg,
2534 BB, Autorelease, DependingInstructions, Visited, PA);
2535 if (DependingInstructions.size() != 1)
2536 goto next_block;
2537
2538 {
2539 CallInst *Retain =
2540 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2541
2542 // Check that we found a retain with the same argument.
2543 if (!Retain ||
2544 !IsRetain(GetBasicInstructionClass(Retain)) ||
2545 GetObjCArg(Retain) != Arg)
2546 goto next_block;
2547
2548 DependingInstructions.clear();
2549 Visited.clear();
2550
2551 // Convert the autorelease to an autoreleaseRV, since it's
2552 // returning the value.
2553 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002554 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
2555 "=> autoreleaseRV since it's returning a value.\n"
2556 " In: " << *Autorelease
2557 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002558 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002559 DEBUG(dbgs() << " Out: " << *Autorelease
2560 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002561 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00002562 AutoreleaseClass = IC_AutoreleaseRV;
2563 }
2564
2565 // Check that there is nothing that can affect the reference
2566 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00002567 // Note that Retain need not be in BB.
2568 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00002569 DependingInstructions, Visited, PA);
2570 if (DependingInstructions.size() != 1)
2571 goto next_block;
2572
2573 {
2574 CallInst *Call =
2575 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2576
2577 // Check that the pointer is the return value of the call.
2578 if (!Call || Arg != Call)
2579 goto next_block;
2580
2581 // Check that the call is a regular call.
2582 InstructionClass Class = GetBasicInstructionClass(Call);
2583 if (Class != IC_CallOrUser && Class != IC_Call)
2584 goto next_block;
2585
2586 // If so, we can zap the retain and autorelease.
2587 Changed = true;
2588 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002589 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
2590 << "\n Erasing: "
2591 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002592 EraseInstruction(Retain);
2593 EraseInstruction(Autorelease);
2594 }
2595 }
2596 }
2597
2598 next_block:
2599 DependingInstructions.clear();
2600 Visited.clear();
2601 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002602
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002603 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002604
John McCalld935e9c2011-06-15 23:37:01 +00002605}
2606
2607bool ObjCARCOpt::doInitialization(Module &M) {
2608 if (!EnableARCOpts)
2609 return false;
2610
Dan Gohman670f9372012-04-13 18:57:48 +00002611 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002612 Run = ModuleHasARC(M);
2613 if (!Run)
2614 return false;
2615
John McCalld935e9c2011-06-15 23:37:01 +00002616 // Identify the imprecise release metadata kind.
2617 ImpreciseReleaseMDKind =
2618 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002619 CopyOnEscapeMDKind =
2620 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002621 NoObjCARCExceptionsMDKind =
2622 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00002623
John McCalld935e9c2011-06-15 23:37:01 +00002624 // Intuitively, objc_retain and others are nocapture, however in practice
2625 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002626 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002627
2628 // These are initialized lazily.
2629 RetainRVCallee = 0;
2630 AutoreleaseRVCallee = 0;
2631 ReleaseCallee = 0;
2632 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002633 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002634 AutoreleaseCallee = 0;
2635
2636 return false;
2637}
2638
2639bool ObjCARCOpt::runOnFunction(Function &F) {
2640 if (!EnableARCOpts)
2641 return false;
2642
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002643 // If nothing in the Module uses ARC, don't do anything.
2644 if (!Run)
2645 return false;
2646
John McCalld935e9c2011-06-15 23:37:01 +00002647 Changed = false;
2648
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002649 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
2650
John McCalld935e9c2011-06-15 23:37:01 +00002651 PA.setAA(&getAnalysis<AliasAnalysis>());
2652
2653 // This pass performs several distinct transformations. As a compile-time aid
2654 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2655 // library functions aren't declared.
2656
2657 // Preliminary optimizations. This also computs UsedInThisFunction.
2658 OptimizeIndividualCalls(F);
2659
2660 // Optimizations for weak pointers.
2661 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2662 (1 << IC_LoadWeakRetained) |
2663 (1 << IC_StoreWeak) |
2664 (1 << IC_InitWeak) |
2665 (1 << IC_CopyWeak) |
2666 (1 << IC_MoveWeak) |
2667 (1 << IC_DestroyWeak)))
2668 OptimizeWeakCalls(F);
2669
2670 // Optimizations for retain+release pairs.
2671 if (UsedInThisFunction & ((1 << IC_Retain) |
2672 (1 << IC_RetainRV) |
2673 (1 << IC_RetainBlock)))
2674 if (UsedInThisFunction & (1 << IC_Release))
2675 // Run OptimizeSequences until it either stops making changes or
2676 // no retain+release pair nesting is detected.
2677 while (OptimizeSequences(F)) {}
2678
2679 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00002680 if (UsedInThisFunction & ((1 << IC_Autorelease) |
2681 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00002682 OptimizeReturns(F);
2683
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002684 DEBUG(dbgs() << "\n");
2685
John McCalld935e9c2011-06-15 23:37:01 +00002686 return Changed;
2687}
2688
2689void ObjCARCOpt::releaseMemory() {
2690 PA.clear();
2691}
2692
Michael Gottesman97e3df02013-01-14 00:35:14 +00002693/// @}
2694///