blob: b37b9efd282fd87c0326885ee254507bbc2b2e2d [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"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000036#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000039#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000040#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000041
John McCalld935e9c2011-06-15 23:37:01 +000042using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000043using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000044
Michael Gottesman97e3df02013-01-14 00:35:14 +000045/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46/// @{
John McCalld935e9c2011-06-15 23:37:01 +000047
48namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000049 /// \brief An associative container with fast insertion-order (deterministic)
50 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000051 template<class KeyT, class ValueT>
52 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000053 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef DenseMap<KeyT, size_t> MapTy;
55 MapTy Map;
56
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000058 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000059 VectorTy Vector;
60
61 public:
62 typedef typename VectorTy::iterator iterator;
63 typedef typename VectorTy::const_iterator const_iterator;
64 iterator begin() { return Vector.begin(); }
65 iterator end() { return Vector.end(); }
66 const_iterator begin() const { return Vector.begin(); }
67 const_iterator end() const { return Vector.end(); }
68
69#ifdef XDEBUG
70 ~MapVector() {
71 assert(Vector.size() >= Map.size()); // May differ due to blotting.
72 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
73 I != E; ++I) {
74 assert(I->second < Vector.size());
75 assert(Vector[I->second].first == I->first);
76 }
77 for (typename VectorTy::const_iterator I = Vector.begin(),
78 E = Vector.end(); I != E; ++I)
79 assert(!I->first ||
80 (Map.count(I->first) &&
81 Map[I->first] == size_t(I - Vector.begin())));
82 }
83#endif
84
Dan Gohman55b06742012-03-02 01:13:53 +000085 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000086 std::pair<typename MapTy::iterator, bool> Pair =
87 Map.insert(std::make_pair(Arg, size_t(0)));
88 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000089 size_t Num = Vector.size();
90 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000091 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000092 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000093 }
94 return Vector[Pair.first->second].second;
95 }
96
97 std::pair<iterator, bool>
98 insert(const std::pair<KeyT, ValueT> &InsertPair) {
99 std::pair<typename MapTy::iterator, bool> Pair =
100 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
101 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000102 size_t Num = Vector.size();
103 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000104 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000105 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000106 }
107 return std::make_pair(Vector.begin() + Pair.first->second, false);
108 }
109
Dan Gohman55b06742012-03-02 01:13:53 +0000110 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000111 typename MapTy::const_iterator It = Map.find(Key);
112 if (It == Map.end()) return Vector.end();
113 return Vector.begin() + It->second;
114 }
115
Michael Gottesman97e3df02013-01-14 00:35:14 +0000116 /// This is similar to erase, but instead of removing the element from the
117 /// vector, it just zeros out the key in the vector. This leaves iterators
118 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000119 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
123 Map.erase(It);
124 }
125
126 void clear() {
127 Map.clear();
128 Vector.clear();
129 }
130 };
131}
132
Michael Gottesman97e3df02013-01-14 00:35:14 +0000133/// @}
134///
135/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
136/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000137
Michael Gottesman97e3df02013-01-14 00:35:14 +0000138/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
139/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000140static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
141 if (Arg->hasOneUse()) {
142 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
143 return FindSingleUseIdentifiedObject(BC->getOperand(0));
144 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
145 if (GEP->hasAllZeroIndices())
146 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
147 if (IsForwarding(GetBasicInstructionClass(Arg)))
148 return FindSingleUseIdentifiedObject(
149 cast<CallInst>(Arg)->getArgOperand(0));
150 if (!IsObjCIdentifiedObject(Arg))
151 return 0;
152 return Arg;
153 }
154
Dan Gohman41375a32012-05-08 23:39:44 +0000155 // If we found an identifiable object but it has multiple uses, but they are
156 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000157 if (IsObjCIdentifiedObject(Arg)) {
158 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
159 UI != UE; ++UI) {
160 const User *U = *UI;
161 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
162 return 0;
163 }
164
165 return Arg;
166 }
167
168 return 0;
169}
170
Michael Gottesman774d2c02013-01-29 21:00:52 +0000171/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000172///
173/// This differs from regular escape analysis in that a use as an
174/// argument to a call is not considered an escape.
175///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000176static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000177 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000178
Dan Gohman728db492012-01-13 00:39:07 +0000179 // Walk the def-use chains.
180 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000181 Worklist.push_back(Ptr);
182 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000183 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
184 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 Worklist.push_back(*I);
186 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000187
188 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000189 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000190
Dan Gohman728db492012-01-13 00:39:07 +0000191 do {
192 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000193
Michael Gottesman89279f82013-04-05 18:10:41 +0000194 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000195
Dan Gohman728db492012-01-13 00:39:07 +0000196 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
197 UI != UE; ++UI) {
198 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000199
Michael Gottesman89279f82013-04-05 18:10:41 +0000200 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Dan Gohman728db492012-01-13 00:39:07 +0000202 // Special - Use by a call (callee or argument) is not considered
203 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000204 switch (GetBasicInstructionClass(UUser)) {
205 case IC_StoreWeak:
206 case IC_InitWeak:
207 case IC_StoreStrong:
208 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000209 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000210 DEBUG(dbgs() << "User copies pointer 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 Gottesman89279f82013-04-05 18:10:41 +0000225 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
226 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000227 Worklist.push_back(UUser);
228 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000229 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000231 continue;
232 }
233 // Use by a load is not an escape.
234 if (isa<LoadInst>(UUser))
235 continue;
236 // Use by a store is not an escape if the use is the address.
237 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
238 if (V != SI->getValueOperand())
239 continue;
240 break;
241 default:
242 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000243 continue;
244 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000245 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000246 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000247 return true;
248 }
249 } while (!Worklist.empty());
250
251 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000252 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000253 return false;
254}
255
Michael Gottesman97e3df02013-01-14 00:35:14 +0000256/// @}
257///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000258/// \defgroup ARCOpt ARC Optimization.
259/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000260
261// TODO: On code like this:
262//
263// objc_retain(%x)
264// stuff_that_cannot_release()
265// objc_autorelease(%x)
266// stuff_that_cannot_release()
267// objc_retain(%x)
268// stuff_that_cannot_release()
269// objc_autorelease(%x)
270//
271// The second retain and autorelease can be deleted.
272
273// TODO: It should be possible to delete
274// objc_autoreleasePoolPush and objc_autoreleasePoolPop
275// pairs if nothing is actually autoreleased between them. Also, autorelease
276// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
277// after inlining) can be turned into plain release calls.
278
279// TODO: Critical-edge splitting. If the optimial insertion point is
280// a critical edge, the current algorithm has to fail, because it doesn't
281// know how to split edges. It should be possible to make the optimizer
282// think in terms of edges, rather than blocks, and then split critical
283// edges on demand.
284
285// TODO: OptimizeSequences could generalized to be Interprocedural.
286
287// TODO: Recognize that a bunch of other objc runtime calls have
288// non-escaping arguments and non-releasing arguments, and may be
289// non-autoreleasing.
290
291// TODO: Sink autorelease calls as far as possible. Unfortunately we
292// usually can't sink them past other calls, which would be the main
293// case where it would be useful.
294
Dan Gohmanb3894012011-08-19 00:26:36 +0000295// TODO: The pointer returned from objc_loadWeakRetained is retained.
296
297// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000298
John McCalld935e9c2011-06-15 23:37:01 +0000299STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
300STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
301STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
302STATISTIC(NumRets, "Number of return value forwarding "
303 "retain+autoreleaes eliminated");
304STATISTIC(NumRRs, "Number of retain+release paths eliminated");
305STATISTIC(NumPeeps, "Number of calls peephole-optimized");
306
307namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000308 /// \enum Sequence
309 ///
310 /// \brief A sequence of states that a pointer may go through in which an
311 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000312 enum Sequence {
313 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000314 S_Retain, ///< objc_retain(x).
315 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
316 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000317 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000318 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000319 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000320 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000321
322 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
323 LLVM_ATTRIBUTE_UNUSED;
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
325 switch (S) {
326 case S_None:
327 return OS << "S_None";
328 case S_Retain:
329 return OS << "S_Retain";
330 case S_CanRelease:
331 return OS << "S_CanRelease";
332 case S_Use:
333 return OS << "S_Use";
334 case S_Release:
335 return OS << "S_Release";
336 case S_MovableRelease:
337 return OS << "S_MovableRelease";
338 case S_Stop:
339 return OS << "S_Stop";
340 }
341 llvm_unreachable("Unknown sequence type.");
342 }
John McCalld935e9c2011-06-15 23:37:01 +0000343}
344
345static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
346 // The easy cases.
347 if (A == B)
348 return A;
349 if (A == S_None || B == S_None)
350 return S_None;
351
John McCalld935e9c2011-06-15 23:37:01 +0000352 if (A > B) std::swap(A, B);
353 if (TopDown) {
354 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000355 if ((A == S_Retain || A == S_CanRelease) &&
356 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000357 return B;
358 } else {
359 // Choose the side which is further along in the sequence.
360 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000361 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000362 return A;
363 // If both sides are releases, choose the more conservative one.
364 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
365 return A;
366 if (A == S_Release && B == S_MovableRelease)
367 return A;
368 }
369
370 return S_None;
371}
372
373namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000374 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000375 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000376 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000377 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000378 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000379 /// object is known to be positive. Similarly, before an objc_release, the
380 /// reference count of the referenced object is known to be positive. If
381 /// there are retain-release pairs in code regions where the retain count
382 /// is known to be positive, they can be eliminated, regardless of any side
383 /// effects between them.
384 ///
385 /// Also, a retain+release pair nested within another retain+release
386 /// pair all on the known same pointer value can be eliminated, regardless
387 /// of any intervening side effects.
388 ///
389 /// KnownSafe is true when either of these conditions is satisfied.
390 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000391
Michael Gottesman97e3df02013-01-14 00:35:14 +0000392 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000393 bool IsTailCallRelease;
394
Michael Gottesman97e3df02013-01-14 00:35:14 +0000395 /// If the Calls are objc_release calls and they all have a
396 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000397 MDNode *ReleaseMetadata;
398
Michael Gottesman97e3df02013-01-14 00:35:14 +0000399 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000400 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
401 SmallPtrSet<Instruction *, 2> Calls;
402
Michael Gottesman97e3df02013-01-14 00:35:14 +0000403 /// The set of optimal insert positions for moving calls in the opposite
404 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000405 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
406
407 RRInfo() :
Michael Gottesmanba648592013-03-28 23:08:44 +0000408 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000409
410 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000411
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000412 bool IsTrackingImpreciseReleases() {
413 return ReleaseMetadata != 0;
414 }
John McCalld935e9c2011-06-15 23:37:01 +0000415 };
416}
417
418void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000419 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000420 IsTailCallRelease = false;
421 ReleaseMetadata = 0;
422 Calls.clear();
423 ReverseInsertPts.clear();
424}
425
426namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000427 /// \brief This class summarizes several per-pointer runtime properties which
428 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000429 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000430 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000431 bool KnownPositiveRefCount;
432
Bob Wilson798a7702013-04-09 22:15:51 +0000433 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000434 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000435 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000436
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000438 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000439
440 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000441 /// Unidirectional information about the current sequence.
442 ///
John McCalld935e9c2011-06-15 23:37:01 +0000443 /// TODO: Encapsulate this better.
444 RRInfo RRI;
445
Dan Gohmandf476e52012-09-04 23:16:20 +0000446 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000447 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000448
Michael Gottesman415ddd72013-02-05 19:32:18 +0000449 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000450 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000451 }
452
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000453 void ClearKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000454 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000455 }
456
Michael Gottesman07beea42013-03-23 05:31:01 +0000457 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000458 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000459 }
460
Michael Gottesman415ddd72013-02-05 19:32:18 +0000461 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000462 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000463 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000464 }
465
Michael Gottesman415ddd72013-02-05 19:32:18 +0000466 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000467 return Seq;
468 }
469
Michael Gottesman415ddd72013-02-05 19:32:18 +0000470 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000471 ResetSequenceProgress(S_None);
472 }
473
Michael Gottesman415ddd72013-02-05 19:32:18 +0000474 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000475 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000476 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000477 RRI.clear();
478 }
479
480 void Merge(const PtrState &Other, bool TopDown);
481 };
482}
483
484void
485PtrState::Merge(const PtrState &Other, bool TopDown) {
486 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000487 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000488
Dan Gohman1736c142011-10-17 18:48:25 +0000489 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000490 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000491 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000492 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000493 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000494 // If we're doing a merge on a path that's previously seen a partial
495 // merge, conservatively drop the sequence, to avoid doing partial
496 // RR elimination. If the branch predicates for the two merge differ,
497 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000498 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000499 } else {
500 // Conservatively merge the ReleaseMetadata information.
501 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
502 RRI.ReleaseMetadata = 0;
503
Dan Gohmanb3894012011-08-19 00:26:36 +0000504 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000505 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
506 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000507 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000508
509 // Merge the insert point sets. If there are any differences,
510 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000511 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000512 for (SmallPtrSet<Instruction *, 2>::const_iterator
513 I = Other.RRI.ReverseInsertPts.begin(),
514 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000515 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000516 }
517}
518
519namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000520 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000521 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// The number of unique control paths from the entry which can reach this
523 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000524 unsigned TopDownPathCount;
525
Michael Gottesman97e3df02013-01-14 00:35:14 +0000526 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000527 unsigned BottomUpPathCount;
528
Michael Gottesman97e3df02013-01-14 00:35:14 +0000529 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000530 typedef MapVector<const Value *, PtrState> MapTy;
531
Michael Gottesman97e3df02013-01-14 00:35:14 +0000532 /// The top-down traversal uses this to record information known about a
533 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000534 MapTy PerPtrTopDown;
535
Michael Gottesman97e3df02013-01-14 00:35:14 +0000536 /// The bottom-up traversal uses this to record information known about a
537 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000538 MapTy PerPtrBottomUp;
539
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540 /// Effective predecessors of the current block ignoring ignorable edges and
541 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000542 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000543 /// Effective successors of the current block ignoring ignorable edges and
544 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000545 SmallVector<BasicBlock *, 2> Succs;
546
John McCalld935e9c2011-06-15 23:37:01 +0000547 public:
548 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
549
550 typedef MapTy::iterator ptr_iterator;
551 typedef MapTy::const_iterator ptr_const_iterator;
552
553 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
554 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
555 ptr_const_iterator top_down_ptr_begin() const {
556 return PerPtrTopDown.begin();
557 }
558 ptr_const_iterator top_down_ptr_end() const {
559 return PerPtrTopDown.end();
560 }
561
562 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
563 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
564 ptr_const_iterator bottom_up_ptr_begin() const {
565 return PerPtrBottomUp.begin();
566 }
567 ptr_const_iterator bottom_up_ptr_end() const {
568 return PerPtrBottomUp.end();
569 }
570
Michael Gottesman97e3df02013-01-14 00:35:14 +0000571 /// Mark this block as being an entry block, which has one path from the
572 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000573 void SetAsEntry() { TopDownPathCount = 1; }
574
Michael Gottesman97e3df02013-01-14 00:35:14 +0000575 /// Mark this block as being an exit block, which has one path to an exit by
576 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000577 void SetAsExit() { BottomUpPathCount = 1; }
578
579 PtrState &getPtrTopDownState(const Value *Arg) {
580 return PerPtrTopDown[Arg];
581 }
582
583 PtrState &getPtrBottomUpState(const Value *Arg) {
584 return PerPtrBottomUp[Arg];
585 }
586
587 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000588 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000589 }
590
591 void clearTopDownPointers() {
592 PerPtrTopDown.clear();
593 }
594
595 void InitFromPred(const BBState &Other);
596 void InitFromSucc(const BBState &Other);
597 void MergePred(const BBState &Other);
598 void MergeSucc(const BBState &Other);
599
Michael Gottesman97e3df02013-01-14 00:35:14 +0000600 /// Return the number of possible unique paths from an entry to an exit
601 /// which pass through this block. This is only valid after both the
602 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000603 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000604 assert(TopDownPathCount != 0);
605 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000606 return TopDownPathCount * BottomUpPathCount;
607 }
Dan Gohman12130272011-08-12 00:26:31 +0000608
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000609 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000610 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000611 edge_iterator pred_begin() { return Preds.begin(); }
612 edge_iterator pred_end() { return Preds.end(); }
613 edge_iterator succ_begin() { return Succs.begin(); }
614 edge_iterator succ_end() { return Succs.end(); }
615
616 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
617 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
618
619 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000620 };
621}
622
623void BBState::InitFromPred(const BBState &Other) {
624 PerPtrTopDown = Other.PerPtrTopDown;
625 TopDownPathCount = Other.TopDownPathCount;
626}
627
628void BBState::InitFromSucc(const BBState &Other) {
629 PerPtrBottomUp = Other.PerPtrBottomUp;
630 BottomUpPathCount = Other.BottomUpPathCount;
631}
632
Michael Gottesman97e3df02013-01-14 00:35:14 +0000633/// The top-down traversal uses this to merge information about predecessors to
634/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000635void BBState::MergePred(const BBState &Other) {
636 // Other.TopDownPathCount can be 0, in which case it is either dead or a
637 // loop backedge. Loop backedges are special.
638 TopDownPathCount += Other.TopDownPathCount;
639
Michael Gottesman4385edf2013-01-14 01:47:53 +0000640 // Check for overflow. If we have overflow, fall back to conservative
641 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000642 if (TopDownPathCount < Other.TopDownPathCount) {
643 clearTopDownPointers();
644 return;
645 }
646
John McCalld935e9c2011-06-15 23:37:01 +0000647 // For each entry in the other set, if our set has an entry with the same key,
648 // merge the entries. Otherwise, copy the entry and merge it with an empty
649 // entry.
650 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
651 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
652 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
653 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
654 /*TopDown=*/true);
655 }
656
Dan Gohman7e315fc32011-08-11 21:06:32 +0000657 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000658 // same key, force it to merge with an empty entry.
659 for (ptr_iterator MI = top_down_ptr_begin(),
660 ME = top_down_ptr_end(); MI != ME; ++MI)
661 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
662 MI->second.Merge(PtrState(), /*TopDown=*/true);
663}
664
Michael Gottesman97e3df02013-01-14 00:35:14 +0000665/// The bottom-up traversal uses this to merge information about successors to
666/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000667void BBState::MergeSucc(const BBState &Other) {
668 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
669 // loop backedge. Loop backedges are special.
670 BottomUpPathCount += Other.BottomUpPathCount;
671
Michael Gottesman4385edf2013-01-14 01:47:53 +0000672 // Check for overflow. If we have overflow, fall back to conservative
673 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000674 if (BottomUpPathCount < Other.BottomUpPathCount) {
675 clearBottomUpPointers();
676 return;
677 }
678
John McCalld935e9c2011-06-15 23:37:01 +0000679 // For each entry in the other set, if our set has an entry with the
680 // same key, merge the entries. Otherwise, copy the entry and merge
681 // it with an empty entry.
682 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
683 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
684 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
685 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
686 /*TopDown=*/false);
687 }
688
Dan Gohman7e315fc32011-08-11 21:06:32 +0000689 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000690 // with the same key, force it to merge with an empty entry.
691 for (ptr_iterator MI = bottom_up_ptr_begin(),
692 ME = bottom_up_ptr_end(); MI != ME; ++MI)
693 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
694 MI->second.Merge(PtrState(), /*TopDown=*/false);
695}
696
Michael Gottesman81b1d432013-03-26 00:42:04 +0000697// Only enable ARC Annotations if we are building a debug version of
698// libObjCARCOpts.
699#ifndef NDEBUG
700#define ARC_ANNOTATIONS
701#endif
702
703// Define some macros along the lines of DEBUG and some helper functions to make
704// it cleaner to create annotations in the source code and to no-op when not
705// building in debug mode.
706#ifdef ARC_ANNOTATIONS
707
708#include "llvm/Support/CommandLine.h"
709
710/// Enable/disable ARC sequence annotations.
711static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000712EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
713 cl::desc("Enable emission of arc data flow analysis "
714 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000715static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000716DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
717 cl::desc("Disable check for cfg hazards when "
718 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000719static cl::opt<std::string>
720ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
721 cl::init(""),
722 cl::desc("filter out all data flow annotations "
723 "but those that apply to the given "
724 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000725
726/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
727/// instruction so that we can track backwards when post processing via the llvm
728/// arc annotation processor tool. If the function is an
729static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
730 Value *Ptr) {
731 MDString *Hash = 0;
732
733 // If pointer is a result of an instruction and it does not have a source
734 // MDNode it, attach a new MDNode onto it. If pointer is a result of
735 // an instruction and does have a source MDNode attached to it, return a
736 // reference to said Node. Otherwise just return 0.
737 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
738 MDNode *Node;
739 if (!(Node = Inst->getMetadata(NodeId))) {
740 // We do not have any node. Generate and attatch the hash MDString to the
741 // instruction.
742
743 // We just use an MDString to ensure that this metadata gets written out
744 // of line at the module level and to provide a very simple format
745 // encoding the information herein. Both of these makes it simpler to
746 // parse the annotations by a simple external program.
747 std::string Str;
748 raw_string_ostream os(Str);
749 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
750 << Inst->getName() << ")";
751
752 Hash = MDString::get(Inst->getContext(), os.str());
753 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
754 } else {
755 // We have a node. Grab its hash and return it.
756 assert(Node->getNumOperands() == 1 &&
757 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
758 Hash = cast<MDString>(Node->getOperand(0));
759 }
760 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
761 std::string str;
762 raw_string_ostream os(str);
763 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
764 << ")";
765 Hash = MDString::get(Arg->getContext(), os.str());
766 }
767
768 return Hash;
769}
770
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000771static std::string SequenceToString(Sequence A) {
772 std::string str;
773 raw_string_ostream os(str);
774 os << A;
775 return os.str();
776}
777
Michael Gottesman81b1d432013-03-26 00:42:04 +0000778/// Helper function to change a Sequence into a String object using our overload
779/// for raw_ostream so we only have printing code in one location.
780static MDString *SequenceToMDString(LLVMContext &Context,
781 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000782 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000783}
784
785/// A simple function to generate a MDNode which describes the change in state
786/// for Value *Ptr caused by Instruction *Inst.
787static void AppendMDNodeToInstForPtr(unsigned NodeId,
788 Instruction *Inst,
789 Value *Ptr,
790 MDString *PtrSourceMDNodeID,
791 Sequence OldSeq,
792 Sequence NewSeq) {
793 MDNode *Node = 0;
794 Value *tmp[3] = {PtrSourceMDNodeID,
795 SequenceToMDString(Inst->getContext(),
796 OldSeq),
797 SequenceToMDString(Inst->getContext(),
798 NewSeq)};
799 Node = MDNode::get(Inst->getContext(),
800 ArrayRef<Value*>(tmp, 3));
801
802 Inst->setMetadata(NodeId, Node);
803}
804
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000805/// Add to the beginning of the basic block llvm.ptr.annotations which show the
806/// state of a pointer at the entrance to a basic block.
807static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
808 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000809 // If we have a target identifier, make sure that we match it before
810 // continuing.
811 if(!ARCAnnotationTargetIdentifier.empty() &&
812 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
813 return;
814
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000815 Module *M = BB->getParent()->getParent();
816 LLVMContext &C = M->getContext();
817 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
818 Type *I8XX = PointerType::getUnqual(I8X);
819 Type *Params[] = {I8XX, I8XX};
820 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
821 ArrayRef<Type*>(Params, 2),
822 /*isVarArg=*/false);
823 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000824
825 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
826
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000827 Value *PtrName;
828 StringRef Tmp = Ptr->getName();
829 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
830 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
831 Tmp + "_STR");
832 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000833 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000834 }
835
836 Value *S;
837 std::string SeqStr = SequenceToString(Seq);
838 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
839 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
840 SeqStr + "_STR");
841 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
842 cast<Constant>(ActualPtrName), SeqStr);
843 }
844
845 Builder.CreateCall2(Callee, PtrName, S);
846}
847
848/// Add to the end of the basic block llvm.ptr.annotations which show the state
849/// of the pointer at the bottom of the basic block.
850static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
851 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000852 // If we have a target identifier, make sure that we match it before emitting
853 // an annotation.
854 if(!ARCAnnotationTargetIdentifier.empty() &&
855 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
856 return;
857
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000858 Module *M = BB->getParent()->getParent();
859 LLVMContext &C = M->getContext();
860 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
861 Type *I8XX = PointerType::getUnqual(I8X);
862 Type *Params[] = {I8XX, I8XX};
863 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
864 ArrayRef<Type*>(Params, 2),
865 /*isVarArg=*/false);
866 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000867
868 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
869
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000870 Value *PtrName;
871 StringRef Tmp = Ptr->getName();
872 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
873 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
874 Tmp + "_STR");
875 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000876 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000877 }
878
879 Value *S;
880 std::string SeqStr = SequenceToString(Seq);
881 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
882 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
883 SeqStr + "_STR");
884 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
885 cast<Constant>(ActualPtrName), SeqStr);
886 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000887 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000888}
889
Michael Gottesman81b1d432013-03-26 00:42:04 +0000890/// Adds a source annotation to pointer and a state change annotation to Inst
891/// referencing the source annotation and the old/new state of pointer.
892static void GenerateARCAnnotation(unsigned InstMDId,
893 unsigned PtrMDId,
894 Instruction *Inst,
895 Value *Ptr,
896 Sequence OldSeq,
897 Sequence NewSeq) {
898 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000899 // If we have a target identifier, make sure that we match it before
900 // emitting an annotation.
901 if(!ARCAnnotationTargetIdentifier.empty() &&
902 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
903 return;
904
Michael Gottesman81b1d432013-03-26 00:42:04 +0000905 // First generate the source annotation on our pointer. This will return an
906 // MDString* if Ptr actually comes from an instruction implying we can put
907 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
908 // then we know that our pointer is from an Argument so we put a reference
909 // to the argument number.
910 //
911 // The point of this is to make it easy for the
912 // llvm-arc-annotation-processor tool to cross reference where the source
913 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
914 // information via debug info for backends to use (since why would anyone
915 // need such a thing from LLVM IR besides in non standard cases
916 // [i.e. this]).
917 MDString *SourcePtrMDNode =
918 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
919 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
920 NewSeq);
921 }
922}
923
924// The actual interface for accessing the above functionality is defined via
925// some simple macros which are defined below. We do this so that the user does
926// not need to pass in what metadata id is needed resulting in cleaner code and
927// additionally since it provides an easy way to conditionally no-op all
928// annotation support in a non-debug build.
929
930/// Use this macro to annotate a sequence state change when processing
931/// instructions bottom up,
932#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
933 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
934 ARCAnnotationProvenanceSourceMDKind, (inst), \
935 const_cast<Value*>(ptr), (old), (new))
936/// Use this macro to annotate a sequence state change when processing
937/// instructions top down.
938#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
939 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
940 ARCAnnotationProvenanceSourceMDKind, (inst), \
941 const_cast<Value*>(ptr), (old), (new))
942
Michael Gottesman43e7e002013-04-03 22:41:59 +0000943#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
944 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000945 if (EnableARCAnnotations) { \
946 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000947 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000948 Value *Ptr = const_cast<Value*>(I->first); \
949 Sequence Seq = I->second.GetSeq(); \
950 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
951 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000952 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000953 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000954
Michael Gottesman89279f82013-04-05 18:10:41 +0000955#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000956 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
957 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000958#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
959 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000960 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000961#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
962 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000963 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000964#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
965 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000966 Terminator, top_down)
967
Michael Gottesman81b1d432013-03-26 00:42:04 +0000968#else // !ARC_ANNOTATION
969// If annotations are off, noop.
970#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
971#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000972#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
973#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
974#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
975#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000976#endif // !ARC_ANNOTATION
977
John McCalld935e9c2011-06-15 23:37:01 +0000978namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000979 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000980 class ObjCARCOpt : public FunctionPass {
981 bool Changed;
982 ProvenanceAnalysis PA;
983
Michael Gottesman97e3df02013-01-14 00:35:14 +0000984 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000985 bool Run;
986
Michael Gottesman97e3df02013-01-14 00:35:14 +0000987 /// Declarations for ObjC runtime functions, for use in creating calls to
988 /// them. These are initialized lazily to avoid cluttering up the Module
989 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000990
Michael Gottesman97e3df02013-01-14 00:35:14 +0000991 /// Declaration for ObjC runtime function
992 /// objc_retainAutoreleasedReturnValue.
993 Constant *RetainRVCallee;
994 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
995 Constant *AutoreleaseRVCallee;
996 /// Declaration for ObjC runtime function objc_release.
997 Constant *ReleaseCallee;
998 /// Declaration for ObjC runtime function objc_retain.
999 Constant *RetainCallee;
1000 /// Declaration for ObjC runtime function objc_retainBlock.
1001 Constant *RetainBlockCallee;
1002 /// Declaration for ObjC runtime function objc_autorelease.
1003 Constant *AutoreleaseCallee;
1004
1005 /// Flags which determine whether each of the interesting runtine functions
1006 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001007 unsigned UsedInThisFunction;
1008
Michael Gottesman97e3df02013-01-14 00:35:14 +00001009 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001010 unsigned ImpreciseReleaseMDKind;
1011
Michael Gottesman97e3df02013-01-14 00:35:14 +00001012 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001013 unsigned CopyOnEscapeMDKind;
1014
Michael Gottesman97e3df02013-01-14 00:35:14 +00001015 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001016 unsigned NoObjCARCExceptionsMDKind;
1017
Michael Gottesman81b1d432013-03-26 00:42:04 +00001018#ifdef ARC_ANNOTATIONS
1019 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1020 unsigned ARCAnnotationBottomUpMDKind;
1021 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1022 unsigned ARCAnnotationTopDownMDKind;
1023 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1024 unsigned ARCAnnotationProvenanceSourceMDKind;
1025#endif // ARC_ANNOATIONS
1026
John McCalld935e9c2011-06-15 23:37:01 +00001027 Constant *getRetainRVCallee(Module *M);
1028 Constant *getAutoreleaseRVCallee(Module *M);
1029 Constant *getReleaseCallee(Module *M);
1030 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001031 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001032 Constant *getAutoreleaseCallee(Module *M);
1033
Dan Gohman728db492012-01-13 00:39:07 +00001034 bool IsRetainBlockOptimizable(const Instruction *Inst);
1035
John McCalld935e9c2011-06-15 23:37:01 +00001036 void OptimizeRetainCall(Function &F, Instruction *Retain);
1037 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001038 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1039 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001040 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1041 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001042 void OptimizeIndividualCalls(Function &F);
1043
1044 void CheckForCFGHazards(const BasicBlock *BB,
1045 DenseMap<const BasicBlock *, BBState> &BBStates,
1046 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001047 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001048 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001049 MapVector<Value *, RRInfo> &Retains,
1050 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001051 bool VisitBottomUp(BasicBlock *BB,
1052 DenseMap<const BasicBlock *, BBState> &BBStates,
1053 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001054 bool VisitInstructionTopDown(Instruction *Inst,
1055 DenseMap<Value *, RRInfo> &Releases,
1056 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001057 bool VisitTopDown(BasicBlock *BB,
1058 DenseMap<const BasicBlock *, BBState> &BBStates,
1059 DenseMap<Value *, RRInfo> &Releases);
1060 bool Visit(Function &F,
1061 DenseMap<const BasicBlock *, BBState> &BBStates,
1062 MapVector<Value *, RRInfo> &Retains,
1063 DenseMap<Value *, RRInfo> &Releases);
1064
1065 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1066 MapVector<Value *, RRInfo> &Retains,
1067 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001068 SmallVectorImpl<Instruction *> &DeadInsts,
1069 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001070
Michael Gottesman9de6f962013-01-22 21:49:00 +00001071 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1072 MapVector<Value *, RRInfo> &Retains,
1073 DenseMap<Value *, RRInfo> &Releases,
1074 Module *M,
1075 SmallVector<Instruction *, 4> &NewRetains,
1076 SmallVector<Instruction *, 4> &NewReleases,
1077 SmallVector<Instruction *, 8> &DeadInsts,
1078 RRInfo &RetainsToMove,
1079 RRInfo &ReleasesToMove,
1080 Value *Arg,
1081 bool KnownSafe,
1082 bool &AnyPairsCompletelyEliminated);
1083
John McCalld935e9c2011-06-15 23:37:01 +00001084 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1085 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001086 DenseMap<Value *, RRInfo> &Releases,
1087 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001088
1089 void OptimizeWeakCalls(Function &F);
1090
1091 bool OptimizeSequences(Function &F);
1092
1093 void OptimizeReturns(Function &F);
1094
1095 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1096 virtual bool doInitialization(Module &M);
1097 virtual bool runOnFunction(Function &F);
1098 virtual void releaseMemory();
1099
1100 public:
1101 static char ID;
1102 ObjCARCOpt() : FunctionPass(ID) {
1103 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1104 }
1105 };
1106}
1107
1108char ObjCARCOpt::ID = 0;
1109INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1110 "objc-arc", "ObjC ARC optimization", false, false)
1111INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1112INITIALIZE_PASS_END(ObjCARCOpt,
1113 "objc-arc", "ObjC ARC optimization", false, false)
1114
1115Pass *llvm::createObjCARCOptPass() {
1116 return new ObjCARCOpt();
1117}
1118
1119void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1120 AU.addRequired<ObjCARCAliasAnalysis>();
1121 AU.addRequired<AliasAnalysis>();
1122 // ARC optimization doesn't currently split critical edges.
1123 AU.setPreservesCFG();
1124}
1125
Dan Gohman728db492012-01-13 00:39:07 +00001126bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1127 // Without the magic metadata tag, we have to assume this might be an
1128 // objc_retainBlock call inserted to convert a block pointer to an id,
1129 // in which case it really is needed.
1130 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1131 return false;
1132
1133 // If the pointer "escapes" (not including being used in a call),
1134 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001135 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001136 return false;
1137
1138 // Otherwise, it's not needed.
1139 return true;
1140}
1141
John McCalld935e9c2011-06-15 23:37:01 +00001142Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1143 if (!RetainRVCallee) {
1144 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001145 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001146 Type *Params[] = { I8X };
1147 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001148 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001149 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1150 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001151 RetainRVCallee =
1152 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001153 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001154 }
1155 return RetainRVCallee;
1156}
1157
1158Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1159 if (!AutoreleaseRVCallee) {
1160 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001161 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001162 Type *Params[] = { I8X };
1163 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001164 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001165 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1166 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001167 AutoreleaseRVCallee =
1168 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001169 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001170 }
1171 return AutoreleaseRVCallee;
1172}
1173
1174Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1175 if (!ReleaseCallee) {
1176 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001177 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001178 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001179 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1180 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001181 ReleaseCallee =
1182 M->getOrInsertFunction(
1183 "objc_release",
1184 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001185 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001186 }
1187 return ReleaseCallee;
1188}
1189
1190Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1191 if (!RetainCallee) {
1192 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001193 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001194 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001195 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1196 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001197 RetainCallee =
1198 M->getOrInsertFunction(
1199 "objc_retain",
1200 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001201 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001202 }
1203 return RetainCallee;
1204}
1205
Dan Gohman6320f522011-07-22 22:29:21 +00001206Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1207 if (!RetainBlockCallee) {
1208 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001209 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001210 // objc_retainBlock is not nounwind because it calls user copy constructors
1211 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001212 RetainBlockCallee =
1213 M->getOrInsertFunction(
1214 "objc_retainBlock",
1215 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001216 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001217 }
1218 return RetainBlockCallee;
1219}
1220
John McCalld935e9c2011-06-15 23:37:01 +00001221Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1222 if (!AutoreleaseCallee) {
1223 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001224 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001225 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001226 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1227 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001228 AutoreleaseCallee =
1229 M->getOrInsertFunction(
1230 "objc_autorelease",
1231 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001232 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001233 }
1234 return AutoreleaseCallee;
1235}
1236
Michael Gottesman97e3df02013-01-14 00:35:14 +00001237/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1238/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001239void
1240ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001241 ImmutableCallSite CS(GetObjCArg(Retain));
1242 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001243 if (!Call) return;
1244 if (Call->getParent() != Retain->getParent()) return;
1245
1246 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001247 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001248 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001249 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001250 if (&*I != Retain)
1251 return;
1252
1253 // Turn it to an objc_retainAutoreleasedReturnValue..
1254 Changed = true;
1255 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001256
Michael Gottesman89279f82013-04-05 18:10:41 +00001257 DEBUG(dbgs() << "Transforming objc_retain => "
1258 "objc_retainAutoreleasedReturnValue since the operand is a "
1259 "return value.\nOld: "<< *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001260
John McCalld935e9c2011-06-15 23:37:01 +00001261 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001262
Michael Gottesman89279f82013-04-05 18:10:41 +00001263 DEBUG(dbgs() << "New: " << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001264}
1265
Michael Gottesman97e3df02013-01-14 00:35:14 +00001266/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1267/// not a return value. Or, if it can be paired with an
1268/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001269bool
1270ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001271 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001272 const Value *Arg = GetObjCArg(RetainRV);
1273 ImmutableCallSite CS(Arg);
1274 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001275 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001276 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001277 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001278 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001279 if (&*I == RetainRV)
1280 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001281 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001282 BasicBlock *RetainRVParent = RetainRV->getParent();
1283 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001284 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001285 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001286 if (&*I == RetainRV)
1287 return false;
1288 }
John McCalld935e9c2011-06-15 23:37:01 +00001289 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001290 }
John McCalld935e9c2011-06-15 23:37:01 +00001291
1292 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1293 // pointer. In this case, we can delete the pair.
1294 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1295 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001296 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001297 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1298 GetObjCArg(I) == Arg) {
1299 Changed = true;
1300 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001301
Michael Gottesman89279f82013-04-05 18:10:41 +00001302 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1303 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001304
John McCalld935e9c2011-06-15 23:37:01 +00001305 EraseInstruction(I);
1306 EraseInstruction(RetainRV);
1307 return true;
1308 }
1309 }
1310
1311 // Turn it to a plain objc_retain.
1312 Changed = true;
1313 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001314
Michael Gottesman89279f82013-04-05 18:10:41 +00001315 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001316 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001317 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001318
John McCalld935e9c2011-06-15 23:37:01 +00001319 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001320
Michael Gottesman89279f82013-04-05 18:10:41 +00001321 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001322
John McCalld935e9c2011-06-15 23:37:01 +00001323 return false;
1324}
1325
Michael Gottesman97e3df02013-01-14 00:35:14 +00001326/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1327/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001328void
Michael Gottesman556ff612013-01-12 01:25:19 +00001329ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1330 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001331 // Check for a return of the pointer value.
1332 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001333 SmallVector<const Value *, 2> Users;
1334 Users.push_back(Ptr);
1335 do {
1336 Ptr = Users.pop_back_val();
1337 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1338 UI != UE; ++UI) {
1339 const User *I = *UI;
1340 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1341 return;
1342 if (isa<BitCastInst>(I))
1343 Users.push_back(I);
1344 }
1345 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001346
1347 Changed = true;
1348 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001349
Michael Gottesman89279f82013-04-05 18:10:41 +00001350 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001351 "objc_autorelease since its operand is not used as a return "
1352 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001353 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001354
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001355 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1356 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001357 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001358 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001359 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001360
Michael Gottesman89279f82013-04-05 18:10:41 +00001361 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001362
John McCalld935e9c2011-06-15 23:37:01 +00001363}
1364
Michael Gottesman158fdf62013-03-28 20:11:19 +00001365// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1366// calls.
1367//
1368// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1369// does not escape (following the rules of block escaping), strength reduce the
1370// objc_retainBlock to an objc_retain.
1371//
1372// TODO: If an objc_retainBlock call is dominated period by a previous
1373// objc_retainBlock call, strength reduce the objc_retainBlock to an
1374// objc_retain.
1375bool
1376ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1377 InstructionClass &Class) {
1378 assert(GetBasicInstructionClass(Inst) == Class);
1379 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001380
Michael Gottesman158fdf62013-03-28 20:11:19 +00001381 // If we can not optimize Inst, return false.
1382 if (!IsRetainBlockOptimizable(Inst))
1383 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001384
Michael Gottesman158fdf62013-03-28 20:11:19 +00001385 CallInst *RetainBlock = cast<CallInst>(Inst);
1386 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1387 // Remove copy_on_escape metadata.
1388 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1389 Class = IC_Retain;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001390
Michael Gottesman158fdf62013-03-28 20:11:19 +00001391 return true;
1392}
1393
Michael Gottesman97e3df02013-01-14 00:35:14 +00001394/// Visit each call, one at a time, and make simplifications without doing any
1395/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001396void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001397 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001398 // Reset all the flags in preparation for recomputing them.
1399 UsedInThisFunction = 0;
1400
1401 // Visit all objc_* calls in F.
1402 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1403 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001404
John McCalld935e9c2011-06-15 23:37:01 +00001405 InstructionClass Class = GetBasicInstructionClass(Inst);
1406
Michael Gottesman89279f82013-04-05 18:10:41 +00001407 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001408
John McCalld935e9c2011-06-15 23:37:01 +00001409 switch (Class) {
1410 default: break;
1411
1412 // Delete no-op casts. These function calls have special semantics, but
1413 // the semantics are entirely implemented via lowering in the front-end,
1414 // so by the time they reach the optimizer, they are just no-op calls
1415 // which return their argument.
1416 //
1417 // There are gray areas here, as the ability to cast reference-counted
1418 // pointers to raw void* and back allows code to break ARC assumptions,
1419 // however these are currently considered to be unimportant.
1420 case IC_NoopCast:
1421 Changed = true;
1422 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001423 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001424 EraseInstruction(Inst);
1425 continue;
1426
1427 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1428 case IC_StoreWeak:
1429 case IC_LoadWeak:
1430 case IC_LoadWeakRetained:
1431 case IC_InitWeak:
1432 case IC_DestroyWeak: {
1433 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001434 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001435 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001436 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001437 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1438 Constant::getNullValue(Ty),
1439 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001440 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001441 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1442 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001443 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001444 CI->eraseFromParent();
1445 continue;
1446 }
1447 break;
1448 }
1449 case IC_CopyWeak:
1450 case IC_MoveWeak: {
1451 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001452 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1453 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001454 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001455 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001456 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1457 Constant::getNullValue(Ty),
1458 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001459
1460 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001461 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1462 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001463
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001464 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001465 CI->eraseFromParent();
1466 continue;
1467 }
1468 break;
1469 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001470 case IC_RetainBlock:
1471 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1472 // onto the objc_retain peephole optimizations. Otherwise break.
1473 if (!OptimizeRetainBlockCall(F, Inst, Class))
1474 break;
1475 // FALLTHROUGH
John McCalld935e9c2011-06-15 23:37:01 +00001476 case IC_Retain:
1477 OptimizeRetainCall(F, Inst);
1478 break;
1479 case IC_RetainRV:
1480 if (OptimizeRetainRVCall(F, Inst))
1481 continue;
1482 break;
1483 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001484 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001485 break;
1486 }
1487
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001488 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001489 if (IsAutorelease(Class) && Inst->use_empty()) {
1490 CallInst *Call = cast<CallInst>(Inst);
1491 const Value *Arg = Call->getArgOperand(0);
1492 Arg = FindSingleUseIdentifiedObject(Arg);
1493 if (Arg) {
1494 Changed = true;
1495 ++NumAutoreleases;
1496
1497 // Create the declaration lazily.
1498 LLVMContext &C = Inst->getContext();
1499 CallInst *NewCall =
1500 CallInst::Create(getReleaseCallee(F.getParent()),
1501 Call->getArgOperand(0), "", Call);
1502 NewCall->setMetadata(ImpreciseReleaseMDKind,
1503 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001504
Michael Gottesman89279f82013-04-05 18:10:41 +00001505 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1506 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1507 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001508
John McCalld935e9c2011-06-15 23:37:01 +00001509 EraseInstruction(Call);
1510 Inst = NewCall;
1511 Class = IC_Release;
1512 }
1513 }
1514
1515 // For functions which can never be passed stack arguments, add
1516 // a tail keyword.
1517 if (IsAlwaysTail(Class)) {
1518 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001519 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1520 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001521 cast<CallInst>(Inst)->setTailCall();
1522 }
1523
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001524 // Ensure that functions that can never have a "tail" keyword due to the
1525 // semantics of ARC truly do not do so.
1526 if (IsNeverTail(Class)) {
1527 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001528 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001529 "\n");
1530 cast<CallInst>(Inst)->setTailCall(false);
1531 }
1532
John McCalld935e9c2011-06-15 23:37:01 +00001533 // Set nounwind as needed.
1534 if (IsNoThrow(Class)) {
1535 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001536 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1537 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001538 cast<CallInst>(Inst)->setDoesNotThrow();
1539 }
1540
1541 if (!IsNoopOnNull(Class)) {
1542 UsedInThisFunction |= 1 << Class;
1543 continue;
1544 }
1545
1546 const Value *Arg = GetObjCArg(Inst);
1547
1548 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001549 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001550 Changed = true;
1551 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001552 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1553 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001554 EraseInstruction(Inst);
1555 continue;
1556 }
1557
1558 // Keep track of which of retain, release, autorelease, and retain_block
1559 // are actually present in this function.
1560 UsedInThisFunction |= 1 << Class;
1561
1562 // If Arg is a PHI, and one or more incoming values to the
1563 // PHI are null, and the call is control-equivalent to the PHI, and there
1564 // are no relevant side effects between the PHI and the call, the call
1565 // could be pushed up to just those paths with non-null incoming values.
1566 // For now, don't bother splitting critical edges for this.
1567 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1568 Worklist.push_back(std::make_pair(Inst, Arg));
1569 do {
1570 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1571 Inst = Pair.first;
1572 Arg = Pair.second;
1573
1574 const PHINode *PN = dyn_cast<PHINode>(Arg);
1575 if (!PN) continue;
1576
1577 // Determine if the PHI has any null operands, or any incoming
1578 // critical edges.
1579 bool HasNull = false;
1580 bool HasCriticalEdges = false;
1581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1582 Value *Incoming =
1583 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001584 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001585 HasNull = true;
1586 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1587 .getNumSuccessors() != 1) {
1588 HasCriticalEdges = true;
1589 break;
1590 }
1591 }
1592 // If we have null operands and no critical edges, optimize.
1593 if (!HasCriticalEdges && HasNull) {
1594 SmallPtrSet<Instruction *, 4> DependingInstructions;
1595 SmallPtrSet<const BasicBlock *, 4> Visited;
1596
1597 // Check that there is nothing that cares about the reference
1598 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001599 switch (Class) {
1600 case IC_Retain:
1601 case IC_RetainBlock:
1602 // These can always be moved up.
1603 break;
1604 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001605 // These can't be moved across things that care about the retain
1606 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001607 FindDependencies(NeedsPositiveRetainCount, Arg,
1608 Inst->getParent(), Inst,
1609 DependingInstructions, Visited, PA);
1610 break;
1611 case IC_Autorelease:
1612 // These can't be moved across autorelease pool scope boundaries.
1613 FindDependencies(AutoreleasePoolBoundary, Arg,
1614 Inst->getParent(), Inst,
1615 DependingInstructions, Visited, PA);
1616 break;
1617 case IC_RetainRV:
1618 case IC_AutoreleaseRV:
1619 // Don't move these; the RV optimization depends on the autoreleaseRV
1620 // being tail called, and the retainRV being immediately after a call
1621 // (which might still happen if we get lucky with codegen layout, but
1622 // it's not worth taking the chance).
1623 continue;
1624 default:
1625 llvm_unreachable("Invalid dependence flavor");
1626 }
1627
John McCalld935e9c2011-06-15 23:37:01 +00001628 if (DependingInstructions.size() == 1 &&
1629 *DependingInstructions.begin() == PN) {
1630 Changed = true;
1631 ++NumPartialNoops;
1632 // Clone the call into each predecessor that has a non-null value.
1633 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001634 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001635 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1636 Value *Incoming =
1637 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001638 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001639 CallInst *Clone = cast<CallInst>(CInst->clone());
1640 Value *Op = PN->getIncomingValue(i);
1641 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1642 if (Op->getType() != ParamTy)
1643 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1644 Clone->setArgOperand(0, Op);
1645 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001646
Michael Gottesman89279f82013-04-05 18:10:41 +00001647 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001648 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001649 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001650 Worklist.push_back(std::make_pair(Clone, Incoming));
1651 }
1652 }
1653 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001654 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001655 EraseInstruction(CInst);
1656 continue;
1657 }
1658 }
1659 } while (!Worklist.empty());
1660 }
1661}
1662
Michael Gottesman97e3df02013-01-14 00:35:14 +00001663/// Check for critical edges, loop boundaries, irreducible control flow, or
1664/// other CFG structures where moving code across the edge would result in it
1665/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001666void
1667ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1668 DenseMap<const BasicBlock *, BBState> &BBStates,
1669 BBState &MyStates) const {
1670 // If any top-down local-use or possible-dec has a succ which is earlier in
1671 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001672 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001673 E = MyStates.top_down_ptr_end(); I != E; ++I)
1674 switch (I->second.GetSeq()) {
1675 default: break;
1676 case S_Use: {
1677 const Value *Arg = I->first;
1678 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1679 bool SomeSuccHasSame = false;
1680 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001681 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001682 succ_const_iterator SI(TI), SE(TI, false);
1683
Dan Gohman0155f302012-02-17 18:59:53 +00001684 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001685 Sequence SuccSSeq = S_None;
1686 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001687 // If VisitBottomUp has pointer information for this successor, take
1688 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001689 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1690 BBStates.find(*SI);
1691 assert(BBI != BBStates.end());
1692 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1693 SuccSSeq = SuccS.GetSeq();
1694 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001695 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001696 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001697 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001698 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001699 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001700 break;
1701 }
Dan Gohman12130272011-08-12 00:26:31 +00001702 continue;
1703 }
John McCalld935e9c2011-06-15 23:37:01 +00001704 case S_Use:
1705 SomeSuccHasSame = true;
1706 break;
1707 case S_Stop:
1708 case S_Release:
1709 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001710 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001711 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001712 break;
1713 case S_Retain:
1714 llvm_unreachable("bottom-up pointer in retain state!");
1715 }
Dan Gohman12130272011-08-12 00:26:31 +00001716 }
John McCalld935e9c2011-06-15 23:37:01 +00001717 // If the state at the other end of any of the successor edges
1718 // matches the current state, require all edges to match. This
1719 // guards against loops in the middle of a sequence.
1720 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001721 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001722 break;
John McCalld935e9c2011-06-15 23:37:01 +00001723 }
1724 case S_CanRelease: {
1725 const Value *Arg = I->first;
1726 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1727 bool SomeSuccHasSame = false;
1728 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001729 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001730 succ_const_iterator SI(TI), SE(TI, false);
1731
Dan Gohman0155f302012-02-17 18:59:53 +00001732 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001733 Sequence SuccSSeq = S_None;
1734 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001735 // If VisitBottomUp has pointer information for this successor, take
1736 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001737 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1738 BBStates.find(*SI);
1739 assert(BBI != BBStates.end());
1740 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1741 SuccSSeq = SuccS.GetSeq();
1742 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001743 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001744 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001745 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001746 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001747 break;
1748 }
Dan Gohman12130272011-08-12 00:26:31 +00001749 continue;
1750 }
John McCalld935e9c2011-06-15 23:37:01 +00001751 case S_CanRelease:
1752 SomeSuccHasSame = true;
1753 break;
1754 case S_Stop:
1755 case S_Release:
1756 case S_MovableRelease:
1757 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001758 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001759 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001760 break;
1761 case S_Retain:
1762 llvm_unreachable("bottom-up pointer in retain state!");
1763 }
Dan Gohman12130272011-08-12 00:26:31 +00001764 }
John McCalld935e9c2011-06-15 23:37:01 +00001765 // If the state at the other end of any of the successor edges
1766 // matches the current state, require all edges to match. This
1767 // guards against loops in the middle of a sequence.
1768 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001769 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001770 break;
John McCalld935e9c2011-06-15 23:37:01 +00001771 }
1772 }
1773}
1774
1775bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001776ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001777 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001778 MapVector<Value *, RRInfo> &Retains,
1779 BBState &MyStates) {
1780 bool NestingDetected = false;
1781 InstructionClass Class = GetInstructionClass(Inst);
1782 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001783
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001784 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001785
Dan Gohman817a7c62012-03-22 18:24:56 +00001786 switch (Class) {
1787 case IC_Release: {
1788 Arg = GetObjCArg(Inst);
1789
1790 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1791
1792 // If we see two releases in a row on the same pointer. If so, make
1793 // a note, and we'll cicle back to revisit it after we've
1794 // hopefully eliminated the second release, which may allow us to
1795 // eliminate the first release too.
1796 // Theoretically we could implement removal of nested retain+release
1797 // pairs by making PtrState hold a stack of states, but this is
1798 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001799 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001800 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001801 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001802 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001803
Dan Gohman817a7c62012-03-22 18:24:56 +00001804 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001805 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1806 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1807 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001808 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001809 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001810 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1811 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001812 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001813 break;
1814 }
1815 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001816 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1817 // objc_retainBlocks to objc_retains. Thus at this point any
1818 // objc_retainBlocks that we see are not optimizable.
1819 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001820 case IC_Retain:
1821 case IC_RetainRV: {
1822 Arg = GetObjCArg(Inst);
1823
1824 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001825 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001826
Michael Gottesman81b1d432013-03-26 00:42:04 +00001827 Sequence OldSeq = S.GetSeq();
1828 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001829 case S_Stop:
1830 case S_Release:
1831 case S_MovableRelease:
1832 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001833 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1834 // imprecise release, clear our reverse insertion points.
1835 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1836 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001837 // FALL THROUGH
1838 case S_CanRelease:
1839 // Don't do retain+release tracking for IC_RetainRV, because it's
1840 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001841 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001842 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001843 S.ClearSequenceProgress();
1844 break;
1845 case S_None:
1846 break;
1847 case S_Retain:
1848 llvm_unreachable("bottom-up pointer in retain state!");
1849 }
Michael Gottesman79249972013-04-05 23:46:45 +00001850 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001851 // A retain moving bottom up can be a use.
1852 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001853 }
1854 case IC_AutoreleasepoolPop:
1855 // Conservatively, clear MyStates for all known pointers.
1856 MyStates.clearBottomUpPointers();
1857 return NestingDetected;
1858 case IC_AutoreleasepoolPush:
1859 case IC_None:
1860 // These are irrelevant.
1861 return NestingDetected;
1862 default:
1863 break;
1864 }
1865
1866 // Consider any other possible effects of this instruction on each
1867 // pointer being tracked.
1868 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1869 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1870 const Value *Ptr = MI->first;
1871 if (Ptr == Arg)
1872 continue; // Handled above.
1873 PtrState &S = MI->second;
1874 Sequence Seq = S.GetSeq();
1875
1876 // Check for possible releases.
1877 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001878 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1879 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001880 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001881 switch (Seq) {
1882 case S_Use:
1883 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001884 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001885 continue;
1886 case S_CanRelease:
1887 case S_Release:
1888 case S_MovableRelease:
1889 case S_Stop:
1890 case S_None:
1891 break;
1892 case S_Retain:
1893 llvm_unreachable("bottom-up pointer in retain state!");
1894 }
1895 }
1896
1897 // Check for possible direct uses.
1898 switch (Seq) {
1899 case S_Release:
1900 case S_MovableRelease:
1901 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001902 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1903 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001904 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001905 // If this is an invoke instruction, we're scanning it as part of
1906 // one of its successor blocks, since we can't insert code after it
1907 // in its own block, and we don't want to split critical edges.
1908 if (isa<InvokeInst>(Inst))
1909 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1910 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001911 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001912 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001913 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001914 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001915 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1916 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001917 // Non-movable releases depend on any possible objc pointer use.
1918 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001919 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001920 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001921 // As above; handle invoke specially.
1922 if (isa<InvokeInst>(Inst))
1923 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1924 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001925 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001926 }
1927 break;
1928 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001929 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001930 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1931 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001932 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001933 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1934 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001935 break;
1936 case S_CanRelease:
1937 case S_Use:
1938 case S_None:
1939 break;
1940 case S_Retain:
1941 llvm_unreachable("bottom-up pointer in retain state!");
1942 }
1943 }
1944
1945 return NestingDetected;
1946}
1947
1948bool
John McCalld935e9c2011-06-15 23:37:01 +00001949ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1950 DenseMap<const BasicBlock *, BBState> &BBStates,
1951 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001952
1953 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001954
John McCalld935e9c2011-06-15 23:37:01 +00001955 bool NestingDetected = false;
1956 BBState &MyStates = BBStates[BB];
1957
1958 // Merge the states from each successor to compute the initial state
1959 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001960 BBState::edge_iterator SI(MyStates.succ_begin()),
1961 SE(MyStates.succ_end());
1962 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001963 const BasicBlock *Succ = *SI;
1964 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1965 assert(I != BBStates.end());
1966 MyStates.InitFromSucc(I->second);
1967 ++SI;
1968 for (; SI != SE; ++SI) {
1969 Succ = *SI;
1970 I = BBStates.find(Succ);
1971 assert(I != BBStates.end());
1972 MyStates.MergeSucc(I->second);
1973 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001974 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001975
Michael Gottesman43e7e002013-04-03 22:41:59 +00001976 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001977 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001978 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001979
John McCalld935e9c2011-06-15 23:37:01 +00001980 // Visit all the instructions, bottom-up.
1981 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1982 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001983
1984 // Invoke instructions are visited as part of their successors (below).
1985 if (isa<InvokeInst>(Inst))
1986 continue;
1987
Michael Gottesman89279f82013-04-05 18:10:41 +00001988 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001989
Dan Gohman5c70fad2012-03-23 17:47:54 +00001990 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1991 }
1992
Dan Gohmandae33492012-04-27 18:56:31 +00001993 // If there's a predecessor with an invoke, visit the invoke as if it were
1994 // part of this block, since we can't insert code after an invoke in its own
1995 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001996 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1997 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001998 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001999 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2000 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002001 }
John McCalld935e9c2011-06-15 23:37:01 +00002002
Michael Gottesman43e7e002013-04-03 22:41:59 +00002003 // If ARC Annotations are enabled, output the current state of pointers at the
2004 // top of the basic block.
2005 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002006
Dan Gohman817a7c62012-03-22 18:24:56 +00002007 return NestingDetected;
2008}
John McCalld935e9c2011-06-15 23:37:01 +00002009
Dan Gohman817a7c62012-03-22 18:24:56 +00002010bool
2011ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2012 DenseMap<Value *, RRInfo> &Releases,
2013 BBState &MyStates) {
2014 bool NestingDetected = false;
2015 InstructionClass Class = GetInstructionClass(Inst);
2016 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002017
Dan Gohman817a7c62012-03-22 18:24:56 +00002018 switch (Class) {
2019 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002020 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2021 // objc_retainBlocks to objc_retains. Thus at this point any
2022 // objc_retainBlocks that we see are not optimizable.
2023 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002024 case IC_Retain:
2025 case IC_RetainRV: {
2026 Arg = GetObjCArg(Inst);
2027
2028 PtrState &S = MyStates.getPtrTopDownState(Arg);
2029
2030 // Don't do retain+release tracking for IC_RetainRV, because it's
2031 // better to let it remain as the first instruction after a call.
2032 if (Class != IC_RetainRV) {
2033 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002034 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002035 // hopefully eliminated the second retain, which may allow us to
2036 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002037 // Theoretically we could implement removal of nested retain+release
2038 // pairs by making PtrState hold a stack of states, but this is
2039 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002040 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002041 NestingDetected = true;
2042
Michael Gottesman81b1d432013-03-26 00:42:04 +00002043 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002044 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002045 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002046 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002047 }
John McCalld935e9c2011-06-15 23:37:01 +00002048
Dan Gohmandf476e52012-09-04 23:16:20 +00002049 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002050
2051 // A retain can be a potential use; procede to the generic checking
2052 // code below.
2053 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002054 }
2055 case IC_Release: {
2056 Arg = GetObjCArg(Inst);
2057
2058 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002059 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002060
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002061 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002062
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002063 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002064
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002065 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002066 case S_Retain:
2067 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002068 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2069 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002070 // FALL THROUGH
2071 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002072 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002073 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2074 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002075 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002076 S.ClearSequenceProgress();
2077 break;
2078 case S_None:
2079 break;
2080 case S_Stop:
2081 case S_Release:
2082 case S_MovableRelease:
2083 llvm_unreachable("top-down pointer in release state!");
2084 }
2085 break;
2086 }
2087 case IC_AutoreleasepoolPop:
2088 // Conservatively, clear MyStates for all known pointers.
2089 MyStates.clearTopDownPointers();
2090 return NestingDetected;
2091 case IC_AutoreleasepoolPush:
2092 case IC_None:
2093 // These are irrelevant.
2094 return NestingDetected;
2095 default:
2096 break;
2097 }
2098
2099 // Consider any other possible effects of this instruction on each
2100 // pointer being tracked.
2101 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2102 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2103 const Value *Ptr = MI->first;
2104 if (Ptr == Arg)
2105 continue; // Handled above.
2106 PtrState &S = MI->second;
2107 Sequence Seq = S.GetSeq();
2108
2109 // Check for possible releases.
2110 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002111 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002112 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002113 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002114 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002115 case S_Retain:
2116 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002117 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002118 assert(S.RRI.ReverseInsertPts.empty());
2119 S.RRI.ReverseInsertPts.insert(Inst);
2120
2121 // One call can't cause a transition from S_Retain to S_CanRelease
2122 // and S_CanRelease to S_Use. If we've made the first transition,
2123 // we're done.
2124 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002125 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002126 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002127 case S_None:
2128 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002129 case S_Stop:
2130 case S_Release:
2131 case S_MovableRelease:
2132 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002133 }
2134 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002135
2136 // Check for possible direct uses.
2137 switch (Seq) {
2138 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002139 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002140 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2141 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002142 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002143 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2144 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002145 break;
2146 case S_Retain:
2147 case S_Use:
2148 case S_None:
2149 break;
2150 case S_Stop:
2151 case S_Release:
2152 case S_MovableRelease:
2153 llvm_unreachable("top-down pointer in release state!");
2154 }
John McCalld935e9c2011-06-15 23:37:01 +00002155 }
2156
2157 return NestingDetected;
2158}
2159
2160bool
2161ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2162 DenseMap<const BasicBlock *, BBState> &BBStates,
2163 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002164 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002165 bool NestingDetected = false;
2166 BBState &MyStates = BBStates[BB];
2167
2168 // Merge the states from each predecessor to compute the initial state
2169 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002170 BBState::edge_iterator PI(MyStates.pred_begin()),
2171 PE(MyStates.pred_end());
2172 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002173 const BasicBlock *Pred = *PI;
2174 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2175 assert(I != BBStates.end());
2176 MyStates.InitFromPred(I->second);
2177 ++PI;
2178 for (; PI != PE; ++PI) {
2179 Pred = *PI;
2180 I = BBStates.find(Pred);
2181 assert(I != BBStates.end());
2182 MyStates.MergePred(I->second);
2183 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002184 }
John McCalld935e9c2011-06-15 23:37:01 +00002185
Michael Gottesman43e7e002013-04-03 22:41:59 +00002186 // If ARC Annotations are enabled, output the current state of pointers at the
2187 // top of the basic block.
2188 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002189
John McCalld935e9c2011-06-15 23:37:01 +00002190 // Visit all the instructions, top-down.
2191 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2192 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002193
Michael Gottesman89279f82013-04-05 18:10:41 +00002194 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002195
Dan Gohman817a7c62012-03-22 18:24:56 +00002196 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002197 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002198
Michael Gottesman43e7e002013-04-03 22:41:59 +00002199 // If ARC Annotations are enabled, output the current state of pointers at the
2200 // bottom of the basic block.
2201 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002202
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002203#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002204 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002205#endif
John McCalld935e9c2011-06-15 23:37:01 +00002206 CheckForCFGHazards(BB, BBStates, MyStates);
2207 return NestingDetected;
2208}
2209
Dan Gohmana53a12c2011-12-12 19:42:25 +00002210static void
2211ComputePostOrders(Function &F,
2212 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002213 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2214 unsigned NoObjCARCExceptionsMDKind,
2215 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002216 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002217 SmallPtrSet<BasicBlock *, 16> Visited;
2218
2219 // Do DFS, computing the PostOrder.
2220 SmallPtrSet<BasicBlock *, 16> OnStack;
2221 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002222
2223 // Functions always have exactly one entry block, and we don't have
2224 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002225 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002226 BBState &MyStates = BBStates[EntryBB];
2227 MyStates.SetAsEntry();
2228 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2229 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002230 Visited.insert(EntryBB);
2231 OnStack.insert(EntryBB);
2232 do {
2233 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002234 BasicBlock *CurrBB = SuccStack.back().first;
2235 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2236 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002237
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002238 while (SuccStack.back().second != SE) {
2239 BasicBlock *SuccBB = *SuccStack.back().second++;
2240 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002241 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2242 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002243 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002244 BBState &SuccStates = BBStates[SuccBB];
2245 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002246 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002247 goto dfs_next_succ;
2248 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002249
2250 if (!OnStack.count(SuccBB)) {
2251 BBStates[CurrBB].addSucc(SuccBB);
2252 BBStates[SuccBB].addPred(CurrBB);
2253 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002254 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002255 OnStack.erase(CurrBB);
2256 PostOrder.push_back(CurrBB);
2257 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002258 } while (!SuccStack.empty());
2259
2260 Visited.clear();
2261
Dan Gohmana53a12c2011-12-12 19:42:25 +00002262 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002263 // Functions may have many exits, and there also blocks which we treat
2264 // as exits due to ignored edges.
2265 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2266 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2267 BasicBlock *ExitBB = I;
2268 BBState &MyStates = BBStates[ExitBB];
2269 if (!MyStates.isExit())
2270 continue;
2271
Dan Gohmandae33492012-04-27 18:56:31 +00002272 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002273
2274 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002275 Visited.insert(ExitBB);
2276 while (!PredStack.empty()) {
2277 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002278 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2279 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002280 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002281 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002282 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002283 goto reverse_dfs_next_succ;
2284 }
2285 }
2286 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2287 }
2288 }
2289}
2290
Michael Gottesman97e3df02013-01-14 00:35:14 +00002291// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002292bool
2293ObjCARCOpt::Visit(Function &F,
2294 DenseMap<const BasicBlock *, BBState> &BBStates,
2295 MapVector<Value *, RRInfo> &Retains,
2296 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002297
2298 // Use reverse-postorder traversals, because we magically know that loops
2299 // will be well behaved, i.e. they won't repeatedly call retain on a single
2300 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2301 // class here because we want the reverse-CFG postorder to consider each
2302 // function exit point, and we want to ignore selected cycle edges.
2303 SmallVector<BasicBlock *, 16> PostOrder;
2304 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002305 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2306 NoObjCARCExceptionsMDKind,
2307 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002308
2309 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002310 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002311 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002312 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2313 I != E; ++I)
2314 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002315
Dan Gohmana53a12c2011-12-12 19:42:25 +00002316 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002317 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002318 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2319 PostOrder.rbegin(), E = PostOrder.rend();
2320 I != E; ++I)
2321 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002322
2323 return TopDownNestingDetected && BottomUpNestingDetected;
2324}
2325
Michael Gottesman97e3df02013-01-14 00:35:14 +00002326/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002327void ObjCARCOpt::MoveCalls(Value *Arg,
2328 RRInfo &RetainsToMove,
2329 RRInfo &ReleasesToMove,
2330 MapVector<Value *, RRInfo> &Retains,
2331 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002332 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002333 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002334 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002335 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002336
Michael Gottesman89279f82013-04-05 18:10:41 +00002337 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002338
John McCalld935e9c2011-06-15 23:37:01 +00002339 // Insert the new retain and release calls.
2340 for (SmallPtrSet<Instruction *, 2>::const_iterator
2341 PI = ReleasesToMove.ReverseInsertPts.begin(),
2342 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2343 Instruction *InsertPt = *PI;
2344 Value *MyArg = ArgTy == ParamTy ? Arg :
2345 new BitCastInst(Arg, ParamTy, "", InsertPt);
2346 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002347 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002348 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002349 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002350
Michael Gottesman89279f82013-04-05 18:10:41 +00002351 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2352 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002353 }
2354 for (SmallPtrSet<Instruction *, 2>::const_iterator
2355 PI = RetainsToMove.ReverseInsertPts.begin(),
2356 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002357 Instruction *InsertPt = *PI;
2358 Value *MyArg = ArgTy == ParamTy ? Arg :
2359 new BitCastInst(Arg, ParamTy, "", InsertPt);
2360 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2361 "", InsertPt);
2362 // Attach a clang.imprecise_release metadata tag, if appropriate.
2363 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2364 Call->setMetadata(ImpreciseReleaseMDKind, M);
2365 Call->setDoesNotThrow();
2366 if (ReleasesToMove.IsTailCallRelease)
2367 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002368
Michael Gottesman89279f82013-04-05 18:10:41 +00002369 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2370 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002371 }
2372
2373 // Delete the original retain and release calls.
2374 for (SmallPtrSet<Instruction *, 2>::const_iterator
2375 AI = RetainsToMove.Calls.begin(),
2376 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2377 Instruction *OrigRetain = *AI;
2378 Retains.blot(OrigRetain);
2379 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002380 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002381 }
2382 for (SmallPtrSet<Instruction *, 2>::const_iterator
2383 AI = ReleasesToMove.Calls.begin(),
2384 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2385 Instruction *OrigRelease = *AI;
2386 Releases.erase(OrigRelease);
2387 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002388 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002389 }
Michael Gottesman79249972013-04-05 23:46:45 +00002390
John McCalld935e9c2011-06-15 23:37:01 +00002391}
2392
Michael Gottesman9de6f962013-01-22 21:49:00 +00002393bool
2394ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2395 &BBStates,
2396 MapVector<Value *, RRInfo> &Retains,
2397 DenseMap<Value *, RRInfo> &Releases,
2398 Module *M,
2399 SmallVector<Instruction *, 4> &NewRetains,
2400 SmallVector<Instruction *, 4> &NewReleases,
2401 SmallVector<Instruction *, 8> &DeadInsts,
2402 RRInfo &RetainsToMove,
2403 RRInfo &ReleasesToMove,
2404 Value *Arg,
2405 bool KnownSafe,
2406 bool &AnyPairsCompletelyEliminated) {
2407 // If a pair happens in a region where it is known that the reference count
2408 // is already incremented, we can similarly ignore possible decrements.
2409 bool KnownSafeTD = true, KnownSafeBU = true;
2410
2411 // Connect the dots between the top-down-collected RetainsToMove and
2412 // bottom-up-collected ReleasesToMove to form sets of related calls.
2413 // This is an iterative process so that we connect multiple releases
2414 // to multiple retains if needed.
2415 unsigned OldDelta = 0;
2416 unsigned NewDelta = 0;
2417 unsigned OldCount = 0;
2418 unsigned NewCount = 0;
2419 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002420 for (;;) {
2421 for (SmallVectorImpl<Instruction *>::const_iterator
2422 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2423 Instruction *NewRetain = *NI;
2424 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2425 assert(It != Retains.end());
2426 const RRInfo &NewRetainRRI = It->second;
2427 KnownSafeTD &= NewRetainRRI.KnownSafe;
2428 for (SmallPtrSet<Instruction *, 2>::const_iterator
2429 LI = NewRetainRRI.Calls.begin(),
2430 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2431 Instruction *NewRetainRelease = *LI;
2432 DenseMap<Value *, RRInfo>::const_iterator Jt =
2433 Releases.find(NewRetainRelease);
2434 if (Jt == Releases.end())
2435 return false;
2436 const RRInfo &NewRetainReleaseRRI = Jt->second;
2437 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2438 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2439 OldDelta -=
2440 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2441
2442 // Merge the ReleaseMetadata and IsTailCallRelease values.
2443 if (FirstRelease) {
2444 ReleasesToMove.ReleaseMetadata =
2445 NewRetainReleaseRRI.ReleaseMetadata;
2446 ReleasesToMove.IsTailCallRelease =
2447 NewRetainReleaseRRI.IsTailCallRelease;
2448 FirstRelease = false;
2449 } else {
2450 if (ReleasesToMove.ReleaseMetadata !=
2451 NewRetainReleaseRRI.ReleaseMetadata)
2452 ReleasesToMove.ReleaseMetadata = 0;
2453 if (ReleasesToMove.IsTailCallRelease !=
2454 NewRetainReleaseRRI.IsTailCallRelease)
2455 ReleasesToMove.IsTailCallRelease = false;
2456 }
2457
2458 // Collect the optimal insertion points.
2459 if (!KnownSafe)
2460 for (SmallPtrSet<Instruction *, 2>::const_iterator
2461 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2462 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2463 RI != RE; ++RI) {
2464 Instruction *RIP = *RI;
2465 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2466 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2467 }
2468 NewReleases.push_back(NewRetainRelease);
2469 }
2470 }
2471 }
2472 NewRetains.clear();
2473 if (NewReleases.empty()) break;
2474
2475 // Back the other way.
2476 for (SmallVectorImpl<Instruction *>::const_iterator
2477 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2478 Instruction *NewRelease = *NI;
2479 DenseMap<Value *, RRInfo>::const_iterator It =
2480 Releases.find(NewRelease);
2481 assert(It != Releases.end());
2482 const RRInfo &NewReleaseRRI = It->second;
2483 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2484 for (SmallPtrSet<Instruction *, 2>::const_iterator
2485 LI = NewReleaseRRI.Calls.begin(),
2486 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2487 Instruction *NewReleaseRetain = *LI;
2488 MapVector<Value *, RRInfo>::const_iterator Jt =
2489 Retains.find(NewReleaseRetain);
2490 if (Jt == Retains.end())
2491 return false;
2492 const RRInfo &NewReleaseRetainRRI = Jt->second;
2493 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2494 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2495 unsigned PathCount =
2496 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2497 OldDelta += PathCount;
2498 OldCount += PathCount;
2499
Michael Gottesman9de6f962013-01-22 21:49:00 +00002500 // Collect the optimal insertion points.
2501 if (!KnownSafe)
2502 for (SmallPtrSet<Instruction *, 2>::const_iterator
2503 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2504 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2505 RI != RE; ++RI) {
2506 Instruction *RIP = *RI;
2507 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2508 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2509 NewDelta += PathCount;
2510 NewCount += PathCount;
2511 }
2512 }
2513 NewRetains.push_back(NewReleaseRetain);
2514 }
2515 }
2516 }
2517 NewReleases.clear();
2518 if (NewRetains.empty()) break;
2519 }
2520
2521 // If the pointer is known incremented or nested, we can safely delete the
2522 // pair regardless of what's between them.
2523 if (KnownSafeTD || KnownSafeBU) {
2524 RetainsToMove.ReverseInsertPts.clear();
2525 ReleasesToMove.ReverseInsertPts.clear();
2526 NewCount = 0;
2527 } else {
2528 // Determine whether the new insertion points we computed preserve the
2529 // balance of retain and release calls through the program.
2530 // TODO: If the fully aggressive solution isn't valid, try to find a
2531 // less aggressive solution which is.
2532 if (NewDelta != 0)
2533 return false;
2534 }
2535
2536 // Determine whether the original call points are balanced in the retain and
2537 // release calls through the program. If not, conservatively don't touch
2538 // them.
2539 // TODO: It's theoretically possible to do code motion in this case, as
2540 // long as the existing imbalances are maintained.
2541 if (OldDelta != 0)
2542 return false;
2543
2544 Changed = true;
2545 assert(OldCount != 0 && "Unreachable code?");
2546 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002547 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002548 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002549
2550 // We can move calls!
2551 return true;
2552}
2553
Michael Gottesman97e3df02013-01-14 00:35:14 +00002554/// Identify pairings between the retains and releases, and delete and/or move
2555/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002556bool
2557ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2558 &BBStates,
2559 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002560 DenseMap<Value *, RRInfo> &Releases,
2561 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002562 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2563
John McCalld935e9c2011-06-15 23:37:01 +00002564 bool AnyPairsCompletelyEliminated = false;
2565 RRInfo RetainsToMove;
2566 RRInfo ReleasesToMove;
2567 SmallVector<Instruction *, 4> NewRetains;
2568 SmallVector<Instruction *, 4> NewReleases;
2569 SmallVector<Instruction *, 8> DeadInsts;
2570
Dan Gohman670f9372012-04-13 18:57:48 +00002571 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002572 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002573 E = Retains.end(); I != E; ++I) {
2574 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002575 if (!V) continue; // blotted
2576
2577 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002578
Michael Gottesman89279f82013-04-05 18:10:41 +00002579 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002580
John McCalld935e9c2011-06-15 23:37:01 +00002581 Value *Arg = GetObjCArg(Retain);
2582
Dan Gohman728db492012-01-13 00:39:07 +00002583 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002584 // not being managed by ObjC reference counting, so we can delete pairs
2585 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002586 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002587
Dan Gohman56e1cef2011-08-22 17:29:11 +00002588 // A constant pointer can't be pointing to an object on the heap. It may
2589 // be reference-counted, but it won't be deleted.
2590 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2591 if (const GlobalVariable *GV =
2592 dyn_cast<GlobalVariable>(
2593 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2594 if (GV->isConstant())
2595 KnownSafe = true;
2596
John McCalld935e9c2011-06-15 23:37:01 +00002597 // Connect the dots between the top-down-collected RetainsToMove and
2598 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002599 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002600 bool PerformMoveCalls =
2601 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2602 NewReleases, DeadInsts, RetainsToMove,
2603 ReleasesToMove, Arg, KnownSafe,
2604 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002605
Michael Gottesman81b1d432013-03-26 00:42:04 +00002606#ifdef ARC_ANNOTATIONS
2607 // Do not move calls if ARC annotations are requested. If we were to move
2608 // calls in this case, we would not be able
2609 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2610#endif // ARC_ANNOTATIONS
2611
Michael Gottesman9de6f962013-01-22 21:49:00 +00002612 if (PerformMoveCalls) {
2613 // Ok, everything checks out and we're all set. Let's move/delete some
2614 // code!
2615 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2616 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002617 }
2618
Michael Gottesman9de6f962013-01-22 21:49:00 +00002619 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002620 NewReleases.clear();
2621 NewRetains.clear();
2622 RetainsToMove.clear();
2623 ReleasesToMove.clear();
2624 }
2625
2626 // Now that we're done moving everything, we can delete the newly dead
2627 // instructions, as we no longer need them as insert points.
2628 while (!DeadInsts.empty())
2629 EraseInstruction(DeadInsts.pop_back_val());
2630
2631 return AnyPairsCompletelyEliminated;
2632}
2633
Michael Gottesman97e3df02013-01-14 00:35:14 +00002634/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002635void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002636 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002637
John McCalld935e9c2011-06-15 23:37:01 +00002638 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2639 // itself because it uses AliasAnalysis and we need to do provenance
2640 // queries instead.
2641 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2642 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002643
Michael Gottesman89279f82013-04-05 18:10:41 +00002644 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002645
John McCalld935e9c2011-06-15 23:37:01 +00002646 InstructionClass Class = GetBasicInstructionClass(Inst);
2647 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2648 continue;
2649
2650 // Delete objc_loadWeak calls with no users.
2651 if (Class == IC_LoadWeak && Inst->use_empty()) {
2652 Inst->eraseFromParent();
2653 continue;
2654 }
2655
2656 // TODO: For now, just look for an earlier available version of this value
2657 // within the same block. Theoretically, we could do memdep-style non-local
2658 // analysis too, but that would want caching. A better approach would be to
2659 // use the technique that EarlyCSE uses.
2660 inst_iterator Current = llvm::prior(I);
2661 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2662 for (BasicBlock::iterator B = CurrentBB->begin(),
2663 J = Current.getInstructionIterator();
2664 J != B; --J) {
2665 Instruction *EarlierInst = &*llvm::prior(J);
2666 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2667 switch (EarlierClass) {
2668 case IC_LoadWeak:
2669 case IC_LoadWeakRetained: {
2670 // If this is loading from the same pointer, replace this load's value
2671 // with that one.
2672 CallInst *Call = cast<CallInst>(Inst);
2673 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2674 Value *Arg = Call->getArgOperand(0);
2675 Value *EarlierArg = EarlierCall->getArgOperand(0);
2676 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2677 case AliasAnalysis::MustAlias:
2678 Changed = true;
2679 // If the load has a builtin retain, insert a plain retain for it.
2680 if (Class == IC_LoadWeakRetained) {
2681 CallInst *CI =
2682 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2683 "", Call);
2684 CI->setTailCall();
2685 }
2686 // Zap the fully redundant load.
2687 Call->replaceAllUsesWith(EarlierCall);
2688 Call->eraseFromParent();
2689 goto clobbered;
2690 case AliasAnalysis::MayAlias:
2691 case AliasAnalysis::PartialAlias:
2692 goto clobbered;
2693 case AliasAnalysis::NoAlias:
2694 break;
2695 }
2696 break;
2697 }
2698 case IC_StoreWeak:
2699 case IC_InitWeak: {
2700 // If this is storing to the same pointer and has the same size etc.
2701 // replace this load's value with the stored value.
2702 CallInst *Call = cast<CallInst>(Inst);
2703 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2704 Value *Arg = Call->getArgOperand(0);
2705 Value *EarlierArg = EarlierCall->getArgOperand(0);
2706 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2707 case AliasAnalysis::MustAlias:
2708 Changed = true;
2709 // If the load has a builtin retain, insert a plain retain for it.
2710 if (Class == IC_LoadWeakRetained) {
2711 CallInst *CI =
2712 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2713 "", Call);
2714 CI->setTailCall();
2715 }
2716 // Zap the fully redundant load.
2717 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2718 Call->eraseFromParent();
2719 goto clobbered;
2720 case AliasAnalysis::MayAlias:
2721 case AliasAnalysis::PartialAlias:
2722 goto clobbered;
2723 case AliasAnalysis::NoAlias:
2724 break;
2725 }
2726 break;
2727 }
2728 case IC_MoveWeak:
2729 case IC_CopyWeak:
2730 // TOOD: Grab the copied value.
2731 goto clobbered;
2732 case IC_AutoreleasepoolPush:
2733 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002734 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002735 case IC_User:
2736 // Weak pointers are only modified through the weak entry points
2737 // (and arbitrary calls, which could call the weak entry points).
2738 break;
2739 default:
2740 // Anything else could modify the weak pointer.
2741 goto clobbered;
2742 }
2743 }
2744 clobbered:;
2745 }
2746
2747 // Then, for each destroyWeak with an alloca operand, check to see if
2748 // the alloca and all its users can be zapped.
2749 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2750 Instruction *Inst = &*I++;
2751 InstructionClass Class = GetBasicInstructionClass(Inst);
2752 if (Class != IC_DestroyWeak)
2753 continue;
2754
2755 CallInst *Call = cast<CallInst>(Inst);
2756 Value *Arg = Call->getArgOperand(0);
2757 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2758 for (Value::use_iterator UI = Alloca->use_begin(),
2759 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002760 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002761 switch (GetBasicInstructionClass(UserInst)) {
2762 case IC_InitWeak:
2763 case IC_StoreWeak:
2764 case IC_DestroyWeak:
2765 continue;
2766 default:
2767 goto done;
2768 }
2769 }
2770 Changed = true;
2771 for (Value::use_iterator UI = Alloca->use_begin(),
2772 UE = Alloca->use_end(); UI != UE; ) {
2773 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002774 switch (GetBasicInstructionClass(UserInst)) {
2775 case IC_InitWeak:
2776 case IC_StoreWeak:
2777 // These functions return their second argument.
2778 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2779 break;
2780 case IC_DestroyWeak:
2781 // No return value.
2782 break;
2783 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002784 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002785 }
John McCalld935e9c2011-06-15 23:37:01 +00002786 UserInst->eraseFromParent();
2787 }
2788 Alloca->eraseFromParent();
2789 done:;
2790 }
2791 }
2792}
2793
Michael Gottesman97e3df02013-01-14 00:35:14 +00002794/// Identify program paths which execute sequences of retains and releases which
2795/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002796bool ObjCARCOpt::OptimizeSequences(Function &F) {
2797 /// Releases, Retains - These are used to store the results of the main flow
2798 /// analysis. These use Value* as the key instead of Instruction* so that the
2799 /// map stays valid when we get around to rewriting code and calls get
2800 /// replaced by arguments.
2801 DenseMap<Value *, RRInfo> Releases;
2802 MapVector<Value *, RRInfo> Retains;
2803
Michael Gottesman97e3df02013-01-14 00:35:14 +00002804 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002805 /// states for each identified object at each block.
2806 DenseMap<const BasicBlock *, BBState> BBStates;
2807
2808 // Analyze the CFG of the function, and all instructions.
2809 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2810
2811 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002812 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2813 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002814}
2815
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002816/// Check if there is a dependent call earlier that does not have anything in
2817/// between the Retain and the call that can affect the reference count of their
2818/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002819static bool
2820HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2821 SmallPtrSet<Instruction *, 4> &DepInsts,
2822 SmallPtrSet<const BasicBlock *, 4> &Visited,
2823 ProvenanceAnalysis &PA) {
2824 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2825 DepInsts, Visited, PA);
2826 if (DepInsts.size() != 1)
2827 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002828
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002829 CallInst *Call =
2830 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002831
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002832 // Check that the pointer is the return value of the call.
2833 if (!Call || Arg != Call)
2834 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002835
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002836 // Check that the call is a regular call.
2837 InstructionClass Class = GetBasicInstructionClass(Call);
2838 if (Class != IC_CallOrUser && Class != IC_Call)
2839 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002840
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002841 return true;
2842}
2843
Michael Gottesman6908db12013-04-03 23:16:05 +00002844/// Find a dependent retain that precedes the given autorelease for which there
2845/// is nothing in between the two instructions that can affect the ref count of
2846/// Arg.
2847static CallInst *
2848FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2849 Instruction *Autorelease,
2850 SmallPtrSet<Instruction *, 4> &DepInsts,
2851 SmallPtrSet<const BasicBlock *, 4> &Visited,
2852 ProvenanceAnalysis &PA) {
2853 FindDependencies(CanChangeRetainCount, Arg,
2854 BB, Autorelease, DepInsts, Visited, PA);
2855 if (DepInsts.size() != 1)
2856 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002857
Michael Gottesman6908db12013-04-03 23:16:05 +00002858 CallInst *Retain =
2859 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002860
Michael Gottesman6908db12013-04-03 23:16:05 +00002861 // Check that we found a retain with the same argument.
2862 if (!Retain ||
2863 !IsRetain(GetBasicInstructionClass(Retain)) ||
2864 GetObjCArg(Retain) != Arg) {
2865 return 0;
2866 }
Michael Gottesman79249972013-04-05 23:46:45 +00002867
Michael Gottesman6908db12013-04-03 23:16:05 +00002868 return Retain;
2869}
2870
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002871/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2872/// no instructions dependent on Arg that need a positive ref count in between
2873/// the autorelease and the ret.
2874static CallInst *
2875FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2876 ReturnInst *Ret,
2877 SmallPtrSet<Instruction *, 4> &DepInsts,
2878 SmallPtrSet<const BasicBlock *, 4> &V,
2879 ProvenanceAnalysis &PA) {
2880 FindDependencies(NeedsPositiveRetainCount, Arg,
2881 BB, Ret, DepInsts, V, PA);
2882 if (DepInsts.size() != 1)
2883 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002884
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002885 CallInst *Autorelease =
2886 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2887 if (!Autorelease)
2888 return 0;
2889 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2890 if (!IsAutorelease(AutoreleaseClass))
2891 return 0;
2892 if (GetObjCArg(Autorelease) != Arg)
2893 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002894
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002895 return Autorelease;
2896}
2897
Michael Gottesman97e3df02013-01-14 00:35:14 +00002898/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002899/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002900/// %call = call i8* @something(...)
2901/// %2 = call i8* @objc_retain(i8* %call)
2902/// %3 = call i8* @objc_autorelease(i8* %2)
2903/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002904/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002905/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002906void ObjCARCOpt::OptimizeReturns(Function &F) {
2907 if (!F.getReturnType()->isPointerTy())
2908 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002909
Michael Gottesman89279f82013-04-05 18:10:41 +00002910 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002911
John McCalld935e9c2011-06-15 23:37:01 +00002912 SmallPtrSet<Instruction *, 4> DependingInstructions;
2913 SmallPtrSet<const BasicBlock *, 4> Visited;
2914 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2915 BasicBlock *BB = FI;
2916 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002917
Michael Gottesman89279f82013-04-05 18:10:41 +00002918 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002919
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002920 if (!Ret)
2921 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002922
John McCalld935e9c2011-06-15 23:37:01 +00002923 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002924
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002925 // Look for an ``autorelease'' instruction that is a predecssor of Ret and
2926 // dependent on Arg such that there are no instructions dependent on Arg
2927 // that need a positive ref count in between the autorelease and Ret.
2928 CallInst *Autorelease =
2929 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2930 DependingInstructions, Visited,
2931 PA);
2932 if (Autorelease) {
John McCalld935e9c2011-06-15 23:37:01 +00002933 DependingInstructions.clear();
2934 Visited.clear();
Michael Gottesman79249972013-04-05 23:46:45 +00002935
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002936 CallInst *Retain =
2937 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2938 DependingInstructions, Visited, PA);
2939 if (Retain) {
John McCalld935e9c2011-06-15 23:37:01 +00002940 DependingInstructions.clear();
2941 Visited.clear();
Michael Gottesman79249972013-04-05 23:46:45 +00002942
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002943 // Check that there is nothing that can affect the reference count
2944 // between the retain and the call. Note that Retain need not be in BB.
2945 if (HasSafePathToPredecessorCall(Arg, Retain, DependingInstructions,
2946 Visited, PA)) {
John McCalld935e9c2011-06-15 23:37:01 +00002947 // If so, we can zap the retain and autorelease.
2948 Changed = true;
2949 ++NumRets;
Michael Gottesman89279f82013-04-05 18:10:41 +00002950 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002951 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002952 EraseInstruction(Retain);
2953 EraseInstruction(Autorelease);
2954 }
2955 }
2956 }
Michael Gottesman79249972013-04-05 23:46:45 +00002957
John McCalld935e9c2011-06-15 23:37:01 +00002958 DependingInstructions.clear();
2959 Visited.clear();
2960 }
2961}
2962
2963bool ObjCARCOpt::doInitialization(Module &M) {
2964 if (!EnableARCOpts)
2965 return false;
2966
Dan Gohman670f9372012-04-13 18:57:48 +00002967 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002968 Run = ModuleHasARC(M);
2969 if (!Run)
2970 return false;
2971
John McCalld935e9c2011-06-15 23:37:01 +00002972 // Identify the imprecise release metadata kind.
2973 ImpreciseReleaseMDKind =
2974 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002975 CopyOnEscapeMDKind =
2976 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002977 NoObjCARCExceptionsMDKind =
2978 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002979#ifdef ARC_ANNOTATIONS
2980 ARCAnnotationBottomUpMDKind =
2981 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2982 ARCAnnotationTopDownMDKind =
2983 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2984 ARCAnnotationProvenanceSourceMDKind =
2985 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2986#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002987
John McCalld935e9c2011-06-15 23:37:01 +00002988 // Intuitively, objc_retain and others are nocapture, however in practice
2989 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002990 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002991
2992 // These are initialized lazily.
2993 RetainRVCallee = 0;
2994 AutoreleaseRVCallee = 0;
2995 ReleaseCallee = 0;
2996 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002997 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002998 AutoreleaseCallee = 0;
2999
3000 return false;
3001}
3002
3003bool ObjCARCOpt::runOnFunction(Function &F) {
3004 if (!EnableARCOpts)
3005 return false;
3006
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003007 // If nothing in the Module uses ARC, don't do anything.
3008 if (!Run)
3009 return false;
3010
John McCalld935e9c2011-06-15 23:37:01 +00003011 Changed = false;
3012
Michael Gottesman89279f82013-04-05 18:10:41 +00003013 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3014 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003015
John McCalld935e9c2011-06-15 23:37:01 +00003016 PA.setAA(&getAnalysis<AliasAnalysis>());
3017
3018 // This pass performs several distinct transformations. As a compile-time aid
3019 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3020 // library functions aren't declared.
3021
3022 // Preliminary optimizations. This also computs UsedInThisFunction.
3023 OptimizeIndividualCalls(F);
3024
3025 // Optimizations for weak pointers.
3026 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3027 (1 << IC_LoadWeakRetained) |
3028 (1 << IC_StoreWeak) |
3029 (1 << IC_InitWeak) |
3030 (1 << IC_CopyWeak) |
3031 (1 << IC_MoveWeak) |
3032 (1 << IC_DestroyWeak)))
3033 OptimizeWeakCalls(F);
3034
3035 // Optimizations for retain+release pairs.
3036 if (UsedInThisFunction & ((1 << IC_Retain) |
3037 (1 << IC_RetainRV) |
3038 (1 << IC_RetainBlock)))
3039 if (UsedInThisFunction & (1 << IC_Release))
3040 // Run OptimizeSequences until it either stops making changes or
3041 // no retain+release pair nesting is detected.
3042 while (OptimizeSequences(F)) {}
3043
3044 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003045 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3046 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003047 OptimizeReturns(F);
3048
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003049 DEBUG(dbgs() << "\n");
3050
John McCalld935e9c2011-06-15 23:37:01 +00003051 return Changed;
3052}
3053
3054void ObjCARCOpt::releaseMemory() {
3055 PA.clear();
3056}
3057
Michael Gottesman97e3df02013-01-14 00:35:14 +00003058/// @}
3059///