blob: 92d6fc4767c2f6108de27394d1dfe53e95778355 [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 Gottesman774d2c02013-01-29 21:00:52 +0000194 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: 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 Gottesman774d2c02013-01-29 21:00:52 +0000200 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: 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 Gottesman23cda0c2013-01-29 21:07:53 +0000210 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies pointer "
211 "arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000212 // These special functions make copies of their pointer arguments.
213 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000214 }
John McCall20182ac2013-03-22 21:38:36 +0000215 case IC_IntrinsicUser:
216 // Use by the use intrinsic is not an escape.
217 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 case IC_User:
219 case IC_None:
220 // Use by an instruction which copies the value is an escape if the
221 // result is an escape.
222 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
223 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000224
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000225 if (VisitedSet.insert(UUser)) {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000226 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies value. "
227 "Ptr escapes if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000228 Worklist.push_back(UUser);
229 } else {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000230 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Already visited node."
231 "\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000232 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000233 continue;
234 }
235 // Use by a load is not an escape.
236 if (isa<LoadInst>(UUser))
237 continue;
238 // Use by a store is not an escape if the use is the address.
239 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
240 if (V != SI->getValueOperand())
241 continue;
242 break;
243 default:
244 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000245 continue;
246 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000247 // Otherwise, conservatively assume an escape.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000248 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000249 return true;
250 }
251 } while (!Worklist.empty());
252
253 // No escapes found.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000254 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000255 return false;
256}
257
Michael Gottesman97e3df02013-01-14 00:35:14 +0000258/// @}
259///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000260/// \defgroup ARCOpt ARC Optimization.
261/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000262
263// TODO: On code like this:
264//
265// objc_retain(%x)
266// stuff_that_cannot_release()
267// objc_autorelease(%x)
268// stuff_that_cannot_release()
269// objc_retain(%x)
270// stuff_that_cannot_release()
271// objc_autorelease(%x)
272//
273// The second retain and autorelease can be deleted.
274
275// TODO: It should be possible to delete
276// objc_autoreleasePoolPush and objc_autoreleasePoolPop
277// pairs if nothing is actually autoreleased between them. Also, autorelease
278// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
279// after inlining) can be turned into plain release calls.
280
281// TODO: Critical-edge splitting. If the optimial insertion point is
282// a critical edge, the current algorithm has to fail, because it doesn't
283// know how to split edges. It should be possible to make the optimizer
284// think in terms of edges, rather than blocks, and then split critical
285// edges on demand.
286
287// TODO: OptimizeSequences could generalized to be Interprocedural.
288
289// TODO: Recognize that a bunch of other objc runtime calls have
290// non-escaping arguments and non-releasing arguments, and may be
291// non-autoreleasing.
292
293// TODO: Sink autorelease calls as far as possible. Unfortunately we
294// usually can't sink them past other calls, which would be the main
295// case where it would be useful.
296
Dan Gohmanb3894012011-08-19 00:26:36 +0000297// TODO: The pointer returned from objc_loadWeakRetained is retained.
298
299// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000300
John McCalld935e9c2011-06-15 23:37:01 +0000301STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
302STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
303STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
304STATISTIC(NumRets, "Number of return value forwarding "
305 "retain+autoreleaes eliminated");
306STATISTIC(NumRRs, "Number of retain+release paths eliminated");
307STATISTIC(NumPeeps, "Number of calls peephole-optimized");
308
309namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000310 /// \enum Sequence
311 ///
312 /// \brief A sequence of states that a pointer may go through in which an
313 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000314 enum Sequence {
315 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000316 S_Retain, ///< objc_retain(x).
317 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
318 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000319 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000320 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000321 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000322 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000323
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
325 LLVM_ATTRIBUTE_UNUSED;
326 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
327 switch (S) {
328 case S_None:
329 return OS << "S_None";
330 case S_Retain:
331 return OS << "S_Retain";
332 case S_CanRelease:
333 return OS << "S_CanRelease";
334 case S_Use:
335 return OS << "S_Use";
336 case S_Release:
337 return OS << "S_Release";
338 case S_MovableRelease:
339 return OS << "S_MovableRelease";
340 case S_Stop:
341 return OS << "S_Stop";
342 }
343 llvm_unreachable("Unknown sequence type.");
344 }
John McCalld935e9c2011-06-15 23:37:01 +0000345}
346
347static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
348 // The easy cases.
349 if (A == B)
350 return A;
351 if (A == S_None || B == S_None)
352 return S_None;
353
John McCalld935e9c2011-06-15 23:37:01 +0000354 if (A > B) std::swap(A, B);
355 if (TopDown) {
356 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000357 if ((A == S_Retain || A == S_CanRelease) &&
358 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000359 return B;
360 } else {
361 // Choose the side which is further along in the sequence.
362 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000363 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000364 return A;
365 // If both sides are releases, choose the more conservative one.
366 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
367 return A;
368 if (A == S_Release && B == S_MovableRelease)
369 return A;
370 }
371
372 return S_None;
373}
374
375namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000376 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000377 /// retain-decrement-use-release sequence or release-use-decrement-retain
378 /// reverese sequence.
379 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000380 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000381 /// object is known to be positive. Similarly, before an objc_release, the
382 /// reference count of the referenced object is known to be positive. If
383 /// there are retain-release pairs in code regions where the retain count
384 /// is known to be positive, they can be eliminated, regardless of any side
385 /// effects between them.
386 ///
387 /// Also, a retain+release pair nested within another retain+release
388 /// pair all on the known same pointer value can be eliminated, regardless
389 /// of any intervening side effects.
390 ///
391 /// KnownSafe is true when either of these conditions is satisfied.
392 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000393
Michael Gottesman97e3df02013-01-14 00:35:14 +0000394 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000395 bool IsTailCallRelease;
396
Michael Gottesman97e3df02013-01-14 00:35:14 +0000397 /// If the Calls are objc_release calls and they all have a
398 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000399 MDNode *ReleaseMetadata;
400
Michael Gottesman97e3df02013-01-14 00:35:14 +0000401 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000402 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
403 SmallPtrSet<Instruction *, 2> Calls;
404
Michael Gottesman97e3df02013-01-14 00:35:14 +0000405 /// The set of optimal insert positions for moving calls in the opposite
406 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000407 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
408
409 RRInfo() :
Michael Gottesmanba648592013-03-28 23:08:44 +0000410 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000411
412 void clear();
413 };
414}
415
416void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000417 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000418 IsTailCallRelease = false;
419 ReleaseMetadata = 0;
420 Calls.clear();
421 ReverseInsertPts.clear();
422}
423
424namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// \brief This class summarizes several per-pointer runtime properties which
426 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000427 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000428 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000429 bool KnownPositiveRefCount;
430
Michael Gottesman97e3df02013-01-14 00:35:14 +0000431 /// True of we've seen an opportunity for partial RR elimination, such as
432 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000433 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000434
Michael Gottesman97e3df02013-01-14 00:35:14 +0000435 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000436 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000437
438 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000439 /// Unidirectional information about the current sequence.
440 ///
John McCalld935e9c2011-06-15 23:37:01 +0000441 /// TODO: Encapsulate this better.
442 RRInfo RRI;
443
Dan Gohmandf476e52012-09-04 23:16:20 +0000444 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000445 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000446
Michael Gottesman415ddd72013-02-05 19:32:18 +0000447 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000448 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000449 }
450
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000451 void ClearKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000452 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000453 }
454
Michael Gottesman07beea42013-03-23 05:31:01 +0000455 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000456 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000457 }
458
Michael Gottesman415ddd72013-02-05 19:32:18 +0000459 void SetSeq(Sequence NewSeq) {
John McCalld935e9c2011-06-15 23:37:01 +0000460 Seq = NewSeq;
461 }
462
Michael Gottesman415ddd72013-02-05 19:32:18 +0000463 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000464 return Seq;
465 }
466
Michael Gottesman415ddd72013-02-05 19:32:18 +0000467 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000468 ResetSequenceProgress(S_None);
469 }
470
Michael Gottesman415ddd72013-02-05 19:32:18 +0000471 void ResetSequenceProgress(Sequence NewSeq) {
Dan Gohman62079b42012-04-25 00:50:46 +0000472 Seq = NewSeq;
473 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000474 RRI.clear();
475 }
476
477 void Merge(const PtrState &Other, bool TopDown);
478 };
479}
480
481void
482PtrState::Merge(const PtrState &Other, bool TopDown) {
483 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000484 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000485
Dan Gohman1736c142011-10-17 18:48:25 +0000486 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000487 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000488 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000489 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000490 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000491 // If we're doing a merge on a path that's previously seen a partial
492 // merge, conservatively drop the sequence, to avoid doing partial
493 // RR elimination. If the branch predicates for the two merge differ,
494 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000495 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000496 } else {
497 // Conservatively merge the ReleaseMetadata information.
498 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
499 RRI.ReleaseMetadata = 0;
500
Dan Gohmanb3894012011-08-19 00:26:36 +0000501 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000502 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
503 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000504 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000505
506 // Merge the insert point sets. If there are any differences,
507 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000508 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000509 for (SmallPtrSet<Instruction *, 2>::const_iterator
510 I = Other.RRI.ReverseInsertPts.begin(),
511 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000512 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000513 }
514}
515
516namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000517 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000518 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000519 /// The number of unique control paths from the entry which can reach this
520 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000521 unsigned TopDownPathCount;
522
Michael Gottesman97e3df02013-01-14 00:35:14 +0000523 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000524 unsigned BottomUpPathCount;
525
Michael Gottesman97e3df02013-01-14 00:35:14 +0000526 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000527 typedef MapVector<const Value *, PtrState> MapTy;
528
Michael Gottesman97e3df02013-01-14 00:35:14 +0000529 /// The top-down traversal uses this to record information known about a
530 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000531 MapTy PerPtrTopDown;
532
Michael Gottesman97e3df02013-01-14 00:35:14 +0000533 /// The bottom-up traversal uses this to record information known about a
534 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000535 MapTy PerPtrBottomUp;
536
Michael Gottesman97e3df02013-01-14 00:35:14 +0000537 /// Effective predecessors of the current block ignoring ignorable edges and
538 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000539 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540 /// Effective successors of the current block ignoring ignorable edges and
541 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000542 SmallVector<BasicBlock *, 2> Succs;
543
John McCalld935e9c2011-06-15 23:37:01 +0000544 public:
545 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
546
547 typedef MapTy::iterator ptr_iterator;
548 typedef MapTy::const_iterator ptr_const_iterator;
549
550 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
551 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
552 ptr_const_iterator top_down_ptr_begin() const {
553 return PerPtrTopDown.begin();
554 }
555 ptr_const_iterator top_down_ptr_end() const {
556 return PerPtrTopDown.end();
557 }
558
559 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
560 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
561 ptr_const_iterator bottom_up_ptr_begin() const {
562 return PerPtrBottomUp.begin();
563 }
564 ptr_const_iterator bottom_up_ptr_end() const {
565 return PerPtrBottomUp.end();
566 }
567
Michael Gottesman97e3df02013-01-14 00:35:14 +0000568 /// Mark this block as being an entry block, which has one path from the
569 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000570 void SetAsEntry() { TopDownPathCount = 1; }
571
Michael Gottesman97e3df02013-01-14 00:35:14 +0000572 /// Mark this block as being an exit block, which has one path to an exit by
573 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000574 void SetAsExit() { BottomUpPathCount = 1; }
575
576 PtrState &getPtrTopDownState(const Value *Arg) {
577 return PerPtrTopDown[Arg];
578 }
579
580 PtrState &getPtrBottomUpState(const Value *Arg) {
581 return PerPtrBottomUp[Arg];
582 }
583
584 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000585 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000586 }
587
588 void clearTopDownPointers() {
589 PerPtrTopDown.clear();
590 }
591
592 void InitFromPred(const BBState &Other);
593 void InitFromSucc(const BBState &Other);
594 void MergePred(const BBState &Other);
595 void MergeSucc(const BBState &Other);
596
Michael Gottesman97e3df02013-01-14 00:35:14 +0000597 /// Return the number of possible unique paths from an entry to an exit
598 /// which pass through this block. This is only valid after both the
599 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000600 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000601 assert(TopDownPathCount != 0);
602 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000603 return TopDownPathCount * BottomUpPathCount;
604 }
Dan Gohman12130272011-08-12 00:26:31 +0000605
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000606 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000607 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000608 edge_iterator pred_begin() { return Preds.begin(); }
609 edge_iterator pred_end() { return Preds.end(); }
610 edge_iterator succ_begin() { return Succs.begin(); }
611 edge_iterator succ_end() { return Succs.end(); }
612
613 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
614 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
615
616 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000617 };
618}
619
620void BBState::InitFromPred(const BBState &Other) {
621 PerPtrTopDown = Other.PerPtrTopDown;
622 TopDownPathCount = Other.TopDownPathCount;
623}
624
625void BBState::InitFromSucc(const BBState &Other) {
626 PerPtrBottomUp = Other.PerPtrBottomUp;
627 BottomUpPathCount = Other.BottomUpPathCount;
628}
629
Michael Gottesman97e3df02013-01-14 00:35:14 +0000630/// The top-down traversal uses this to merge information about predecessors to
631/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000632void BBState::MergePred(const BBState &Other) {
633 // Other.TopDownPathCount can be 0, in which case it is either dead or a
634 // loop backedge. Loop backedges are special.
635 TopDownPathCount += Other.TopDownPathCount;
636
Michael Gottesman4385edf2013-01-14 01:47:53 +0000637 // Check for overflow. If we have overflow, fall back to conservative
638 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000639 if (TopDownPathCount < Other.TopDownPathCount) {
640 clearTopDownPointers();
641 return;
642 }
643
John McCalld935e9c2011-06-15 23:37:01 +0000644 // For each entry in the other set, if our set has an entry with the same key,
645 // merge the entries. Otherwise, copy the entry and merge it with an empty
646 // entry.
647 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
648 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
649 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
650 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
651 /*TopDown=*/true);
652 }
653
Dan Gohman7e315fc32011-08-11 21:06:32 +0000654 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000655 // same key, force it to merge with an empty entry.
656 for (ptr_iterator MI = top_down_ptr_begin(),
657 ME = top_down_ptr_end(); MI != ME; ++MI)
658 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
659 MI->second.Merge(PtrState(), /*TopDown=*/true);
660}
661
Michael Gottesman97e3df02013-01-14 00:35:14 +0000662/// The bottom-up traversal uses this to merge information about successors to
663/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000664void BBState::MergeSucc(const BBState &Other) {
665 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
666 // loop backedge. Loop backedges are special.
667 BottomUpPathCount += Other.BottomUpPathCount;
668
Michael Gottesman4385edf2013-01-14 01:47:53 +0000669 // Check for overflow. If we have overflow, fall back to conservative
670 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000671 if (BottomUpPathCount < Other.BottomUpPathCount) {
672 clearBottomUpPointers();
673 return;
674 }
675
John McCalld935e9c2011-06-15 23:37:01 +0000676 // For each entry in the other set, if our set has an entry with the
677 // same key, merge the entries. Otherwise, copy the entry and merge
678 // it with an empty entry.
679 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
680 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
681 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
682 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
683 /*TopDown=*/false);
684 }
685
Dan Gohman7e315fc32011-08-11 21:06:32 +0000686 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000687 // with the same key, force it to merge with an empty entry.
688 for (ptr_iterator MI = bottom_up_ptr_begin(),
689 ME = bottom_up_ptr_end(); MI != ME; ++MI)
690 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
691 MI->second.Merge(PtrState(), /*TopDown=*/false);
692}
693
Michael Gottesman81b1d432013-03-26 00:42:04 +0000694// Only enable ARC Annotations if we are building a debug version of
695// libObjCARCOpts.
696#ifndef NDEBUG
697#define ARC_ANNOTATIONS
698#endif
699
700// Define some macros along the lines of DEBUG and some helper functions to make
701// it cleaner to create annotations in the source code and to no-op when not
702// building in debug mode.
703#ifdef ARC_ANNOTATIONS
704
705#include "llvm/Support/CommandLine.h"
706
707/// Enable/disable ARC sequence annotations.
708static cl::opt<bool>
709EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false));
710
711/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
712/// instruction so that we can track backwards when post processing via the llvm
713/// arc annotation processor tool. If the function is an
714static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
715 Value *Ptr) {
716 MDString *Hash = 0;
717
718 // If pointer is a result of an instruction and it does not have a source
719 // MDNode it, attach a new MDNode onto it. If pointer is a result of
720 // an instruction and does have a source MDNode attached to it, return a
721 // reference to said Node. Otherwise just return 0.
722 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
723 MDNode *Node;
724 if (!(Node = Inst->getMetadata(NodeId))) {
725 // We do not have any node. Generate and attatch the hash MDString to the
726 // instruction.
727
728 // We just use an MDString to ensure that this metadata gets written out
729 // of line at the module level and to provide a very simple format
730 // encoding the information herein. Both of these makes it simpler to
731 // parse the annotations by a simple external program.
732 std::string Str;
733 raw_string_ostream os(Str);
734 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
735 << Inst->getName() << ")";
736
737 Hash = MDString::get(Inst->getContext(), os.str());
738 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
739 } else {
740 // We have a node. Grab its hash and return it.
741 assert(Node->getNumOperands() == 1 &&
742 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
743 Hash = cast<MDString>(Node->getOperand(0));
744 }
745 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
746 std::string str;
747 raw_string_ostream os(str);
748 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
749 << ")";
750 Hash = MDString::get(Arg->getContext(), os.str());
751 }
752
753 return Hash;
754}
755
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000756static std::string SequenceToString(Sequence A) {
757 std::string str;
758 raw_string_ostream os(str);
759 os << A;
760 return os.str();
761}
762
Michael Gottesman81b1d432013-03-26 00:42:04 +0000763/// Helper function to change a Sequence into a String object using our overload
764/// for raw_ostream so we only have printing code in one location.
765static MDString *SequenceToMDString(LLVMContext &Context,
766 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000767 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000768}
769
770/// A simple function to generate a MDNode which describes the change in state
771/// for Value *Ptr caused by Instruction *Inst.
772static void AppendMDNodeToInstForPtr(unsigned NodeId,
773 Instruction *Inst,
774 Value *Ptr,
775 MDString *PtrSourceMDNodeID,
776 Sequence OldSeq,
777 Sequence NewSeq) {
778 MDNode *Node = 0;
779 Value *tmp[3] = {PtrSourceMDNodeID,
780 SequenceToMDString(Inst->getContext(),
781 OldSeq),
782 SequenceToMDString(Inst->getContext(),
783 NewSeq)};
784 Node = MDNode::get(Inst->getContext(),
785 ArrayRef<Value*>(tmp, 3));
786
787 Inst->setMetadata(NodeId, Node);
788}
789
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000790/// Add to the beginning of the basic block llvm.ptr.annotations which show the
791/// state of a pointer at the entrance to a basic block.
792static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
793 Value *Ptr, Sequence Seq) {
794 Module *M = BB->getParent()->getParent();
795 LLVMContext &C = M->getContext();
796 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
797 Type *I8XX = PointerType::getUnqual(I8X);
798 Type *Params[] = {I8XX, I8XX};
799 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
800 ArrayRef<Type*>(Params, 2),
801 /*isVarArg=*/false);
802 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000803
804 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
805
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000806 Value *PtrName;
807 StringRef Tmp = Ptr->getName();
808 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
809 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
810 Tmp + "_STR");
811 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000812 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000813 }
814
815 Value *S;
816 std::string SeqStr = SequenceToString(Seq);
817 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
818 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
819 SeqStr + "_STR");
820 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
821 cast<Constant>(ActualPtrName), SeqStr);
822 }
823
824 Builder.CreateCall2(Callee, PtrName, S);
825}
826
827/// Add to the end of the basic block llvm.ptr.annotations which show the state
828/// of the pointer at the bottom of the basic block.
829static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
830 Value *Ptr, Sequence Seq) {
831 Module *M = BB->getParent()->getParent();
832 LLVMContext &C = M->getContext();
833 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
834 Type *I8XX = PointerType::getUnqual(I8X);
835 Type *Params[] = {I8XX, I8XX};
836 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
837 ArrayRef<Type*>(Params, 2),
838 /*isVarArg=*/false);
839 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000840
841 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
842
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000843 Value *PtrName;
844 StringRef Tmp = Ptr->getName();
845 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
846 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
847 Tmp + "_STR");
848 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000849 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000850 }
851
852 Value *S;
853 std::string SeqStr = SequenceToString(Seq);
854 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
855 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
856 SeqStr + "_STR");
857 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
858 cast<Constant>(ActualPtrName), SeqStr);
859 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000860 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000861}
862
Michael Gottesman81b1d432013-03-26 00:42:04 +0000863/// Adds a source annotation to pointer and a state change annotation to Inst
864/// referencing the source annotation and the old/new state of pointer.
865static void GenerateARCAnnotation(unsigned InstMDId,
866 unsigned PtrMDId,
867 Instruction *Inst,
868 Value *Ptr,
869 Sequence OldSeq,
870 Sequence NewSeq) {
871 if (EnableARCAnnotations) {
872 // First generate the source annotation on our pointer. This will return an
873 // MDString* if Ptr actually comes from an instruction implying we can put
874 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
875 // then we know that our pointer is from an Argument so we put a reference
876 // to the argument number.
877 //
878 // The point of this is to make it easy for the
879 // llvm-arc-annotation-processor tool to cross reference where the source
880 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
881 // information via debug info for backends to use (since why would anyone
882 // need such a thing from LLVM IR besides in non standard cases
883 // [i.e. this]).
884 MDString *SourcePtrMDNode =
885 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
886 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
887 NewSeq);
888 }
889}
890
891// The actual interface for accessing the above functionality is defined via
892// some simple macros which are defined below. We do this so that the user does
893// not need to pass in what metadata id is needed resulting in cleaner code and
894// additionally since it provides an easy way to conditionally no-op all
895// annotation support in a non-debug build.
896
897/// Use this macro to annotate a sequence state change when processing
898/// instructions bottom up,
899#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
900 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
901 ARCAnnotationProvenanceSourceMDKind, (inst), \
902 const_cast<Value*>(ptr), (old), (new))
903/// Use this macro to annotate a sequence state change when processing
904/// instructions top down.
905#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
906 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
907 ARCAnnotationProvenanceSourceMDKind, (inst), \
908 const_cast<Value*>(ptr), (old), (new))
909
Michael Gottesman43e7e002013-04-03 22:41:59 +0000910#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
911 do { \
912 if (EnableARCAnnotations) { \
913 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
914 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
915 Value *Ptr = const_cast<Value*>(I->first); \
916 Sequence Seq = I->second.GetSeq(); \
917 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
918 } \
919 } \
920} while (0)
921
922#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
923 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
924 Entrance, bottom_up)
925#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
926 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
927 Terminator, bottom_up)
928#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
929 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
930 Entrance, top_down)
931#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
932 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
933 Terminator, top_down)
934
Michael Gottesman81b1d432013-03-26 00:42:04 +0000935#else // !ARC_ANNOTATION
936// If annotations are off, noop.
937#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
938#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000939#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
940#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
941#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
942#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000943#endif // !ARC_ANNOTATION
944
John McCalld935e9c2011-06-15 23:37:01 +0000945namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000946 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000947 class ObjCARCOpt : public FunctionPass {
948 bool Changed;
949 ProvenanceAnalysis PA;
950
Michael Gottesman97e3df02013-01-14 00:35:14 +0000951 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000952 bool Run;
953
Michael Gottesman97e3df02013-01-14 00:35:14 +0000954 /// Declarations for ObjC runtime functions, for use in creating calls to
955 /// them. These are initialized lazily to avoid cluttering up the Module
956 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000957
Michael Gottesman97e3df02013-01-14 00:35:14 +0000958 /// Declaration for ObjC runtime function
959 /// objc_retainAutoreleasedReturnValue.
960 Constant *RetainRVCallee;
961 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
962 Constant *AutoreleaseRVCallee;
963 /// Declaration for ObjC runtime function objc_release.
964 Constant *ReleaseCallee;
965 /// Declaration for ObjC runtime function objc_retain.
966 Constant *RetainCallee;
967 /// Declaration for ObjC runtime function objc_retainBlock.
968 Constant *RetainBlockCallee;
969 /// Declaration for ObjC runtime function objc_autorelease.
970 Constant *AutoreleaseCallee;
971
972 /// Flags which determine whether each of the interesting runtine functions
973 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000974 unsigned UsedInThisFunction;
975
Michael Gottesman97e3df02013-01-14 00:35:14 +0000976 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000977 unsigned ImpreciseReleaseMDKind;
978
Michael Gottesman97e3df02013-01-14 00:35:14 +0000979 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000980 unsigned CopyOnEscapeMDKind;
981
Michael Gottesman97e3df02013-01-14 00:35:14 +0000982 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000983 unsigned NoObjCARCExceptionsMDKind;
984
Michael Gottesman81b1d432013-03-26 00:42:04 +0000985#ifdef ARC_ANNOTATIONS
986 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
987 unsigned ARCAnnotationBottomUpMDKind;
988 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
989 unsigned ARCAnnotationTopDownMDKind;
990 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
991 unsigned ARCAnnotationProvenanceSourceMDKind;
992#endif // ARC_ANNOATIONS
993
John McCalld935e9c2011-06-15 23:37:01 +0000994 Constant *getRetainRVCallee(Module *M);
995 Constant *getAutoreleaseRVCallee(Module *M);
996 Constant *getReleaseCallee(Module *M);
997 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +0000998 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000999 Constant *getAutoreleaseCallee(Module *M);
1000
Dan Gohman728db492012-01-13 00:39:07 +00001001 bool IsRetainBlockOptimizable(const Instruction *Inst);
1002
John McCalld935e9c2011-06-15 23:37:01 +00001003 void OptimizeRetainCall(Function &F, Instruction *Retain);
1004 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001005 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1006 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001007 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1008 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001009 void OptimizeIndividualCalls(Function &F);
1010
1011 void CheckForCFGHazards(const BasicBlock *BB,
1012 DenseMap<const BasicBlock *, BBState> &BBStates,
1013 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001014 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001015 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001016 MapVector<Value *, RRInfo> &Retains,
1017 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001018 bool VisitBottomUp(BasicBlock *BB,
1019 DenseMap<const BasicBlock *, BBState> &BBStates,
1020 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001021 bool VisitInstructionTopDown(Instruction *Inst,
1022 DenseMap<Value *, RRInfo> &Releases,
1023 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001024 bool VisitTopDown(BasicBlock *BB,
1025 DenseMap<const BasicBlock *, BBState> &BBStates,
1026 DenseMap<Value *, RRInfo> &Releases);
1027 bool Visit(Function &F,
1028 DenseMap<const BasicBlock *, BBState> &BBStates,
1029 MapVector<Value *, RRInfo> &Retains,
1030 DenseMap<Value *, RRInfo> &Releases);
1031
1032 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1033 MapVector<Value *, RRInfo> &Retains,
1034 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001035 SmallVectorImpl<Instruction *> &DeadInsts,
1036 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001037
Michael Gottesman9de6f962013-01-22 21:49:00 +00001038 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1039 MapVector<Value *, RRInfo> &Retains,
1040 DenseMap<Value *, RRInfo> &Releases,
1041 Module *M,
1042 SmallVector<Instruction *, 4> &NewRetains,
1043 SmallVector<Instruction *, 4> &NewReleases,
1044 SmallVector<Instruction *, 8> &DeadInsts,
1045 RRInfo &RetainsToMove,
1046 RRInfo &ReleasesToMove,
1047 Value *Arg,
1048 bool KnownSafe,
1049 bool &AnyPairsCompletelyEliminated);
1050
John McCalld935e9c2011-06-15 23:37:01 +00001051 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1052 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001053 DenseMap<Value *, RRInfo> &Releases,
1054 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001055
1056 void OptimizeWeakCalls(Function &F);
1057
1058 bool OptimizeSequences(Function &F);
1059
1060 void OptimizeReturns(Function &F);
1061
1062 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1063 virtual bool doInitialization(Module &M);
1064 virtual bool runOnFunction(Function &F);
1065 virtual void releaseMemory();
1066
1067 public:
1068 static char ID;
1069 ObjCARCOpt() : FunctionPass(ID) {
1070 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1071 }
1072 };
1073}
1074
1075char ObjCARCOpt::ID = 0;
1076INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1077 "objc-arc", "ObjC ARC optimization", false, false)
1078INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1079INITIALIZE_PASS_END(ObjCARCOpt,
1080 "objc-arc", "ObjC ARC optimization", false, false)
1081
1082Pass *llvm::createObjCARCOptPass() {
1083 return new ObjCARCOpt();
1084}
1085
1086void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1087 AU.addRequired<ObjCARCAliasAnalysis>();
1088 AU.addRequired<AliasAnalysis>();
1089 // ARC optimization doesn't currently split critical edges.
1090 AU.setPreservesCFG();
1091}
1092
Dan Gohman728db492012-01-13 00:39:07 +00001093bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1094 // Without the magic metadata tag, we have to assume this might be an
1095 // objc_retainBlock call inserted to convert a block pointer to an id,
1096 // in which case it really is needed.
1097 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1098 return false;
1099
1100 // If the pointer "escapes" (not including being used in a call),
1101 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001102 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001103 return false;
1104
1105 // Otherwise, it's not needed.
1106 return true;
1107}
1108
John McCalld935e9c2011-06-15 23:37:01 +00001109Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1110 if (!RetainRVCallee) {
1111 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001112 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001113 Type *Params[] = { I8X };
1114 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001115 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001116 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1117 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001118 RetainRVCallee =
1119 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001120 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001121 }
1122 return RetainRVCallee;
1123}
1124
1125Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1126 if (!AutoreleaseRVCallee) {
1127 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001128 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001129 Type *Params[] = { I8X };
1130 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001131 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001132 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1133 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001134 AutoreleaseRVCallee =
1135 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001136 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001137 }
1138 return AutoreleaseRVCallee;
1139}
1140
1141Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1142 if (!ReleaseCallee) {
1143 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001144 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001145 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001146 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1147 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001148 ReleaseCallee =
1149 M->getOrInsertFunction(
1150 "objc_release",
1151 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001152 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001153 }
1154 return ReleaseCallee;
1155}
1156
1157Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1158 if (!RetainCallee) {
1159 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001160 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001161 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001162 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1163 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001164 RetainCallee =
1165 M->getOrInsertFunction(
1166 "objc_retain",
1167 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001168 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001169 }
1170 return RetainCallee;
1171}
1172
Dan Gohman6320f522011-07-22 22:29:21 +00001173Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1174 if (!RetainBlockCallee) {
1175 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001176 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001177 // objc_retainBlock is not nounwind because it calls user copy constructors
1178 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001179 RetainBlockCallee =
1180 M->getOrInsertFunction(
1181 "objc_retainBlock",
1182 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001183 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001184 }
1185 return RetainBlockCallee;
1186}
1187
John McCalld935e9c2011-06-15 23:37:01 +00001188Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1189 if (!AutoreleaseCallee) {
1190 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001191 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001192 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001193 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1194 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001195 AutoreleaseCallee =
1196 M->getOrInsertFunction(
1197 "objc_autorelease",
1198 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001199 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001200 }
1201 return AutoreleaseCallee;
1202}
1203
Michael Gottesman97e3df02013-01-14 00:35:14 +00001204/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1205/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001206void
1207ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001208 ImmutableCallSite CS(GetObjCArg(Retain));
1209 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001210 if (!Call) return;
1211 if (Call->getParent() != Retain->getParent()) return;
1212
1213 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001214 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001215 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001216 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001217 if (&*I != Retain)
1218 return;
1219
1220 // Turn it to an objc_retainAutoreleasedReturnValue..
1221 Changed = true;
1222 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001223
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001224 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00001225 "objc_retain => objc_retainAutoreleasedReturnValue"
1226 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001227 " Old: "
1228 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001229
John McCalld935e9c2011-06-15 23:37:01 +00001230 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001231
1232 DEBUG(dbgs() << " New: "
1233 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001234}
1235
Michael Gottesman97e3df02013-01-14 00:35:14 +00001236/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1237/// not a return value. Or, if it can be paired with an
1238/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001239bool
1240ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001241 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001242 const Value *Arg = GetObjCArg(RetainRV);
1243 ImmutableCallSite CS(Arg);
1244 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001245 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001246 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001247 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001248 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001249 if (&*I == RetainRV)
1250 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001251 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001252 BasicBlock *RetainRVParent = RetainRV->getParent();
1253 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001254 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001255 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001256 if (&*I == RetainRV)
1257 return false;
1258 }
John McCalld935e9c2011-06-15 23:37:01 +00001259 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001260 }
John McCalld935e9c2011-06-15 23:37:01 +00001261
1262 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1263 // pointer. In this case, we can delete the pair.
1264 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1265 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001266 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001267 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1268 GetObjCArg(I) == Arg) {
1269 Changed = true;
1270 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001271
Michael Gottesman5c32ce92013-01-05 17:55:35 +00001272 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1273 << " Erasing " << *RetainRV
1274 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001275
John McCalld935e9c2011-06-15 23:37:01 +00001276 EraseInstruction(I);
1277 EraseInstruction(RetainRV);
1278 return true;
1279 }
1280 }
1281
1282 // Turn it to a plain objc_retain.
1283 Changed = true;
1284 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001285
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001286 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1287 "objc_retainAutoreleasedReturnValue => "
1288 "objc_retain since the operand is not a return value.\n"
1289 " Old: "
1290 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001291
John McCalld935e9c2011-06-15 23:37:01 +00001292 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001293
1294 DEBUG(dbgs() << " New: "
1295 << *RetainRV << "\n");
1296
John McCalld935e9c2011-06-15 23:37:01 +00001297 return false;
1298}
1299
Michael Gottesman97e3df02013-01-14 00:35:14 +00001300/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1301/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001302void
Michael Gottesman556ff612013-01-12 01:25:19 +00001303ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1304 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001305 // Check for a return of the pointer value.
1306 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001307 SmallVector<const Value *, 2> Users;
1308 Users.push_back(Ptr);
1309 do {
1310 Ptr = Users.pop_back_val();
1311 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1312 UI != UE; ++UI) {
1313 const User *I = *UI;
1314 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1315 return;
1316 if (isa<BitCastInst>(I))
1317 Users.push_back(I);
1318 }
1319 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001320
1321 Changed = true;
1322 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001323
1324 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1325 "objc_autoreleaseReturnValue => "
1326 "objc_autorelease since its operand is not used as a return "
1327 "value.\n"
1328 " Old: "
1329 << *AutoreleaseRV << "\n");
1330
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001331 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1332 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001333 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001334 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001335 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001336
Michael Gottesman1bf69082013-01-06 21:07:11 +00001337 DEBUG(dbgs() << " New: "
1338 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001339
John McCalld935e9c2011-06-15 23:37:01 +00001340}
1341
Michael Gottesman158fdf62013-03-28 20:11:19 +00001342// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1343// calls.
1344//
1345// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1346// does not escape (following the rules of block escaping), strength reduce the
1347// objc_retainBlock to an objc_retain.
1348//
1349// TODO: If an objc_retainBlock call is dominated period by a previous
1350// objc_retainBlock call, strength reduce the objc_retainBlock to an
1351// objc_retain.
1352bool
1353ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1354 InstructionClass &Class) {
1355 assert(GetBasicInstructionClass(Inst) == Class);
1356 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001357
Michael Gottesman158fdf62013-03-28 20:11:19 +00001358 // If we can not optimize Inst, return false.
1359 if (!IsRetainBlockOptimizable(Inst))
1360 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001361
Michael Gottesman158fdf62013-03-28 20:11:19 +00001362 CallInst *RetainBlock = cast<CallInst>(Inst);
1363 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1364 // Remove copy_on_escape metadata.
1365 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1366 Class = IC_Retain;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001367
Michael Gottesman158fdf62013-03-28 20:11:19 +00001368 return true;
1369}
1370
Michael Gottesman97e3df02013-01-14 00:35:14 +00001371/// Visit each call, one at a time, and make simplifications without doing any
1372/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001373void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1374 // Reset all the flags in preparation for recomputing them.
1375 UsedInThisFunction = 0;
1376
1377 // Visit all objc_* calls in F.
1378 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1379 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001380
John McCalld935e9c2011-06-15 23:37:01 +00001381 InstructionClass Class = GetBasicInstructionClass(Inst);
1382
Michael Gottesmand359e062013-01-18 03:08:39 +00001383 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1384 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001385
John McCalld935e9c2011-06-15 23:37:01 +00001386 switch (Class) {
1387 default: break;
1388
1389 // Delete no-op casts. These function calls have special semantics, but
1390 // the semantics are entirely implemented via lowering in the front-end,
1391 // so by the time they reach the optimizer, they are just no-op calls
1392 // which return their argument.
1393 //
1394 // There are gray areas here, as the ability to cast reference-counted
1395 // pointers to raw void* and back allows code to break ARC assumptions,
1396 // however these are currently considered to be unimportant.
1397 case IC_NoopCast:
1398 Changed = true;
1399 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00001400 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1401 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001402 EraseInstruction(Inst);
1403 continue;
1404
1405 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1406 case IC_StoreWeak:
1407 case IC_LoadWeak:
1408 case IC_LoadWeakRetained:
1409 case IC_InitWeak:
1410 case IC_DestroyWeak: {
1411 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001412 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001413 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001414 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001415 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1416 Constant::getNullValue(Ty),
1417 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001418 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001419 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1420 "pointer-to-weak-pointer is undefined behavior.\n"
1421 " Old = " << *CI <<
1422 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00001423 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001424 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001425 CI->eraseFromParent();
1426 continue;
1427 }
1428 break;
1429 }
1430 case IC_CopyWeak:
1431 case IC_MoveWeak: {
1432 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001433 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1434 IsNullOrUndef(CI->getArgOperand(1))) {
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 Gottesmanfec61c02013-01-06 21:54:30 +00001440
1441 llvm::Value *NewValue = UndefValue::get(CI->getType());
1442 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1443 "pointer-to-weak-pointer is undefined behavior.\n"
1444 " Old = " << *CI <<
1445 "\n New = " <<
1446 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001447
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001448 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001449 CI->eraseFromParent();
1450 continue;
1451 }
1452 break;
1453 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001454 case IC_RetainBlock:
1455 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1456 // onto the objc_retain peephole optimizations. Otherwise break.
1457 if (!OptimizeRetainBlockCall(F, Inst, Class))
1458 break;
1459 // FALLTHROUGH
John McCalld935e9c2011-06-15 23:37:01 +00001460 case IC_Retain:
1461 OptimizeRetainCall(F, Inst);
1462 break;
1463 case IC_RetainRV:
1464 if (OptimizeRetainRVCall(F, Inst))
1465 continue;
1466 break;
1467 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001468 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001469 break;
1470 }
1471
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001472 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001473 if (IsAutorelease(Class) && Inst->use_empty()) {
1474 CallInst *Call = cast<CallInst>(Inst);
1475 const Value *Arg = Call->getArgOperand(0);
1476 Arg = FindSingleUseIdentifiedObject(Arg);
1477 if (Arg) {
1478 Changed = true;
1479 ++NumAutoreleases;
1480
1481 // Create the declaration lazily.
1482 LLVMContext &C = Inst->getContext();
1483 CallInst *NewCall =
1484 CallInst::Create(getReleaseCallee(F.getParent()),
1485 Call->getArgOperand(0), "", Call);
1486 NewCall->setMetadata(ImpreciseReleaseMDKind,
1487 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001488
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001489 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1490 "objc_autorelease(x) with objc_release(x) since x is "
1491 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00001492 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001493 "\n New: " <<
1494 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001495
John McCalld935e9c2011-06-15 23:37:01 +00001496 EraseInstruction(Call);
1497 Inst = NewCall;
1498 Class = IC_Release;
1499 }
1500 }
1501
1502 // For functions which can never be passed stack arguments, add
1503 // a tail keyword.
1504 if (IsAlwaysTail(Class)) {
1505 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00001506 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1507 " to function since it can never be passed stack args: " << *Inst <<
1508 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001509 cast<CallInst>(Inst)->setTailCall();
1510 }
1511
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001512 // Ensure that functions that can never have a "tail" keyword due to the
1513 // semantics of ARC truly do not do so.
1514 if (IsNeverTail(Class)) {
1515 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001516 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1517 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001518 "\n");
1519 cast<CallInst>(Inst)->setTailCall(false);
1520 }
1521
John McCalld935e9c2011-06-15 23:37:01 +00001522 // Set nounwind as needed.
1523 if (IsNoThrow(Class)) {
1524 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00001525 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1526 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001527 cast<CallInst>(Inst)->setDoesNotThrow();
1528 }
1529
1530 if (!IsNoopOnNull(Class)) {
1531 UsedInThisFunction |= 1 << Class;
1532 continue;
1533 }
1534
1535 const Value *Arg = GetObjCArg(Inst);
1536
1537 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001538 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001539 Changed = true;
1540 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00001541 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1542 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001543 EraseInstruction(Inst);
1544 continue;
1545 }
1546
1547 // Keep track of which of retain, release, autorelease, and retain_block
1548 // are actually present in this function.
1549 UsedInThisFunction |= 1 << Class;
1550
1551 // If Arg is a PHI, and one or more incoming values to the
1552 // PHI are null, and the call is control-equivalent to the PHI, and there
1553 // are no relevant side effects between the PHI and the call, the call
1554 // could be pushed up to just those paths with non-null incoming values.
1555 // For now, don't bother splitting critical edges for this.
1556 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1557 Worklist.push_back(std::make_pair(Inst, Arg));
1558 do {
1559 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1560 Inst = Pair.first;
1561 Arg = Pair.second;
1562
1563 const PHINode *PN = dyn_cast<PHINode>(Arg);
1564 if (!PN) continue;
1565
1566 // Determine if the PHI has any null operands, or any incoming
1567 // critical edges.
1568 bool HasNull = false;
1569 bool HasCriticalEdges = false;
1570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1571 Value *Incoming =
1572 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001573 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001574 HasNull = true;
1575 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1576 .getNumSuccessors() != 1) {
1577 HasCriticalEdges = true;
1578 break;
1579 }
1580 }
1581 // If we have null operands and no critical edges, optimize.
1582 if (!HasCriticalEdges && HasNull) {
1583 SmallPtrSet<Instruction *, 4> DependingInstructions;
1584 SmallPtrSet<const BasicBlock *, 4> Visited;
1585
1586 // Check that there is nothing that cares about the reference
1587 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001588 switch (Class) {
1589 case IC_Retain:
1590 case IC_RetainBlock:
1591 // These can always be moved up.
1592 break;
1593 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001594 // These can't be moved across things that care about the retain
1595 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001596 FindDependencies(NeedsPositiveRetainCount, Arg,
1597 Inst->getParent(), Inst,
1598 DependingInstructions, Visited, PA);
1599 break;
1600 case IC_Autorelease:
1601 // These can't be moved across autorelease pool scope boundaries.
1602 FindDependencies(AutoreleasePoolBoundary, Arg,
1603 Inst->getParent(), Inst,
1604 DependingInstructions, Visited, PA);
1605 break;
1606 case IC_RetainRV:
1607 case IC_AutoreleaseRV:
1608 // Don't move these; the RV optimization depends on the autoreleaseRV
1609 // being tail called, and the retainRV being immediately after a call
1610 // (which might still happen if we get lucky with codegen layout, but
1611 // it's not worth taking the chance).
1612 continue;
1613 default:
1614 llvm_unreachable("Invalid dependence flavor");
1615 }
1616
John McCalld935e9c2011-06-15 23:37:01 +00001617 if (DependingInstructions.size() == 1 &&
1618 *DependingInstructions.begin() == PN) {
1619 Changed = true;
1620 ++NumPartialNoops;
1621 // Clone the call into each predecessor that has a non-null value.
1622 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001623 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001624 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1625 Value *Incoming =
1626 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001627 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001628 CallInst *Clone = cast<CallInst>(CInst->clone());
1629 Value *Op = PN->getIncomingValue(i);
1630 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1631 if (Op->getType() != ParamTy)
1632 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1633 Clone->setArgOperand(0, Op);
1634 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001635
1636 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1637 << *CInst << "\n"
1638 " And inserting "
1639 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001640 Worklist.push_back(std::make_pair(Clone, Incoming));
1641 }
1642 }
1643 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001644 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001645 EraseInstruction(CInst);
1646 continue;
1647 }
1648 }
1649 } while (!Worklist.empty());
1650 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00001651 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00001652}
1653
Michael Gottesman97e3df02013-01-14 00:35:14 +00001654/// Check for critical edges, loop boundaries, irreducible control flow, or
1655/// other CFG structures where moving code across the edge would result in it
1656/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001657void
1658ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1659 DenseMap<const BasicBlock *, BBState> &BBStates,
1660 BBState &MyStates) const {
1661 // If any top-down local-use or possible-dec has a succ which is earlier in
1662 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001663 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001664 E = MyStates.top_down_ptr_end(); I != E; ++I)
1665 switch (I->second.GetSeq()) {
1666 default: break;
1667 case S_Use: {
1668 const Value *Arg = I->first;
1669 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1670 bool SomeSuccHasSame = false;
1671 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001672 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001673 succ_const_iterator SI(TI), SE(TI, false);
1674
Dan Gohman0155f302012-02-17 18:59:53 +00001675 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001676 Sequence SuccSSeq = S_None;
1677 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001678 // If VisitBottomUp has pointer information for this successor, take
1679 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001680 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1681 BBStates.find(*SI);
1682 assert(BBI != BBStates.end());
1683 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1684 SuccSSeq = SuccS.GetSeq();
1685 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001686 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001687 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001688 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001689 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001690 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001691 break;
1692 }
Dan Gohman12130272011-08-12 00:26:31 +00001693 continue;
1694 }
John McCalld935e9c2011-06-15 23:37:01 +00001695 case S_Use:
1696 SomeSuccHasSame = true;
1697 break;
1698 case S_Stop:
1699 case S_Release:
1700 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001701 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001702 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001703 break;
1704 case S_Retain:
1705 llvm_unreachable("bottom-up pointer in retain state!");
1706 }
Dan Gohman12130272011-08-12 00:26:31 +00001707 }
John McCalld935e9c2011-06-15 23:37:01 +00001708 // If the state at the other end of any of the successor edges
1709 // matches the current state, require all edges to match. This
1710 // guards against loops in the middle of a sequence.
1711 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001712 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001713 break;
John McCalld935e9c2011-06-15 23:37:01 +00001714 }
1715 case S_CanRelease: {
1716 const Value *Arg = I->first;
1717 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1718 bool SomeSuccHasSame = false;
1719 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001720 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001721 succ_const_iterator SI(TI), SE(TI, false);
1722
Dan Gohman0155f302012-02-17 18:59:53 +00001723 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001724 Sequence SuccSSeq = S_None;
1725 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001726 // If VisitBottomUp has pointer information for this successor, take
1727 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001728 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1729 BBStates.find(*SI);
1730 assert(BBI != BBStates.end());
1731 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1732 SuccSSeq = SuccS.GetSeq();
1733 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001734 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001735 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001736 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001737 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001738 break;
1739 }
Dan Gohman12130272011-08-12 00:26:31 +00001740 continue;
1741 }
John McCalld935e9c2011-06-15 23:37:01 +00001742 case S_CanRelease:
1743 SomeSuccHasSame = true;
1744 break;
1745 case S_Stop:
1746 case S_Release:
1747 case S_MovableRelease:
1748 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001749 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001750 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001751 break;
1752 case S_Retain:
1753 llvm_unreachable("bottom-up pointer in retain state!");
1754 }
Dan Gohman12130272011-08-12 00:26:31 +00001755 }
John McCalld935e9c2011-06-15 23:37:01 +00001756 // If the state at the other end of any of the successor edges
1757 // matches the current state, require all edges to match. This
1758 // guards against loops in the middle of a sequence.
1759 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001760 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001761 break;
John McCalld935e9c2011-06-15 23:37:01 +00001762 }
1763 }
1764}
1765
1766bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001767ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001768 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001769 MapVector<Value *, RRInfo> &Retains,
1770 BBState &MyStates) {
1771 bool NestingDetected = false;
1772 InstructionClass Class = GetInstructionClass(Inst);
1773 const Value *Arg = 0;
1774
1775 switch (Class) {
1776 case IC_Release: {
1777 Arg = GetObjCArg(Inst);
1778
1779 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1780
1781 // If we see two releases in a row on the same pointer. If so, make
1782 // a note, and we'll cicle back to revisit it after we've
1783 // hopefully eliminated the second release, which may allow us to
1784 // eliminate the first release too.
1785 // Theoretically we could implement removal of nested retain+release
1786 // pairs by making PtrState hold a stack of states, but this is
1787 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001788 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1789 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
1790 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001791 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001792 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001793
Dan Gohman817a7c62012-03-22 18:24:56 +00001794 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001795 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1796 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1797 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001798 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001799 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001800 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1801 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001802 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001803 break;
1804 }
1805 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001806 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1807 // objc_retainBlocks to objc_retains. Thus at this point any
1808 // objc_retainBlocks that we see are not optimizable.
1809 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001810 case IC_Retain:
1811 case IC_RetainRV: {
1812 Arg = GetObjCArg(Inst);
1813
1814 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001815 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001816
Michael Gottesman81b1d432013-03-26 00:42:04 +00001817 Sequence OldSeq = S.GetSeq();
1818 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001819 case S_Stop:
1820 case S_Release:
1821 case S_MovableRelease:
1822 case S_Use:
1823 S.RRI.ReverseInsertPts.clear();
1824 // FALL THROUGH
1825 case S_CanRelease:
1826 // Don't do retain+release tracking for IC_RetainRV, because it's
1827 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001828 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001829 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001830 S.ClearSequenceProgress();
1831 break;
1832 case S_None:
1833 break;
1834 case S_Retain:
1835 llvm_unreachable("bottom-up pointer in retain state!");
1836 }
Michael Gottesman81b1d432013-03-26 00:42:04 +00001837 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001838 return NestingDetected;
1839 }
1840 case IC_AutoreleasepoolPop:
1841 // Conservatively, clear MyStates for all known pointers.
1842 MyStates.clearBottomUpPointers();
1843 return NestingDetected;
1844 case IC_AutoreleasepoolPush:
1845 case IC_None:
1846 // These are irrelevant.
1847 return NestingDetected;
1848 default:
1849 break;
1850 }
1851
1852 // Consider any other possible effects of this instruction on each
1853 // pointer being tracked.
1854 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1855 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1856 const Value *Ptr = MI->first;
1857 if (Ptr == Arg)
1858 continue; // Handled above.
1859 PtrState &S = MI->second;
1860 Sequence Seq = S.GetSeq();
1861
1862 // Check for possible releases.
1863 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001864 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001865 switch (Seq) {
1866 case S_Use:
1867 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001868 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001869 continue;
1870 case S_CanRelease:
1871 case S_Release:
1872 case S_MovableRelease:
1873 case S_Stop:
1874 case S_None:
1875 break;
1876 case S_Retain:
1877 llvm_unreachable("bottom-up pointer in retain state!");
1878 }
1879 }
1880
1881 // Check for possible direct uses.
1882 switch (Seq) {
1883 case S_Release:
1884 case S_MovableRelease:
1885 if (CanUse(Inst, Ptr, PA, Class)) {
1886 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001887 // If this is an invoke instruction, we're scanning it as part of
1888 // one of its successor blocks, since we can't insert code after it
1889 // in its own block, and we don't want to split critical edges.
1890 if (isa<InvokeInst>(Inst))
1891 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1892 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001893 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001894 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001895 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001896 } else if (Seq == S_Release && IsUser(Class)) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001897 // Non-movable releases depend on any possible objc pointer use.
1898 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001899 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001900 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001901 // As above; handle invoke specially.
1902 if (isa<InvokeInst>(Inst))
1903 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1904 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001905 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001906 }
1907 break;
1908 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001909 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001910 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001911 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1912 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001913 break;
1914 case S_CanRelease:
1915 case S_Use:
1916 case S_None:
1917 break;
1918 case S_Retain:
1919 llvm_unreachable("bottom-up pointer in retain state!");
1920 }
1921 }
1922
1923 return NestingDetected;
1924}
1925
1926bool
John McCalld935e9c2011-06-15 23:37:01 +00001927ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1928 DenseMap<const BasicBlock *, BBState> &BBStates,
1929 MapVector<Value *, RRInfo> &Retains) {
1930 bool NestingDetected = false;
1931 BBState &MyStates = BBStates[BB];
1932
1933 // Merge the states from each successor to compute the initial state
1934 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001935 BBState::edge_iterator SI(MyStates.succ_begin()),
1936 SE(MyStates.succ_end());
1937 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001938 const BasicBlock *Succ = *SI;
1939 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1940 assert(I != BBStates.end());
1941 MyStates.InitFromSucc(I->second);
1942 ++SI;
1943 for (; SI != SE; ++SI) {
1944 Succ = *SI;
1945 I = BBStates.find(Succ);
1946 assert(I != BBStates.end());
1947 MyStates.MergeSucc(I->second);
1948 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001949 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001950
Michael Gottesman43e7e002013-04-03 22:41:59 +00001951 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001952 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001953 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001954
John McCalld935e9c2011-06-15 23:37:01 +00001955 // Visit all the instructions, bottom-up.
1956 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1957 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001958
1959 // Invoke instructions are visited as part of their successors (below).
1960 if (isa<InvokeInst>(Inst))
1961 continue;
1962
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001963 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
1964
Dan Gohman5c70fad2012-03-23 17:47:54 +00001965 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1966 }
1967
Dan Gohmandae33492012-04-27 18:56:31 +00001968 // If there's a predecessor with an invoke, visit the invoke as if it were
1969 // part of this block, since we can't insert code after an invoke in its own
1970 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001971 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1972 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001973 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001974 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1975 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001976 }
John McCalld935e9c2011-06-15 23:37:01 +00001977
Michael Gottesman43e7e002013-04-03 22:41:59 +00001978 // If ARC Annotations are enabled, output the current state of pointers at the
1979 // top of the basic block.
1980 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001981
Dan Gohman817a7c62012-03-22 18:24:56 +00001982 return NestingDetected;
1983}
John McCalld935e9c2011-06-15 23:37:01 +00001984
Dan Gohman817a7c62012-03-22 18:24:56 +00001985bool
1986ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1987 DenseMap<Value *, RRInfo> &Releases,
1988 BBState &MyStates) {
1989 bool NestingDetected = false;
1990 InstructionClass Class = GetInstructionClass(Inst);
1991 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001992
Dan Gohman817a7c62012-03-22 18:24:56 +00001993 switch (Class) {
1994 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001995 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1996 // objc_retainBlocks to objc_retains. Thus at this point any
1997 // objc_retainBlocks that we see are not optimizable.
1998 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001999 case IC_Retain:
2000 case IC_RetainRV: {
2001 Arg = GetObjCArg(Inst);
2002
2003 PtrState &S = MyStates.getPtrTopDownState(Arg);
2004
2005 // Don't do retain+release tracking for IC_RetainRV, because it's
2006 // better to let it remain as the first instruction after a call.
2007 if (Class != IC_RetainRV) {
2008 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002009 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002010 // hopefully eliminated the second retain, which may allow us to
2011 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002012 // Theoretically we could implement removal of nested retain+release
2013 // pairs by making PtrState hold a stack of states, but this is
2014 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002015 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002016 NestingDetected = true;
2017
Michael Gottesman81b1d432013-03-26 00:42:04 +00002018 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002019 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002020 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002021 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002022 }
John McCalld935e9c2011-06-15 23:37:01 +00002023
Dan Gohmandf476e52012-09-04 23:16:20 +00002024 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002025
2026 // A retain can be a potential use; procede to the generic checking
2027 // code below.
2028 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002029 }
2030 case IC_Release: {
2031 Arg = GetObjCArg(Inst);
2032
2033 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002034 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002035
2036 switch (S.GetSeq()) {
2037 case S_Retain:
2038 case S_CanRelease:
2039 S.RRI.ReverseInsertPts.clear();
2040 // FALL THROUGH
2041 case S_Use:
2042 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2043 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2044 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002045 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002046 S.ClearSequenceProgress();
2047 break;
2048 case S_None:
2049 break;
2050 case S_Stop:
2051 case S_Release:
2052 case S_MovableRelease:
2053 llvm_unreachable("top-down pointer in release state!");
2054 }
2055 break;
2056 }
2057 case IC_AutoreleasepoolPop:
2058 // Conservatively, clear MyStates for all known pointers.
2059 MyStates.clearTopDownPointers();
2060 return NestingDetected;
2061 case IC_AutoreleasepoolPush:
2062 case IC_None:
2063 // These are irrelevant.
2064 return NestingDetected;
2065 default:
2066 break;
2067 }
2068
2069 // Consider any other possible effects of this instruction on each
2070 // pointer being tracked.
2071 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2072 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2073 const Value *Ptr = MI->first;
2074 if (Ptr == Arg)
2075 continue; // Handled above.
2076 PtrState &S = MI->second;
2077 Sequence Seq = S.GetSeq();
2078
2079 // Check for possible releases.
2080 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002081 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002082 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002083 case S_Retain:
2084 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002085 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002086 assert(S.RRI.ReverseInsertPts.empty());
2087 S.RRI.ReverseInsertPts.insert(Inst);
2088
2089 // One call can't cause a transition from S_Retain to S_CanRelease
2090 // and S_CanRelease to S_Use. If we've made the first transition,
2091 // we're done.
2092 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002093 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002094 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002095 case S_None:
2096 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002097 case S_Stop:
2098 case S_Release:
2099 case S_MovableRelease:
2100 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002101 }
2102 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002103
2104 // Check for possible direct uses.
2105 switch (Seq) {
2106 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002107 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002108 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002109 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2110 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002111 break;
2112 case S_Retain:
2113 case S_Use:
2114 case S_None:
2115 break;
2116 case S_Stop:
2117 case S_Release:
2118 case S_MovableRelease:
2119 llvm_unreachable("top-down pointer in release state!");
2120 }
John McCalld935e9c2011-06-15 23:37:01 +00002121 }
2122
2123 return NestingDetected;
2124}
2125
2126bool
2127ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2128 DenseMap<const BasicBlock *, BBState> &BBStates,
2129 DenseMap<Value *, RRInfo> &Releases) {
2130 bool NestingDetected = false;
2131 BBState &MyStates = BBStates[BB];
2132
2133 // Merge the states from each predecessor to compute the initial state
2134 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002135 BBState::edge_iterator PI(MyStates.pred_begin()),
2136 PE(MyStates.pred_end());
2137 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002138 const BasicBlock *Pred = *PI;
2139 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2140 assert(I != BBStates.end());
2141 MyStates.InitFromPred(I->second);
2142 ++PI;
2143 for (; PI != PE; ++PI) {
2144 Pred = *PI;
2145 I = BBStates.find(Pred);
2146 assert(I != BBStates.end());
2147 MyStates.MergePred(I->second);
2148 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002149 }
John McCalld935e9c2011-06-15 23:37:01 +00002150
Michael Gottesman43e7e002013-04-03 22:41:59 +00002151 // If ARC Annotations are enabled, output the current state of pointers at the
2152 // top of the basic block.
2153 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002154
John McCalld935e9c2011-06-15 23:37:01 +00002155 // Visit all the instructions, top-down.
2156 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2157 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002158
2159 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
2160
Dan Gohman817a7c62012-03-22 18:24:56 +00002161 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002162 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002163
Michael Gottesman43e7e002013-04-03 22:41:59 +00002164 // If ARC Annotations are enabled, output the current state of pointers at the
2165 // bottom of the basic block.
2166 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002167
John McCalld935e9c2011-06-15 23:37:01 +00002168 CheckForCFGHazards(BB, BBStates, MyStates);
2169 return NestingDetected;
2170}
2171
Dan Gohmana53a12c2011-12-12 19:42:25 +00002172static void
2173ComputePostOrders(Function &F,
2174 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002175 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2176 unsigned NoObjCARCExceptionsMDKind,
2177 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002178 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002179 SmallPtrSet<BasicBlock *, 16> Visited;
2180
2181 // Do DFS, computing the PostOrder.
2182 SmallPtrSet<BasicBlock *, 16> OnStack;
2183 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002184
2185 // Functions always have exactly one entry block, and we don't have
2186 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002187 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002188 BBState &MyStates = BBStates[EntryBB];
2189 MyStates.SetAsEntry();
2190 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2191 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002192 Visited.insert(EntryBB);
2193 OnStack.insert(EntryBB);
2194 do {
2195 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002196 BasicBlock *CurrBB = SuccStack.back().first;
2197 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2198 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002199
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002200 while (SuccStack.back().second != SE) {
2201 BasicBlock *SuccBB = *SuccStack.back().second++;
2202 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002203 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2204 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002205 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002206 BBState &SuccStates = BBStates[SuccBB];
2207 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002208 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002209 goto dfs_next_succ;
2210 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002211
2212 if (!OnStack.count(SuccBB)) {
2213 BBStates[CurrBB].addSucc(SuccBB);
2214 BBStates[SuccBB].addPred(CurrBB);
2215 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002216 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002217 OnStack.erase(CurrBB);
2218 PostOrder.push_back(CurrBB);
2219 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002220 } while (!SuccStack.empty());
2221
2222 Visited.clear();
2223
Dan Gohmana53a12c2011-12-12 19:42:25 +00002224 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002225 // Functions may have many exits, and there also blocks which we treat
2226 // as exits due to ignored edges.
2227 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2228 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2229 BasicBlock *ExitBB = I;
2230 BBState &MyStates = BBStates[ExitBB];
2231 if (!MyStates.isExit())
2232 continue;
2233
Dan Gohmandae33492012-04-27 18:56:31 +00002234 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002235
2236 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002237 Visited.insert(ExitBB);
2238 while (!PredStack.empty()) {
2239 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002240 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2241 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002242 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002243 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002244 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002245 goto reverse_dfs_next_succ;
2246 }
2247 }
2248 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2249 }
2250 }
2251}
2252
Michael Gottesman97e3df02013-01-14 00:35:14 +00002253// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002254bool
2255ObjCARCOpt::Visit(Function &F,
2256 DenseMap<const BasicBlock *, BBState> &BBStates,
2257 MapVector<Value *, RRInfo> &Retains,
2258 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002259
2260 // Use reverse-postorder traversals, because we magically know that loops
2261 // will be well behaved, i.e. they won't repeatedly call retain on a single
2262 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2263 // class here because we want the reverse-CFG postorder to consider each
2264 // function exit point, and we want to ignore selected cycle edges.
2265 SmallVector<BasicBlock *, 16> PostOrder;
2266 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002267 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2268 NoObjCARCExceptionsMDKind,
2269 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002270
2271 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002272 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002273 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002274 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2275 I != E; ++I)
2276 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002277
Dan Gohmana53a12c2011-12-12 19:42:25 +00002278 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002279 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002280 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2281 PostOrder.rbegin(), E = PostOrder.rend();
2282 I != E; ++I)
2283 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002284
2285 return TopDownNestingDetected && BottomUpNestingDetected;
2286}
2287
Michael Gottesman97e3df02013-01-14 00:35:14 +00002288/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002289void ObjCARCOpt::MoveCalls(Value *Arg,
2290 RRInfo &RetainsToMove,
2291 RRInfo &ReleasesToMove,
2292 MapVector<Value *, RRInfo> &Retains,
2293 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002294 SmallVectorImpl<Instruction *> &DeadInsts,
2295 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002296 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002297 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00002298
2299 // Insert the new retain and release calls.
2300 for (SmallPtrSet<Instruction *, 2>::const_iterator
2301 PI = ReleasesToMove.ReverseInsertPts.begin(),
2302 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2303 Instruction *InsertPt = *PI;
2304 Value *MyArg = ArgTy == ParamTy ? Arg :
2305 new BitCastInst(Arg, ParamTy, "", InsertPt);
2306 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002307 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002308 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002309 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002310
Michael Gottesmanc189a392013-01-09 19:23:24 +00002311 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2312 << "\n"
2313 " At insertion point: " << *InsertPt
2314 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002315 }
2316 for (SmallPtrSet<Instruction *, 2>::const_iterator
2317 PI = RetainsToMove.ReverseInsertPts.begin(),
2318 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002319 Instruction *InsertPt = *PI;
2320 Value *MyArg = ArgTy == ParamTy ? Arg :
2321 new BitCastInst(Arg, ParamTy, "", InsertPt);
2322 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2323 "", InsertPt);
2324 // Attach a clang.imprecise_release metadata tag, if appropriate.
2325 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2326 Call->setMetadata(ImpreciseReleaseMDKind, M);
2327 Call->setDoesNotThrow();
2328 if (ReleasesToMove.IsTailCallRelease)
2329 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002330
2331 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2332 << "\n"
2333 " At insertion point: " << *InsertPt
2334 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002335 }
2336
2337 // Delete the original retain and release calls.
2338 for (SmallPtrSet<Instruction *, 2>::const_iterator
2339 AI = RetainsToMove.Calls.begin(),
2340 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2341 Instruction *OrigRetain = *AI;
2342 Retains.blot(OrigRetain);
2343 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002344 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2345 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002346 }
2347 for (SmallPtrSet<Instruction *, 2>::const_iterator
2348 AI = ReleasesToMove.Calls.begin(),
2349 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2350 Instruction *OrigRelease = *AI;
2351 Releases.erase(OrigRelease);
2352 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002353 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2354 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002355 }
2356}
2357
Michael Gottesman9de6f962013-01-22 21:49:00 +00002358bool
2359ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2360 &BBStates,
2361 MapVector<Value *, RRInfo> &Retains,
2362 DenseMap<Value *, RRInfo> &Releases,
2363 Module *M,
2364 SmallVector<Instruction *, 4> &NewRetains,
2365 SmallVector<Instruction *, 4> &NewReleases,
2366 SmallVector<Instruction *, 8> &DeadInsts,
2367 RRInfo &RetainsToMove,
2368 RRInfo &ReleasesToMove,
2369 Value *Arg,
2370 bool KnownSafe,
2371 bool &AnyPairsCompletelyEliminated) {
2372 // If a pair happens in a region where it is known that the reference count
2373 // is already incremented, we can similarly ignore possible decrements.
2374 bool KnownSafeTD = true, KnownSafeBU = true;
2375
2376 // Connect the dots between the top-down-collected RetainsToMove and
2377 // bottom-up-collected ReleasesToMove to form sets of related calls.
2378 // This is an iterative process so that we connect multiple releases
2379 // to multiple retains if needed.
2380 unsigned OldDelta = 0;
2381 unsigned NewDelta = 0;
2382 unsigned OldCount = 0;
2383 unsigned NewCount = 0;
2384 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002385 for (;;) {
2386 for (SmallVectorImpl<Instruction *>::const_iterator
2387 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2388 Instruction *NewRetain = *NI;
2389 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2390 assert(It != Retains.end());
2391 const RRInfo &NewRetainRRI = It->second;
2392 KnownSafeTD &= NewRetainRRI.KnownSafe;
2393 for (SmallPtrSet<Instruction *, 2>::const_iterator
2394 LI = NewRetainRRI.Calls.begin(),
2395 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2396 Instruction *NewRetainRelease = *LI;
2397 DenseMap<Value *, RRInfo>::const_iterator Jt =
2398 Releases.find(NewRetainRelease);
2399 if (Jt == Releases.end())
2400 return false;
2401 const RRInfo &NewRetainReleaseRRI = Jt->second;
2402 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2403 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2404 OldDelta -=
2405 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2406
2407 // Merge the ReleaseMetadata and IsTailCallRelease values.
2408 if (FirstRelease) {
2409 ReleasesToMove.ReleaseMetadata =
2410 NewRetainReleaseRRI.ReleaseMetadata;
2411 ReleasesToMove.IsTailCallRelease =
2412 NewRetainReleaseRRI.IsTailCallRelease;
2413 FirstRelease = false;
2414 } else {
2415 if (ReleasesToMove.ReleaseMetadata !=
2416 NewRetainReleaseRRI.ReleaseMetadata)
2417 ReleasesToMove.ReleaseMetadata = 0;
2418 if (ReleasesToMove.IsTailCallRelease !=
2419 NewRetainReleaseRRI.IsTailCallRelease)
2420 ReleasesToMove.IsTailCallRelease = false;
2421 }
2422
2423 // Collect the optimal insertion points.
2424 if (!KnownSafe)
2425 for (SmallPtrSet<Instruction *, 2>::const_iterator
2426 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2427 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2428 RI != RE; ++RI) {
2429 Instruction *RIP = *RI;
2430 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2431 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2432 }
2433 NewReleases.push_back(NewRetainRelease);
2434 }
2435 }
2436 }
2437 NewRetains.clear();
2438 if (NewReleases.empty()) break;
2439
2440 // Back the other way.
2441 for (SmallVectorImpl<Instruction *>::const_iterator
2442 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2443 Instruction *NewRelease = *NI;
2444 DenseMap<Value *, RRInfo>::const_iterator It =
2445 Releases.find(NewRelease);
2446 assert(It != Releases.end());
2447 const RRInfo &NewReleaseRRI = It->second;
2448 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2449 for (SmallPtrSet<Instruction *, 2>::const_iterator
2450 LI = NewReleaseRRI.Calls.begin(),
2451 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2452 Instruction *NewReleaseRetain = *LI;
2453 MapVector<Value *, RRInfo>::const_iterator Jt =
2454 Retains.find(NewReleaseRetain);
2455 if (Jt == Retains.end())
2456 return false;
2457 const RRInfo &NewReleaseRetainRRI = Jt->second;
2458 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2459 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2460 unsigned PathCount =
2461 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2462 OldDelta += PathCount;
2463 OldCount += PathCount;
2464
Michael Gottesman9de6f962013-01-22 21:49:00 +00002465 // Collect the optimal insertion points.
2466 if (!KnownSafe)
2467 for (SmallPtrSet<Instruction *, 2>::const_iterator
2468 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2469 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2470 RI != RE; ++RI) {
2471 Instruction *RIP = *RI;
2472 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2473 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2474 NewDelta += PathCount;
2475 NewCount += PathCount;
2476 }
2477 }
2478 NewRetains.push_back(NewReleaseRetain);
2479 }
2480 }
2481 }
2482 NewReleases.clear();
2483 if (NewRetains.empty()) break;
2484 }
2485
2486 // If the pointer is known incremented or nested, we can safely delete the
2487 // pair regardless of what's between them.
2488 if (KnownSafeTD || KnownSafeBU) {
2489 RetainsToMove.ReverseInsertPts.clear();
2490 ReleasesToMove.ReverseInsertPts.clear();
2491 NewCount = 0;
2492 } else {
2493 // Determine whether the new insertion points we computed preserve the
2494 // balance of retain and release calls through the program.
2495 // TODO: If the fully aggressive solution isn't valid, try to find a
2496 // less aggressive solution which is.
2497 if (NewDelta != 0)
2498 return false;
2499 }
2500
2501 // Determine whether the original call points are balanced in the retain and
2502 // release calls through the program. If not, conservatively don't touch
2503 // them.
2504 // TODO: It's theoretically possible to do code motion in this case, as
2505 // long as the existing imbalances are maintained.
2506 if (OldDelta != 0)
2507 return false;
2508
2509 Changed = true;
2510 assert(OldCount != 0 && "Unreachable code?");
2511 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002512 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002513 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002514
2515 // We can move calls!
2516 return true;
2517}
2518
Michael Gottesman97e3df02013-01-14 00:35:14 +00002519/// Identify pairings between the retains and releases, and delete and/or move
2520/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002521bool
2522ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2523 &BBStates,
2524 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002525 DenseMap<Value *, RRInfo> &Releases,
2526 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00002527 bool AnyPairsCompletelyEliminated = false;
2528 RRInfo RetainsToMove;
2529 RRInfo ReleasesToMove;
2530 SmallVector<Instruction *, 4> NewRetains;
2531 SmallVector<Instruction *, 4> NewReleases;
2532 SmallVector<Instruction *, 8> DeadInsts;
2533
Dan Gohman670f9372012-04-13 18:57:48 +00002534 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002535 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002536 E = Retains.end(); I != E; ++I) {
2537 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002538 if (!V) continue; // blotted
2539
2540 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002541
2542 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2543 << "\n");
2544
John McCalld935e9c2011-06-15 23:37:01 +00002545 Value *Arg = GetObjCArg(Retain);
2546
Dan Gohman728db492012-01-13 00:39:07 +00002547 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002548 // not being managed by ObjC reference counting, so we can delete pairs
2549 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002550 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002551
Dan Gohman56e1cef2011-08-22 17:29:11 +00002552 // A constant pointer can't be pointing to an object on the heap. It may
2553 // be reference-counted, but it won't be deleted.
2554 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2555 if (const GlobalVariable *GV =
2556 dyn_cast<GlobalVariable>(
2557 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2558 if (GV->isConstant())
2559 KnownSafe = true;
2560
John McCalld935e9c2011-06-15 23:37:01 +00002561 // Connect the dots between the top-down-collected RetainsToMove and
2562 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002563 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002564 bool PerformMoveCalls =
2565 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2566 NewReleases, DeadInsts, RetainsToMove,
2567 ReleasesToMove, Arg, KnownSafe,
2568 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002569
Michael Gottesman81b1d432013-03-26 00:42:04 +00002570#ifdef ARC_ANNOTATIONS
2571 // Do not move calls if ARC annotations are requested. If we were to move
2572 // calls in this case, we would not be able
2573 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2574#endif // ARC_ANNOTATIONS
2575
Michael Gottesman9de6f962013-01-22 21:49:00 +00002576 if (PerformMoveCalls) {
2577 // Ok, everything checks out and we're all set. Let's move/delete some
2578 // code!
2579 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2580 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002581 }
2582
Michael Gottesman9de6f962013-01-22 21:49:00 +00002583 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002584 NewReleases.clear();
2585 NewRetains.clear();
2586 RetainsToMove.clear();
2587 ReleasesToMove.clear();
2588 }
2589
2590 // Now that we're done moving everything, we can delete the newly dead
2591 // instructions, as we no longer need them as insert points.
2592 while (!DeadInsts.empty())
2593 EraseInstruction(DeadInsts.pop_back_val());
2594
2595 return AnyPairsCompletelyEliminated;
2596}
2597
Michael Gottesman97e3df02013-01-14 00:35:14 +00002598/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002599void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2600 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2601 // itself because it uses AliasAnalysis and we need to do provenance
2602 // queries instead.
2603 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2604 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002605
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002606 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00002607 "\n");
2608
John McCalld935e9c2011-06-15 23:37:01 +00002609 InstructionClass Class = GetBasicInstructionClass(Inst);
2610 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2611 continue;
2612
2613 // Delete objc_loadWeak calls with no users.
2614 if (Class == IC_LoadWeak && Inst->use_empty()) {
2615 Inst->eraseFromParent();
2616 continue;
2617 }
2618
2619 // TODO: For now, just look for an earlier available version of this value
2620 // within the same block. Theoretically, we could do memdep-style non-local
2621 // analysis too, but that would want caching. A better approach would be to
2622 // use the technique that EarlyCSE uses.
2623 inst_iterator Current = llvm::prior(I);
2624 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2625 for (BasicBlock::iterator B = CurrentBB->begin(),
2626 J = Current.getInstructionIterator();
2627 J != B; --J) {
2628 Instruction *EarlierInst = &*llvm::prior(J);
2629 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2630 switch (EarlierClass) {
2631 case IC_LoadWeak:
2632 case IC_LoadWeakRetained: {
2633 // If this is loading from the same pointer, replace this load's value
2634 // with that one.
2635 CallInst *Call = cast<CallInst>(Inst);
2636 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2637 Value *Arg = Call->getArgOperand(0);
2638 Value *EarlierArg = EarlierCall->getArgOperand(0);
2639 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2640 case AliasAnalysis::MustAlias:
2641 Changed = true;
2642 // If the load has a builtin retain, insert a plain retain for it.
2643 if (Class == IC_LoadWeakRetained) {
2644 CallInst *CI =
2645 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2646 "", Call);
2647 CI->setTailCall();
2648 }
2649 // Zap the fully redundant load.
2650 Call->replaceAllUsesWith(EarlierCall);
2651 Call->eraseFromParent();
2652 goto clobbered;
2653 case AliasAnalysis::MayAlias:
2654 case AliasAnalysis::PartialAlias:
2655 goto clobbered;
2656 case AliasAnalysis::NoAlias:
2657 break;
2658 }
2659 break;
2660 }
2661 case IC_StoreWeak:
2662 case IC_InitWeak: {
2663 // If this is storing to the same pointer and has the same size etc.
2664 // replace this load's value with the stored value.
2665 CallInst *Call = cast<CallInst>(Inst);
2666 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2667 Value *Arg = Call->getArgOperand(0);
2668 Value *EarlierArg = EarlierCall->getArgOperand(0);
2669 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2670 case AliasAnalysis::MustAlias:
2671 Changed = true;
2672 // If the load has a builtin retain, insert a plain retain for it.
2673 if (Class == IC_LoadWeakRetained) {
2674 CallInst *CI =
2675 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2676 "", Call);
2677 CI->setTailCall();
2678 }
2679 // Zap the fully redundant load.
2680 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2681 Call->eraseFromParent();
2682 goto clobbered;
2683 case AliasAnalysis::MayAlias:
2684 case AliasAnalysis::PartialAlias:
2685 goto clobbered;
2686 case AliasAnalysis::NoAlias:
2687 break;
2688 }
2689 break;
2690 }
2691 case IC_MoveWeak:
2692 case IC_CopyWeak:
2693 // TOOD: Grab the copied value.
2694 goto clobbered;
2695 case IC_AutoreleasepoolPush:
2696 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002697 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002698 case IC_User:
2699 // Weak pointers are only modified through the weak entry points
2700 // (and arbitrary calls, which could call the weak entry points).
2701 break;
2702 default:
2703 // Anything else could modify the weak pointer.
2704 goto clobbered;
2705 }
2706 }
2707 clobbered:;
2708 }
2709
2710 // Then, for each destroyWeak with an alloca operand, check to see if
2711 // the alloca and all its users can be zapped.
2712 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2713 Instruction *Inst = &*I++;
2714 InstructionClass Class = GetBasicInstructionClass(Inst);
2715 if (Class != IC_DestroyWeak)
2716 continue;
2717
2718 CallInst *Call = cast<CallInst>(Inst);
2719 Value *Arg = Call->getArgOperand(0);
2720 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2721 for (Value::use_iterator UI = Alloca->use_begin(),
2722 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002723 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002724 switch (GetBasicInstructionClass(UserInst)) {
2725 case IC_InitWeak:
2726 case IC_StoreWeak:
2727 case IC_DestroyWeak:
2728 continue;
2729 default:
2730 goto done;
2731 }
2732 }
2733 Changed = true;
2734 for (Value::use_iterator UI = Alloca->use_begin(),
2735 UE = Alloca->use_end(); UI != UE; ) {
2736 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002737 switch (GetBasicInstructionClass(UserInst)) {
2738 case IC_InitWeak:
2739 case IC_StoreWeak:
2740 // These functions return their second argument.
2741 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2742 break;
2743 case IC_DestroyWeak:
2744 // No return value.
2745 break;
2746 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002747 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002748 }
John McCalld935e9c2011-06-15 23:37:01 +00002749 UserInst->eraseFromParent();
2750 }
2751 Alloca->eraseFromParent();
2752 done:;
2753 }
2754 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002755
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002756 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002757
John McCalld935e9c2011-06-15 23:37:01 +00002758}
2759
Michael Gottesman97e3df02013-01-14 00:35:14 +00002760/// Identify program paths which execute sequences of retains and releases which
2761/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002762bool ObjCARCOpt::OptimizeSequences(Function &F) {
2763 /// Releases, Retains - These are used to store the results of the main flow
2764 /// analysis. These use Value* as the key instead of Instruction* so that the
2765 /// map stays valid when we get around to rewriting code and calls get
2766 /// replaced by arguments.
2767 DenseMap<Value *, RRInfo> Releases;
2768 MapVector<Value *, RRInfo> Retains;
2769
Michael Gottesman97e3df02013-01-14 00:35:14 +00002770 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002771 /// states for each identified object at each block.
2772 DenseMap<const BasicBlock *, BBState> BBStates;
2773
2774 // Analyze the CFG of the function, and all instructions.
2775 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2776
2777 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002778 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2779 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002780}
2781
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002782/// Check if there is a dependent call earlier that does not have anything in
2783/// between the Retain and the call that can affect the reference count of their
2784/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002785static bool
2786HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2787 SmallPtrSet<Instruction *, 4> &DepInsts,
2788 SmallPtrSet<const BasicBlock *, 4> &Visited,
2789 ProvenanceAnalysis &PA) {
2790 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2791 DepInsts, Visited, PA);
2792 if (DepInsts.size() != 1)
2793 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002794
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002795 CallInst *Call =
2796 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002797
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002798 // Check that the pointer is the return value of the call.
2799 if (!Call || Arg != Call)
2800 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002801
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002802 // Check that the call is a regular call.
2803 InstructionClass Class = GetBasicInstructionClass(Call);
2804 if (Class != IC_CallOrUser && Class != IC_Call)
2805 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002806
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002807 return true;
2808}
2809
Michael Gottesman6908db12013-04-03 23:16:05 +00002810/// Find a dependent retain that precedes the given autorelease for which there
2811/// is nothing in between the two instructions that can affect the ref count of
2812/// Arg.
2813static CallInst *
2814FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2815 Instruction *Autorelease,
2816 SmallPtrSet<Instruction *, 4> &DepInsts,
2817 SmallPtrSet<const BasicBlock *, 4> &Visited,
2818 ProvenanceAnalysis &PA) {
2819 FindDependencies(CanChangeRetainCount, Arg,
2820 BB, Autorelease, DepInsts, Visited, PA);
2821 if (DepInsts.size() != 1)
2822 return 0;
2823
2824 CallInst *Retain =
2825 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2826
2827 // Check that we found a retain with the same argument.
2828 if (!Retain ||
2829 !IsRetain(GetBasicInstructionClass(Retain)) ||
2830 GetObjCArg(Retain) != Arg) {
2831 return 0;
2832 }
2833
2834 return Retain;
2835}
2836
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002837/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2838/// no instructions dependent on Arg that need a positive ref count in between
2839/// the autorelease and the ret.
2840static CallInst *
2841FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2842 ReturnInst *Ret,
2843 SmallPtrSet<Instruction *, 4> &DepInsts,
2844 SmallPtrSet<const BasicBlock *, 4> &V,
2845 ProvenanceAnalysis &PA) {
2846 FindDependencies(NeedsPositiveRetainCount, Arg,
2847 BB, Ret, DepInsts, V, PA);
2848 if (DepInsts.size() != 1)
2849 return 0;
2850
2851 CallInst *Autorelease =
2852 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2853 if (!Autorelease)
2854 return 0;
2855 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2856 if (!IsAutorelease(AutoreleaseClass))
2857 return 0;
2858 if (GetObjCArg(Autorelease) != Arg)
2859 return 0;
2860
2861 return Autorelease;
2862}
2863
Michael Gottesman97e3df02013-01-14 00:35:14 +00002864/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002865/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002866/// %call = call i8* @something(...)
2867/// %2 = call i8* @objc_retain(i8* %call)
2868/// %3 = call i8* @objc_autorelease(i8* %2)
2869/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002870/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002871/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002872void ObjCARCOpt::OptimizeReturns(Function &F) {
2873 if (!F.getReturnType()->isPointerTy())
2874 return;
2875
2876 SmallPtrSet<Instruction *, 4> DependingInstructions;
2877 SmallPtrSet<const BasicBlock *, 4> Visited;
2878 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2879 BasicBlock *BB = FI;
2880 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002881
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002882 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002883
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002884 if (!Ret)
2885 continue;
2886
John McCalld935e9c2011-06-15 23:37:01 +00002887 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002888
2889 // Look for an ``autorelease'' instruction that is a predecssor of Ret and
2890 // dependent on Arg such that there are no instructions dependent on Arg
2891 // that need a positive ref count in between the autorelease and Ret.
2892 CallInst *Autorelease =
2893 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2894 DependingInstructions, Visited,
2895 PA);
2896 if (Autorelease) {
John McCalld935e9c2011-06-15 23:37:01 +00002897 DependingInstructions.clear();
2898 Visited.clear();
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002899
2900 CallInst *Retain =
2901 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2902 DependingInstructions, Visited, PA);
2903 if (Retain) {
John McCalld935e9c2011-06-15 23:37:01 +00002904 DependingInstructions.clear();
2905 Visited.clear();
Michael Gottesman6908db12013-04-03 23:16:05 +00002906
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002907 // Check that there is nothing that can affect the reference count
2908 // between the retain and the call. Note that Retain need not be in BB.
2909 if (HasSafePathToPredecessorCall(Arg, Retain, DependingInstructions,
2910 Visited, PA)) {
John McCalld935e9c2011-06-15 23:37:01 +00002911 // If so, we can zap the retain and autorelease.
2912 Changed = true;
2913 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002914 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
2915 << "\n Erasing: "
2916 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002917 EraseInstruction(Retain);
2918 EraseInstruction(Autorelease);
2919 }
2920 }
2921 }
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002922
John McCalld935e9c2011-06-15 23:37:01 +00002923 DependingInstructions.clear();
2924 Visited.clear();
2925 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002926
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002927 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002928
John McCalld935e9c2011-06-15 23:37:01 +00002929}
2930
2931bool ObjCARCOpt::doInitialization(Module &M) {
2932 if (!EnableARCOpts)
2933 return false;
2934
Dan Gohman670f9372012-04-13 18:57:48 +00002935 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002936 Run = ModuleHasARC(M);
2937 if (!Run)
2938 return false;
2939
John McCalld935e9c2011-06-15 23:37:01 +00002940 // Identify the imprecise release metadata kind.
2941 ImpreciseReleaseMDKind =
2942 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002943 CopyOnEscapeMDKind =
2944 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002945 NoObjCARCExceptionsMDKind =
2946 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002947#ifdef ARC_ANNOTATIONS
2948 ARCAnnotationBottomUpMDKind =
2949 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2950 ARCAnnotationTopDownMDKind =
2951 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2952 ARCAnnotationProvenanceSourceMDKind =
2953 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2954#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002955
John McCalld935e9c2011-06-15 23:37:01 +00002956 // Intuitively, objc_retain and others are nocapture, however in practice
2957 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002958 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002959
2960 // These are initialized lazily.
2961 RetainRVCallee = 0;
2962 AutoreleaseRVCallee = 0;
2963 ReleaseCallee = 0;
2964 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002965 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002966 AutoreleaseCallee = 0;
2967
2968 return false;
2969}
2970
2971bool ObjCARCOpt::runOnFunction(Function &F) {
2972 if (!EnableARCOpts)
2973 return false;
2974
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002975 // If nothing in the Module uses ARC, don't do anything.
2976 if (!Run)
2977 return false;
2978
John McCalld935e9c2011-06-15 23:37:01 +00002979 Changed = false;
2980
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002981 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
2982
John McCalld935e9c2011-06-15 23:37:01 +00002983 PA.setAA(&getAnalysis<AliasAnalysis>());
2984
2985 // This pass performs several distinct transformations. As a compile-time aid
2986 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2987 // library functions aren't declared.
2988
2989 // Preliminary optimizations. This also computs UsedInThisFunction.
2990 OptimizeIndividualCalls(F);
2991
2992 // Optimizations for weak pointers.
2993 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2994 (1 << IC_LoadWeakRetained) |
2995 (1 << IC_StoreWeak) |
2996 (1 << IC_InitWeak) |
2997 (1 << IC_CopyWeak) |
2998 (1 << IC_MoveWeak) |
2999 (1 << IC_DestroyWeak)))
3000 OptimizeWeakCalls(F);
3001
3002 // Optimizations for retain+release pairs.
3003 if (UsedInThisFunction & ((1 << IC_Retain) |
3004 (1 << IC_RetainRV) |
3005 (1 << IC_RetainBlock)))
3006 if (UsedInThisFunction & (1 << IC_Release))
3007 // Run OptimizeSequences until it either stops making changes or
3008 // no retain+release pair nesting is detected.
3009 while (OptimizeSequences(F)) {}
3010
3011 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003012 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3013 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003014 OptimizeReturns(F);
3015
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003016 DEBUG(dbgs() << "\n");
3017
John McCalld935e9c2011-06-15 23:37:01 +00003018 return Changed;
3019}
3020
3021void ObjCARCOpt::releaseMemory() {
3022 PA.clear();
3023}
3024
Michael Gottesman97e3df02013-01-14 00:35:14 +00003025/// @}
3026///