blob: e1a81dda8c12e3b0bee9cb9a86faceb1fa0de712 [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 Gottesman5a91bbf2013-05-24 20:44:02 +000033#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000034#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000036#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000037#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000039#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000040#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000041#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000042
John McCalld935e9c2011-06-15 23:37:01 +000043using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000044using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000045
Michael Gottesman97e3df02013-01-14 00:35:14 +000046/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
47/// @{
John McCalld935e9c2011-06-15 23:37:01 +000048
49namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000052 template<class KeyT, class ValueT>
53 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000054 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000055 typedef DenseMap<KeyT, size_t> MapTy;
56 MapTy Map;
57
John McCalld935e9c2011-06-15 23:37:01 +000058 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000059 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000060 VectorTy Vector;
61
62 public:
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
69
70#ifdef XDEBUG
71 ~MapVector() {
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
74 I != E; ++I) {
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
77 }
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
80 assert(!I->first ||
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
83 }
84#endif
85
Dan Gohman55b06742012-03-02 01:13:53 +000086 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000087 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
89 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000090 size_t Num = Vector.size();
91 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000092 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000093 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000094 }
95 return Vector[Pair.first->second].second;
96 }
97
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
102 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000103 size_t Num = Vector.size();
104 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000105 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000106 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000107 }
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
109 }
110
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
115 }
116
Dan Gohman55b06742012-03-02 01:13:53 +0000117 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
121 }
122
Michael Gottesman97e3df02013-01-14 00:35:14 +0000123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000126 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
130 Map.erase(It);
131 }
132
133 void clear() {
134 Map.clear();
135 Vector.clear();
136 }
137 };
138}
139
Michael Gottesman97e3df02013-01-14 00:35:14 +0000140/// @}
141///
142/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
143/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000144
Michael Gottesman97e3df02013-01-14 00:35:14 +0000145/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000147static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
158 return 0;
159 return Arg;
160 }
161
Dan Gohman41375a32012-05-08 23:39:44 +0000162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
166 UI != UE; ++UI) {
167 const User *U = *UI;
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
169 return 0;
170 }
171
172 return Arg;
173 }
174
175 return 0;
176}
177
Michael Gottesman774d2c02013-01-29 21:00:52 +0000178/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179///
180/// This differs from regular escape analysis in that a use as an
181/// argument to a call is not considered an escape.
182///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000183static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000185
Dan Gohman728db492012-01-13 00:39:07 +0000186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
191 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000192 Worklist.push_back(*I);
193 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000194
195 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000196 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000197
Dan Gohman728db492012-01-13 00:39:07 +0000198 do {
199 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000200
Michael Gottesman89279f82013-04-05 18:10:41 +0000201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000202
Dan Gohman728db492012-01-13 00:39:07 +0000203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
204 UI != UE; ++UI) {
205 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000206
Michael Gottesman89279f82013-04-05 18:10:41 +0000207 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000208
Dan Gohman728db492012-01-13 00:39:07 +0000209 // Special - Use by a call (callee or argument) is not considered
210 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 switch (GetBasicInstructionClass(UUser)) {
212 case IC_StoreWeak:
213 case IC_InitWeak:
214 case IC_StoreStrong:
215 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000216 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 // These special functions make copies of their pointer arguments.
219 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000220 }
John McCall20182ac2013-03-22 21:38:36 +0000221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
223 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000224 case IC_User:
225 case IC_None:
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000231 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000234 Worklist.push_back(UUser);
235 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000236 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000237 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000238 continue;
239 }
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
242 continue;
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
246 continue;
247 break;
248 default:
249 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000250 continue;
251 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000252 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000254 return true;
255 }
256 } while (!Worklist.empty());
257
258 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000259 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000260 return false;
261}
262
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000263/// This is a wrapper around getUnderlyingObjCPtr along the lines of
264/// GetUnderlyingObjects except that it returns early when it sees the first
265/// alloca.
266static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
270 do {
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000273
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000274 if (isa<AllocaInst>(P))
275 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000276
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000277 if (!Visited.insert(P))
278 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000279
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
283 continue;
284 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000285
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
289 continue;
290 }
291 } while (!Worklist.empty());
292
293 return false;
294}
295
296
Michael Gottesman97e3df02013-01-14 00:35:14 +0000297/// @}
298///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000299/// \defgroup ARCOpt ARC Optimization.
300/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000301
302// TODO: On code like this:
303//
304// objc_retain(%x)
305// stuff_that_cannot_release()
306// objc_autorelease(%x)
307// stuff_that_cannot_release()
308// objc_retain(%x)
309// stuff_that_cannot_release()
310// objc_autorelease(%x)
311//
312// The second retain and autorelease can be deleted.
313
314// TODO: It should be possible to delete
315// objc_autoreleasePoolPush and objc_autoreleasePoolPop
316// pairs if nothing is actually autoreleased between them. Also, autorelease
317// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318// after inlining) can be turned into plain release calls.
319
320// TODO: Critical-edge splitting. If the optimial insertion point is
321// a critical edge, the current algorithm has to fail, because it doesn't
322// know how to split edges. It should be possible to make the optimizer
323// think in terms of edges, rather than blocks, and then split critical
324// edges on demand.
325
326// TODO: OptimizeSequences could generalized to be Interprocedural.
327
328// TODO: Recognize that a bunch of other objc runtime calls have
329// non-escaping arguments and non-releasing arguments, and may be
330// non-autoreleasing.
331
332// TODO: Sink autorelease calls as far as possible. Unfortunately we
333// usually can't sink them past other calls, which would be the main
334// case where it would be useful.
335
Dan Gohmanb3894012011-08-19 00:26:36 +0000336// TODO: The pointer returned from objc_loadWeakRetained is retained.
337
338// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000339
John McCalld935e9c2011-06-15 23:37:01 +0000340STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000344 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000345STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000347#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000348STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000349 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000350STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000351 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000352STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000353 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000354STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000355 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000356#endif
John McCalld935e9c2011-06-15 23:37:01 +0000357
358namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000359 /// \enum Sequence
360 ///
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000363 enum Sequence {
364 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000368 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000369 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000371 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000372
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
376 switch (S) {
377 case S_None:
378 return OS << "S_None";
379 case S_Retain:
380 return OS << "S_Retain";
381 case S_CanRelease:
382 return OS << "S_CanRelease";
383 case S_Use:
384 return OS << "S_Use";
385 case S_Release:
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
389 case S_Stop:
390 return OS << "S_Stop";
391 }
392 llvm_unreachable("Unknown sequence type.");
393 }
John McCalld935e9c2011-06-15 23:37:01 +0000394}
395
396static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
397 // The easy cases.
398 if (A == B)
399 return A;
400 if (A == S_None || B == S_None)
401 return S_None;
402
John McCalld935e9c2011-06-15 23:37:01 +0000403 if (A > B) std::swap(A, B);
404 if (TopDown) {
405 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000408 return B;
409 } else {
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000413 return A;
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
416 return A;
417 if (A == S_Release && B == S_MovableRelease)
418 return A;
419 }
420
421 return S_None;
422}
423
424namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000426 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000427 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000428 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
435 ///
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
439 ///
440 /// KnownSafe is true when either of these conditions is satisfied.
441 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000442
Michael Gottesman97e3df02013-01-14 00:35:14 +0000443 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000444 bool IsTailCallRelease;
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000448 MDNode *ReleaseMetadata;
449
Michael Gottesman97e3df02013-01-14 00:35:14 +0000450 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
453
Michael Gottesman97e3df02013-01-14 00:35:14 +0000454 /// The set of optimal insert positions for moving calls in the opposite
455 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
457
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
461
John McCalld935e9c2011-06-15 23:37:01 +0000462 RRInfo() :
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000465
466 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000467
Michael Gottesman4773a102013-06-21 05:42:08 +0000468 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469 /// occured, false otherwise.
470 bool Merge(const RRInfo &Other);
471
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000472 bool IsTrackingImpreciseReleases() {
473 return ReleaseMetadata != 0;
474 }
John McCalld935e9c2011-06-15 23:37:01 +0000475 };
476}
477
478void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000479 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000480 IsTailCallRelease = false;
481 ReleaseMetadata = 0;
482 Calls.clear();
483 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000484 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000485}
486
Michael Gottesman4773a102013-06-21 05:42:08 +0000487bool RRInfo::Merge(const RRInfo &Other) {
488 // Conservatively merge the ReleaseMetadata information.
489 if (ReleaseMetadata != Other.ReleaseMetadata)
490 ReleaseMetadata = 0;
491
492 // Conservatively merge the boolean state.
493 KnownSafe &= Other.KnownSafe;
494 IsTailCallRelease &= Other.IsTailCallRelease;
495 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
496
497 // Merge the call sets.
498 Calls.insert(Other.Calls.begin(), Other.Calls.end());
499
500 // Merge the insert point sets. If there are any differences,
501 // that makes this a partial merge.
502 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
503 for (SmallPtrSet<Instruction *, 2>::const_iterator
504 I = Other.ReverseInsertPts.begin(),
505 E = Other.ReverseInsertPts.end(); I != E; ++I)
506 Partial |= ReverseInsertPts.insert(*I);
507 return Partial;
508}
509
John McCalld935e9c2011-06-15 23:37:01 +0000510namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000511 /// \brief This class summarizes several per-pointer runtime properties which
512 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000513 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000514 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000515 bool KnownPositiveRefCount;
516
Bob Wilson798a7702013-04-09 22:15:51 +0000517 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000518 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000519 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000520
Michael Gottesman97e3df02013-01-14 00:35:14 +0000521 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000522 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000523
524 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000525 /// Unidirectional information about the current sequence.
526 ///
John McCalld935e9c2011-06-15 23:37:01 +0000527 /// TODO: Encapsulate this better.
528 RRInfo RRI;
529
Dan Gohmandf476e52012-09-04 23:16:20 +0000530 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000531 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000532
Michael Gottesman93132252013-06-21 06:59:02 +0000533
534 bool IsKnownSafe() const {
535 return RRI.KnownSafe;
536 }
537
538 void SetKnownSafe(const bool NewValue) {
539 RRI.KnownSafe = NewValue;
540 }
541
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000542 bool IsTailCallRelease() const {
543 return RRI.IsTailCallRelease;
544 }
545
546 void SetTailCallRelease(const bool NewValue) {
547 RRI.IsTailCallRelease = NewValue;
548 }
549
Michael Gottesman415ddd72013-02-05 19:32:18 +0000550 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000551 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000552 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000553 }
554
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000555 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000556 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000557 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000558 }
559
Michael Gottesman07beea42013-03-23 05:31:01 +0000560 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000561 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000562 }
563
Michael Gottesman415ddd72013-02-05 19:32:18 +0000564 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000565 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000566 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000567 }
568
Michael Gottesman415ddd72013-02-05 19:32:18 +0000569 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000570 return Seq;
571 }
572
Michael Gottesman415ddd72013-02-05 19:32:18 +0000573 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000574 ResetSequenceProgress(S_None);
575 }
576
Michael Gottesman415ddd72013-02-05 19:32:18 +0000577 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000578 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000579 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000580 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000581 RRI.clear();
582 }
583
584 void Merge(const PtrState &Other, bool TopDown);
585 };
586}
587
588void
589PtrState::Merge(const PtrState &Other, bool TopDown) {
590 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000591 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000592
Dan Gohman1736c142011-10-17 18:48:25 +0000593 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000594 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000595 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000596 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000597 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000598 // If we're doing a merge on a path that's previously seen a partial
599 // merge, conservatively drop the sequence, to avoid doing partial
600 // RR elimination. If the branch predicates for the two merge differ,
601 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000602 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000603 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000604 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
605 // point, we know that currently we are not partial. Stash whether or not
606 // the merge operation caused us to undergo a partial merging of reverse
607 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000608 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000609 }
610}
611
612namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000613 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000614 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000615 /// The number of unique control paths from the entry which can reach this
616 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000617 unsigned TopDownPathCount;
618
Michael Gottesman97e3df02013-01-14 00:35:14 +0000619 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000620 unsigned BottomUpPathCount;
621
Michael Gottesman97e3df02013-01-14 00:35:14 +0000622 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000623 typedef MapVector<const Value *, PtrState> MapTy;
624
Michael Gottesman97e3df02013-01-14 00:35:14 +0000625 /// The top-down traversal uses this to record information known about a
626 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000627 MapTy PerPtrTopDown;
628
Michael Gottesman97e3df02013-01-14 00:35:14 +0000629 /// The bottom-up traversal uses this to record information known about a
630 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000631 MapTy PerPtrBottomUp;
632
Michael Gottesman97e3df02013-01-14 00:35:14 +0000633 /// Effective predecessors of the current block ignoring ignorable edges and
634 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000635 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000636 /// Effective successors of the current block ignoring ignorable edges and
637 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000638 SmallVector<BasicBlock *, 2> Succs;
639
John McCalld935e9c2011-06-15 23:37:01 +0000640 public:
641 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
642
643 typedef MapTy::iterator ptr_iterator;
644 typedef MapTy::const_iterator ptr_const_iterator;
645
646 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
647 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
648 ptr_const_iterator top_down_ptr_begin() const {
649 return PerPtrTopDown.begin();
650 }
651 ptr_const_iterator top_down_ptr_end() const {
652 return PerPtrTopDown.end();
653 }
654
655 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
656 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
657 ptr_const_iterator bottom_up_ptr_begin() const {
658 return PerPtrBottomUp.begin();
659 }
660 ptr_const_iterator bottom_up_ptr_end() const {
661 return PerPtrBottomUp.end();
662 }
663
Michael Gottesman97e3df02013-01-14 00:35:14 +0000664 /// Mark this block as being an entry block, which has one path from the
665 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000666 void SetAsEntry() { TopDownPathCount = 1; }
667
Michael Gottesman97e3df02013-01-14 00:35:14 +0000668 /// Mark this block as being an exit block, which has one path to an exit by
669 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000670 void SetAsExit() { BottomUpPathCount = 1; }
671
Michael Gottesman993fbf72013-05-13 19:40:39 +0000672 /// Attempt to find the PtrState object describing the top down state for
673 /// pointer Arg. Return a new initialized PtrState describing the top down
674 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000675 PtrState &getPtrTopDownState(const Value *Arg) {
676 return PerPtrTopDown[Arg];
677 }
678
Michael Gottesman993fbf72013-05-13 19:40:39 +0000679 /// Attempt to find the PtrState object describing the bottom up state for
680 /// pointer Arg. Return a new initialized PtrState describing the bottom up
681 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000682 PtrState &getPtrBottomUpState(const Value *Arg) {
683 return PerPtrBottomUp[Arg];
684 }
685
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000686 /// Attempt to find the PtrState object describing the bottom up state for
687 /// pointer Arg.
688 ptr_iterator findPtrBottomUpState(const Value *Arg) {
689 return PerPtrBottomUp.find(Arg);
690 }
691
John McCalld935e9c2011-06-15 23:37:01 +0000692 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000693 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000694 }
695
696 void clearTopDownPointers() {
697 PerPtrTopDown.clear();
698 }
699
700 void InitFromPred(const BBState &Other);
701 void InitFromSucc(const BBState &Other);
702 void MergePred(const BBState &Other);
703 void MergeSucc(const BBState &Other);
704
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000705 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000706 /// which pass through this block. This is only valid after both the
707 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000708 ///
709 /// Returns true if overflow occured. Returns false if overflow did not
710 /// occur.
711 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000712 assert(TopDownPathCount != 0);
713 assert(BottomUpPathCount != 0);
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000714 unsigned long long Product =
715 (unsigned long long)TopDownPathCount*BottomUpPathCount;
716 PathCount = Product;
717 // Overflow occured if any of the upper bits of Product are set.
718 return Product >> 32;
John McCalld935e9c2011-06-15 23:37:01 +0000719 }
Dan Gohman12130272011-08-12 00:26:31 +0000720
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000721 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000722 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000723 edge_iterator pred_begin() { return Preds.begin(); }
724 edge_iterator pred_end() { return Preds.end(); }
725 edge_iterator succ_begin() { return Succs.begin(); }
726 edge_iterator succ_end() { return Succs.end(); }
727
728 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
729 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
730
731 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000732 };
733}
734
735void BBState::InitFromPred(const BBState &Other) {
736 PerPtrTopDown = Other.PerPtrTopDown;
737 TopDownPathCount = Other.TopDownPathCount;
738}
739
740void BBState::InitFromSucc(const BBState &Other) {
741 PerPtrBottomUp = Other.PerPtrBottomUp;
742 BottomUpPathCount = Other.BottomUpPathCount;
743}
744
Michael Gottesman97e3df02013-01-14 00:35:14 +0000745/// The top-down traversal uses this to merge information about predecessors to
746/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000747void BBState::MergePred(const BBState &Other) {
748 // Other.TopDownPathCount can be 0, in which case it is either dead or a
749 // loop backedge. Loop backedges are special.
750 TopDownPathCount += Other.TopDownPathCount;
751
Michael Gottesman4385edf2013-01-14 01:47:53 +0000752 // Check for overflow. If we have overflow, fall back to conservative
753 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000754 if (TopDownPathCount < Other.TopDownPathCount) {
755 clearTopDownPointers();
756 return;
757 }
758
John McCalld935e9c2011-06-15 23:37:01 +0000759 // For each entry in the other set, if our set has an entry with the same key,
760 // merge the entries. Otherwise, copy the entry and merge it with an empty
761 // entry.
762 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
763 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
764 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
765 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
766 /*TopDown=*/true);
767 }
768
Dan Gohman7e315fc32011-08-11 21:06:32 +0000769 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000770 // same key, force it to merge with an empty entry.
771 for (ptr_iterator MI = top_down_ptr_begin(),
772 ME = top_down_ptr_end(); MI != ME; ++MI)
773 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
774 MI->second.Merge(PtrState(), /*TopDown=*/true);
775}
776
Michael Gottesman97e3df02013-01-14 00:35:14 +0000777/// The bottom-up traversal uses this to merge information about successors to
778/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000779void BBState::MergeSucc(const BBState &Other) {
780 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
781 // loop backedge. Loop backedges are special.
782 BottomUpPathCount += Other.BottomUpPathCount;
783
Michael Gottesman4385edf2013-01-14 01:47:53 +0000784 // Check for overflow. If we have overflow, fall back to conservative
785 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000786 if (BottomUpPathCount < Other.BottomUpPathCount) {
787 clearBottomUpPointers();
788 return;
789 }
790
John McCalld935e9c2011-06-15 23:37:01 +0000791 // For each entry in the other set, if our set has an entry with the
792 // same key, merge the entries. Otherwise, copy the entry and merge
793 // it with an empty entry.
794 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
795 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
796 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
797 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
798 /*TopDown=*/false);
799 }
800
Dan Gohman7e315fc32011-08-11 21:06:32 +0000801 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000802 // with the same key, force it to merge with an empty entry.
803 for (ptr_iterator MI = bottom_up_ptr_begin(),
804 ME = bottom_up_ptr_end(); MI != ME; ++MI)
805 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
806 MI->second.Merge(PtrState(), /*TopDown=*/false);
807}
808
Michael Gottesman81b1d432013-03-26 00:42:04 +0000809// Only enable ARC Annotations if we are building a debug version of
810// libObjCARCOpts.
811#ifndef NDEBUG
812#define ARC_ANNOTATIONS
813#endif
814
815// Define some macros along the lines of DEBUG and some helper functions to make
816// it cleaner to create annotations in the source code and to no-op when not
817// building in debug mode.
818#ifdef ARC_ANNOTATIONS
819
820#include "llvm/Support/CommandLine.h"
821
822/// Enable/disable ARC sequence annotations.
823static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000824EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
825 cl::desc("Enable emission of arc data flow analysis "
826 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000827static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000828DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
829 cl::desc("Disable check for cfg hazards when "
830 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000831static cl::opt<std::string>
832ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
833 cl::init(""),
834 cl::desc("filter out all data flow annotations "
835 "but those that apply to the given "
836 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000837
838/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
839/// instruction so that we can track backwards when post processing via the llvm
840/// arc annotation processor tool. If the function is an
841static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
842 Value *Ptr) {
843 MDString *Hash = 0;
844
845 // If pointer is a result of an instruction and it does not have a source
846 // MDNode it, attach a new MDNode onto it. If pointer is a result of
847 // an instruction and does have a source MDNode attached to it, return a
848 // reference to said Node. Otherwise just return 0.
849 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
850 MDNode *Node;
851 if (!(Node = Inst->getMetadata(NodeId))) {
852 // We do not have any node. Generate and attatch the hash MDString to the
853 // instruction.
854
855 // We just use an MDString to ensure that this metadata gets written out
856 // of line at the module level and to provide a very simple format
857 // encoding the information herein. Both of these makes it simpler to
858 // parse the annotations by a simple external program.
859 std::string Str;
860 raw_string_ostream os(Str);
861 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
862 << Inst->getName() << ")";
863
864 Hash = MDString::get(Inst->getContext(), os.str());
865 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
866 } else {
867 // We have a node. Grab its hash and return it.
868 assert(Node->getNumOperands() == 1 &&
869 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
870 Hash = cast<MDString>(Node->getOperand(0));
871 }
872 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
873 std::string str;
874 raw_string_ostream os(str);
875 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
876 << ")";
877 Hash = MDString::get(Arg->getContext(), os.str());
878 }
879
880 return Hash;
881}
882
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000883static std::string SequenceToString(Sequence A) {
884 std::string str;
885 raw_string_ostream os(str);
886 os << A;
887 return os.str();
888}
889
Michael Gottesman81b1d432013-03-26 00:42:04 +0000890/// Helper function to change a Sequence into a String object using our overload
891/// for raw_ostream so we only have printing code in one location.
892static MDString *SequenceToMDString(LLVMContext &Context,
893 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000894 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000895}
896
897/// A simple function to generate a MDNode which describes the change in state
898/// for Value *Ptr caused by Instruction *Inst.
899static void AppendMDNodeToInstForPtr(unsigned NodeId,
900 Instruction *Inst,
901 Value *Ptr,
902 MDString *PtrSourceMDNodeID,
903 Sequence OldSeq,
904 Sequence NewSeq) {
905 MDNode *Node = 0;
906 Value *tmp[3] = {PtrSourceMDNodeID,
907 SequenceToMDString(Inst->getContext(),
908 OldSeq),
909 SequenceToMDString(Inst->getContext(),
910 NewSeq)};
911 Node = MDNode::get(Inst->getContext(),
912 ArrayRef<Value*>(tmp, 3));
913
914 Inst->setMetadata(NodeId, Node);
915}
916
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000917/// Add to the beginning of the basic block llvm.ptr.annotations which show the
918/// state of a pointer at the entrance to a basic block.
919static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
920 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000921 // If we have a target identifier, make sure that we match it before
922 // continuing.
923 if(!ARCAnnotationTargetIdentifier.empty() &&
924 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
925 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000926
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000927 Module *M = BB->getParent()->getParent();
928 LLVMContext &C = M->getContext();
929 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
930 Type *I8XX = PointerType::getUnqual(I8X);
931 Type *Params[] = {I8XX, I8XX};
932 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
933 ArrayRef<Type*>(Params, 2),
934 /*isVarArg=*/false);
935 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000936
937 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
938
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000939 Value *PtrName;
940 StringRef Tmp = Ptr->getName();
941 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
942 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
943 Tmp + "_STR");
944 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000945 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000946 }
947
948 Value *S;
949 std::string SeqStr = SequenceToString(Seq);
950 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
951 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
952 SeqStr + "_STR");
953 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
954 cast<Constant>(ActualPtrName), SeqStr);
955 }
956
957 Builder.CreateCall2(Callee, PtrName, S);
958}
959
960/// Add to the end of the basic block llvm.ptr.annotations which show the state
961/// of the pointer at the bottom of the basic block.
962static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
963 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000964 // If we have a target identifier, make sure that we match it before emitting
965 // an annotation.
966 if(!ARCAnnotationTargetIdentifier.empty() &&
967 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
968 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000969
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000970 Module *M = BB->getParent()->getParent();
971 LLVMContext &C = M->getContext();
972 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
973 Type *I8XX = PointerType::getUnqual(I8X);
974 Type *Params[] = {I8XX, I8XX};
975 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
976 ArrayRef<Type*>(Params, 2),
977 /*isVarArg=*/false);
978 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000979
980 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
981
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000982 Value *PtrName;
983 StringRef Tmp = Ptr->getName();
984 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
985 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
986 Tmp + "_STR");
987 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000988 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000989 }
990
991 Value *S;
992 std::string SeqStr = SequenceToString(Seq);
993 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
994 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
995 SeqStr + "_STR");
996 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
997 cast<Constant>(ActualPtrName), SeqStr);
998 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000999 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001000}
1001
Michael Gottesman81b1d432013-03-26 00:42:04 +00001002/// Adds a source annotation to pointer and a state change annotation to Inst
1003/// referencing the source annotation and the old/new state of pointer.
1004static void GenerateARCAnnotation(unsigned InstMDId,
1005 unsigned PtrMDId,
1006 Instruction *Inst,
1007 Value *Ptr,
1008 Sequence OldSeq,
1009 Sequence NewSeq) {
1010 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001011 // If we have a target identifier, make sure that we match it before
1012 // emitting an annotation.
1013 if(!ARCAnnotationTargetIdentifier.empty() &&
1014 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1015 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001016
Michael Gottesman81b1d432013-03-26 00:42:04 +00001017 // First generate the source annotation on our pointer. This will return an
1018 // MDString* if Ptr actually comes from an instruction implying we can put
1019 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1020 // then we know that our pointer is from an Argument so we put a reference
1021 // to the argument number.
1022 //
1023 // The point of this is to make it easy for the
1024 // llvm-arc-annotation-processor tool to cross reference where the source
1025 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1026 // information via debug info for backends to use (since why would anyone
1027 // need such a thing from LLVM IR besides in non standard cases
1028 // [i.e. this]).
1029 MDString *SourcePtrMDNode =
1030 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1031 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1032 NewSeq);
1033 }
1034}
1035
1036// The actual interface for accessing the above functionality is defined via
1037// some simple macros which are defined below. We do this so that the user does
1038// not need to pass in what metadata id is needed resulting in cleaner code and
1039// additionally since it provides an easy way to conditionally no-op all
1040// annotation support in a non-debug build.
1041
1042/// Use this macro to annotate a sequence state change when processing
1043/// instructions bottom up,
1044#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1045 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1046 ARCAnnotationProvenanceSourceMDKind, (inst), \
1047 const_cast<Value*>(ptr), (old), (new))
1048/// Use this macro to annotate a sequence state change when processing
1049/// instructions top down.
1050#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1051 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1052 ARCAnnotationProvenanceSourceMDKind, (inst), \
1053 const_cast<Value*>(ptr), (old), (new))
1054
Michael Gottesman43e7e002013-04-03 22:41:59 +00001055#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1056 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001057 if (EnableARCAnnotations) { \
1058 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001059 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001060 Value *Ptr = const_cast<Value*>(I->first); \
1061 Sequence Seq = I->second.GetSeq(); \
1062 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1063 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001064 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001065 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001066
Michael Gottesman89279f82013-04-05 18:10:41 +00001067#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001068 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1069 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001070#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1071 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001072 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001073#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1074 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001075 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001076#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1077 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001078 Terminator, top_down)
1079
Michael Gottesman81b1d432013-03-26 00:42:04 +00001080#else // !ARC_ANNOTATION
1081// If annotations are off, noop.
1082#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1083#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001084#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1085#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1086#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1087#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001088#endif // !ARC_ANNOTATION
1089
John McCalld935e9c2011-06-15 23:37:01 +00001090namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001091 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001092 class ObjCARCOpt : public FunctionPass {
1093 bool Changed;
1094 ProvenanceAnalysis PA;
1095
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001096 // This is used to track if a pointer is stored into an alloca.
1097 DenseSet<const Value *> MultiOwnersSet;
1098
Michael Gottesman97e3df02013-01-14 00:35:14 +00001099 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001100 bool Run;
1101
Michael Gottesman97e3df02013-01-14 00:35:14 +00001102 /// Declarations for ObjC runtime functions, for use in creating calls to
1103 /// them. These are initialized lazily to avoid cluttering up the Module
1104 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001105
Michael Gottesman97e3df02013-01-14 00:35:14 +00001106 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1107 Constant *AutoreleaseRVCallee;
1108 /// Declaration for ObjC runtime function objc_release.
1109 Constant *ReleaseCallee;
1110 /// Declaration for ObjC runtime function objc_retain.
1111 Constant *RetainCallee;
1112 /// Declaration for ObjC runtime function objc_retainBlock.
1113 Constant *RetainBlockCallee;
1114 /// Declaration for ObjC runtime function objc_autorelease.
1115 Constant *AutoreleaseCallee;
1116
1117 /// Flags which determine whether each of the interesting runtine functions
1118 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001119 unsigned UsedInThisFunction;
1120
Michael Gottesman97e3df02013-01-14 00:35:14 +00001121 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001122 unsigned ImpreciseReleaseMDKind;
1123
Michael Gottesman97e3df02013-01-14 00:35:14 +00001124 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001125 unsigned CopyOnEscapeMDKind;
1126
Michael Gottesman97e3df02013-01-14 00:35:14 +00001127 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001128 unsigned NoObjCARCExceptionsMDKind;
1129
Michael Gottesman81b1d432013-03-26 00:42:04 +00001130#ifdef ARC_ANNOTATIONS
1131 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1132 unsigned ARCAnnotationBottomUpMDKind;
1133 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1134 unsigned ARCAnnotationTopDownMDKind;
1135 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1136 unsigned ARCAnnotationProvenanceSourceMDKind;
1137#endif // ARC_ANNOATIONS
1138
John McCalld935e9c2011-06-15 23:37:01 +00001139 Constant *getAutoreleaseRVCallee(Module *M);
1140 Constant *getReleaseCallee(Module *M);
1141 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001142 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001143 Constant *getAutoreleaseCallee(Module *M);
1144
Dan Gohman728db492012-01-13 00:39:07 +00001145 bool IsRetainBlockOptimizable(const Instruction *Inst);
1146
John McCalld935e9c2011-06-15 23:37:01 +00001147 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001148 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1149 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001150 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1151 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001152 void OptimizeIndividualCalls(Function &F);
1153
1154 void CheckForCFGHazards(const BasicBlock *BB,
1155 DenseMap<const BasicBlock *, BBState> &BBStates,
1156 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001157 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001158 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001159 MapVector<Value *, RRInfo> &Retains,
1160 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001161 bool VisitBottomUp(BasicBlock *BB,
1162 DenseMap<const BasicBlock *, BBState> &BBStates,
1163 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001164 bool VisitInstructionTopDown(Instruction *Inst,
1165 DenseMap<Value *, RRInfo> &Releases,
1166 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001167 bool VisitTopDown(BasicBlock *BB,
1168 DenseMap<const BasicBlock *, BBState> &BBStates,
1169 DenseMap<Value *, RRInfo> &Releases);
1170 bool Visit(Function &F,
1171 DenseMap<const BasicBlock *, BBState> &BBStates,
1172 MapVector<Value *, RRInfo> &Retains,
1173 DenseMap<Value *, RRInfo> &Releases);
1174
1175 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1176 MapVector<Value *, RRInfo> &Retains,
1177 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001178 SmallVectorImpl<Instruction *> &DeadInsts,
1179 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001180
Michael Gottesman9de6f962013-01-22 21:49:00 +00001181 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1182 MapVector<Value *, RRInfo> &Retains,
1183 DenseMap<Value *, RRInfo> &Releases,
1184 Module *M,
1185 SmallVector<Instruction *, 4> &NewRetains,
1186 SmallVector<Instruction *, 4> &NewReleases,
1187 SmallVector<Instruction *, 8> &DeadInsts,
1188 RRInfo &RetainsToMove,
1189 RRInfo &ReleasesToMove,
1190 Value *Arg,
1191 bool KnownSafe,
1192 bool &AnyPairsCompletelyEliminated);
1193
John McCalld935e9c2011-06-15 23:37:01 +00001194 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1195 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001196 DenseMap<Value *, RRInfo> &Releases,
1197 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001198
1199 void OptimizeWeakCalls(Function &F);
1200
1201 bool OptimizeSequences(Function &F);
1202
1203 void OptimizeReturns(Function &F);
1204
Michael Gottesman9c118152013-04-29 06:16:57 +00001205#ifndef NDEBUG
1206 void GatherStatistics(Function &F, bool AfterOptimization = false);
1207#endif
1208
John McCalld935e9c2011-06-15 23:37:01 +00001209 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1210 virtual bool doInitialization(Module &M);
1211 virtual bool runOnFunction(Function &F);
1212 virtual void releaseMemory();
1213
1214 public:
1215 static char ID;
1216 ObjCARCOpt() : FunctionPass(ID) {
1217 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1218 }
1219 };
1220}
1221
1222char ObjCARCOpt::ID = 0;
1223INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1224 "objc-arc", "ObjC ARC optimization", false, false)
1225INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1226INITIALIZE_PASS_END(ObjCARCOpt,
1227 "objc-arc", "ObjC ARC optimization", false, false)
1228
1229Pass *llvm::createObjCARCOptPass() {
1230 return new ObjCARCOpt();
1231}
1232
1233void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1234 AU.addRequired<ObjCARCAliasAnalysis>();
1235 AU.addRequired<AliasAnalysis>();
1236 // ARC optimization doesn't currently split critical edges.
1237 AU.setPreservesCFG();
1238}
1239
Dan Gohman728db492012-01-13 00:39:07 +00001240bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1241 // Without the magic metadata tag, we have to assume this might be an
1242 // objc_retainBlock call inserted to convert a block pointer to an id,
1243 // in which case it really is needed.
1244 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1245 return false;
1246
1247 // If the pointer "escapes" (not including being used in a call),
1248 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001249 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001250 return false;
1251
1252 // Otherwise, it's not needed.
1253 return true;
1254}
1255
John McCalld935e9c2011-06-15 23:37:01 +00001256Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1257 if (!AutoreleaseRVCallee) {
1258 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001259 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001260 Type *Params[] = { I8X };
1261 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001262 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001263 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1264 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001265 AutoreleaseRVCallee =
1266 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001267 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001268 }
1269 return AutoreleaseRVCallee;
1270}
1271
1272Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1273 if (!ReleaseCallee) {
1274 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001276 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001277 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1278 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001279 ReleaseCallee =
1280 M->getOrInsertFunction(
1281 "objc_release",
1282 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001283 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001284 }
1285 return ReleaseCallee;
1286}
1287
1288Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1289 if (!RetainCallee) {
1290 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001291 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001292 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001293 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1294 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001295 RetainCallee =
1296 M->getOrInsertFunction(
1297 "objc_retain",
1298 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001299 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001300 }
1301 return RetainCallee;
1302}
1303
Dan Gohman6320f522011-07-22 22:29:21 +00001304Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1305 if (!RetainBlockCallee) {
1306 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001307 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001308 // objc_retainBlock is not nounwind because it calls user copy constructors
1309 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001310 RetainBlockCallee =
1311 M->getOrInsertFunction(
1312 "objc_retainBlock",
1313 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001314 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001315 }
1316 return RetainBlockCallee;
1317}
1318
John McCalld935e9c2011-06-15 23:37:01 +00001319Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1320 if (!AutoreleaseCallee) {
1321 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001322 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001323 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001324 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1325 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001326 AutoreleaseCallee =
1327 M->getOrInsertFunction(
1328 "objc_autorelease",
1329 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001330 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001331 }
1332 return AutoreleaseCallee;
1333}
1334
Michael Gottesman97e3df02013-01-14 00:35:14 +00001335/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1336/// not a return value. Or, if it can be paired with an
1337/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001338bool
1339ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001340 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001341 const Value *Arg = GetObjCArg(RetainRV);
1342 ImmutableCallSite CS(Arg);
1343 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001344 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001345 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001346 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001347 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001348 if (&*I == RetainRV)
1349 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001350 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001351 BasicBlock *RetainRVParent = RetainRV->getParent();
1352 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001353 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001354 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001355 if (&*I == RetainRV)
1356 return false;
1357 }
John McCalld935e9c2011-06-15 23:37:01 +00001358 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001359 }
John McCalld935e9c2011-06-15 23:37:01 +00001360
1361 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1362 // pointer. In this case, we can delete the pair.
1363 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1364 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001365 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001366 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1367 GetObjCArg(I) == Arg) {
1368 Changed = true;
1369 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001370
Michael Gottesman89279f82013-04-05 18:10:41 +00001371 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1372 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001373
John McCalld935e9c2011-06-15 23:37:01 +00001374 EraseInstruction(I);
1375 EraseInstruction(RetainRV);
1376 return true;
1377 }
1378 }
1379
1380 // Turn it to a plain objc_retain.
1381 Changed = true;
1382 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001383
Michael Gottesman89279f82013-04-05 18:10:41 +00001384 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001385 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001386 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001387
John McCalld935e9c2011-06-15 23:37:01 +00001388 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001389
Michael Gottesman89279f82013-04-05 18:10:41 +00001390 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001391
John McCalld935e9c2011-06-15 23:37:01 +00001392 return false;
1393}
1394
Michael Gottesman97e3df02013-01-14 00:35:14 +00001395/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1396/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001397void
Michael Gottesman556ff612013-01-12 01:25:19 +00001398ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1399 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001400 // Check for a return of the pointer value.
1401 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001402 SmallVector<const Value *, 2> Users;
1403 Users.push_back(Ptr);
1404 do {
1405 Ptr = Users.pop_back_val();
1406 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1407 UI != UE; ++UI) {
1408 const User *I = *UI;
1409 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1410 return;
1411 if (isa<BitCastInst>(I))
1412 Users.push_back(I);
1413 }
1414 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001415
1416 Changed = true;
1417 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001418
Michael Gottesman89279f82013-04-05 18:10:41 +00001419 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001420 "objc_autorelease since its operand is not used as a return "
1421 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001422 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001423
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001424 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1425 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001426 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001427 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001428 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001429
Michael Gottesman89279f82013-04-05 18:10:41 +00001430 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001431
John McCalld935e9c2011-06-15 23:37:01 +00001432}
1433
Michael Gottesman158fdf62013-03-28 20:11:19 +00001434// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1435// calls.
1436//
1437// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1438// does not escape (following the rules of block escaping), strength reduce the
1439// objc_retainBlock to an objc_retain.
1440//
1441// TODO: If an objc_retainBlock call is dominated period by a previous
1442// objc_retainBlock call, strength reduce the objc_retainBlock to an
1443// objc_retain.
1444bool
1445ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1446 InstructionClass &Class) {
1447 assert(GetBasicInstructionClass(Inst) == Class);
1448 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001449
Michael Gottesman158fdf62013-03-28 20:11:19 +00001450 // If we can not optimize Inst, return false.
1451 if (!IsRetainBlockOptimizable(Inst))
1452 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001453
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001454 Changed = true;
1455 ++NumPeeps;
1456
1457 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1458 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001459 CallInst *RetainBlock = cast<CallInst>(Inst);
1460 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1461 // Remove copy_on_escape metadata.
1462 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1463 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001464 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001465 return true;
1466}
1467
Michael Gottesman97e3df02013-01-14 00:35:14 +00001468/// Visit each call, one at a time, and make simplifications without doing any
1469/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001470void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001471 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001472 // Reset all the flags in preparation for recomputing them.
1473 UsedInThisFunction = 0;
1474
1475 // Visit all objc_* calls in F.
1476 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1477 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001478
John McCalld935e9c2011-06-15 23:37:01 +00001479 InstructionClass Class = GetBasicInstructionClass(Inst);
1480
Michael Gottesman89279f82013-04-05 18:10:41 +00001481 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001482
John McCalld935e9c2011-06-15 23:37:01 +00001483 switch (Class) {
1484 default: break;
1485
1486 // Delete no-op casts. These function calls have special semantics, but
1487 // the semantics are entirely implemented via lowering in the front-end,
1488 // so by the time they reach the optimizer, they are just no-op calls
1489 // which return their argument.
1490 //
1491 // There are gray areas here, as the ability to cast reference-counted
1492 // pointers to raw void* and back allows code to break ARC assumptions,
1493 // however these are currently considered to be unimportant.
1494 case IC_NoopCast:
1495 Changed = true;
1496 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001497 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001498 EraseInstruction(Inst);
1499 continue;
1500
1501 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1502 case IC_StoreWeak:
1503 case IC_LoadWeak:
1504 case IC_LoadWeakRetained:
1505 case IC_InitWeak:
1506 case IC_DestroyWeak: {
1507 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001508 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001509 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001510 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001511 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1512 Constant::getNullValue(Ty),
1513 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001514 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001515 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1516 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001517 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001518 CI->eraseFromParent();
1519 continue;
1520 }
1521 break;
1522 }
1523 case IC_CopyWeak:
1524 case IC_MoveWeak: {
1525 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001526 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1527 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001528 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001529 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001530 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1531 Constant::getNullValue(Ty),
1532 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001533
1534 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001535 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1536 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001537
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001538 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001539 CI->eraseFromParent();
1540 continue;
1541 }
1542 break;
1543 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001544 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001545 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001546 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001547 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001548 break;
1549 case IC_RetainRV:
1550 if (OptimizeRetainRVCall(F, Inst))
1551 continue;
1552 break;
1553 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001554 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001555 break;
1556 }
1557
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001558 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001559 if (IsAutorelease(Class) && Inst->use_empty()) {
1560 CallInst *Call = cast<CallInst>(Inst);
1561 const Value *Arg = Call->getArgOperand(0);
1562 Arg = FindSingleUseIdentifiedObject(Arg);
1563 if (Arg) {
1564 Changed = true;
1565 ++NumAutoreleases;
1566
1567 // Create the declaration lazily.
1568 LLVMContext &C = Inst->getContext();
1569 CallInst *NewCall =
1570 CallInst::Create(getReleaseCallee(F.getParent()),
1571 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001572 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001573
Michael Gottesman89279f82013-04-05 18:10:41 +00001574 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1575 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1576 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001577
John McCalld935e9c2011-06-15 23:37:01 +00001578 EraseInstruction(Call);
1579 Inst = NewCall;
1580 Class = IC_Release;
1581 }
1582 }
1583
1584 // For functions which can never be passed stack arguments, add
1585 // a tail keyword.
1586 if (IsAlwaysTail(Class)) {
1587 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001588 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1589 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001590 cast<CallInst>(Inst)->setTailCall();
1591 }
1592
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001593 // Ensure that functions that can never have a "tail" keyword due to the
1594 // semantics of ARC truly do not do so.
1595 if (IsNeverTail(Class)) {
1596 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001597 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001598 "\n");
1599 cast<CallInst>(Inst)->setTailCall(false);
1600 }
1601
John McCalld935e9c2011-06-15 23:37:01 +00001602 // Set nounwind as needed.
1603 if (IsNoThrow(Class)) {
1604 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001605 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1606 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001607 cast<CallInst>(Inst)->setDoesNotThrow();
1608 }
1609
1610 if (!IsNoopOnNull(Class)) {
1611 UsedInThisFunction |= 1 << Class;
1612 continue;
1613 }
1614
1615 const Value *Arg = GetObjCArg(Inst);
1616
1617 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001618 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001619 Changed = true;
1620 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001621 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1622 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001623 EraseInstruction(Inst);
1624 continue;
1625 }
1626
1627 // Keep track of which of retain, release, autorelease, and retain_block
1628 // are actually present in this function.
1629 UsedInThisFunction |= 1 << Class;
1630
1631 // If Arg is a PHI, and one or more incoming values to the
1632 // PHI are null, and the call is control-equivalent to the PHI, and there
1633 // are no relevant side effects between the PHI and the call, the call
1634 // could be pushed up to just those paths with non-null incoming values.
1635 // For now, don't bother splitting critical edges for this.
1636 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1637 Worklist.push_back(std::make_pair(Inst, Arg));
1638 do {
1639 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1640 Inst = Pair.first;
1641 Arg = Pair.second;
1642
1643 const PHINode *PN = dyn_cast<PHINode>(Arg);
1644 if (!PN) continue;
1645
1646 // Determine if the PHI has any null operands, or any incoming
1647 // critical edges.
1648 bool HasNull = false;
1649 bool HasCriticalEdges = false;
1650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1651 Value *Incoming =
1652 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001653 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001654 HasNull = true;
1655 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1656 .getNumSuccessors() != 1) {
1657 HasCriticalEdges = true;
1658 break;
1659 }
1660 }
1661 // If we have null operands and no critical edges, optimize.
1662 if (!HasCriticalEdges && HasNull) {
1663 SmallPtrSet<Instruction *, 4> DependingInstructions;
1664 SmallPtrSet<const BasicBlock *, 4> Visited;
1665
1666 // Check that there is nothing that cares about the reference
1667 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001668 switch (Class) {
1669 case IC_Retain:
1670 case IC_RetainBlock:
1671 // These can always be moved up.
1672 break;
1673 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001674 // These can't be moved across things that care about the retain
1675 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001676 FindDependencies(NeedsPositiveRetainCount, Arg,
1677 Inst->getParent(), Inst,
1678 DependingInstructions, Visited, PA);
1679 break;
1680 case IC_Autorelease:
1681 // These can't be moved across autorelease pool scope boundaries.
1682 FindDependencies(AutoreleasePoolBoundary, Arg,
1683 Inst->getParent(), Inst,
1684 DependingInstructions, Visited, PA);
1685 break;
1686 case IC_RetainRV:
1687 case IC_AutoreleaseRV:
1688 // Don't move these; the RV optimization depends on the autoreleaseRV
1689 // being tail called, and the retainRV being immediately after a call
1690 // (which might still happen if we get lucky with codegen layout, but
1691 // it's not worth taking the chance).
1692 continue;
1693 default:
1694 llvm_unreachable("Invalid dependence flavor");
1695 }
1696
John McCalld935e9c2011-06-15 23:37:01 +00001697 if (DependingInstructions.size() == 1 &&
1698 *DependingInstructions.begin() == PN) {
1699 Changed = true;
1700 ++NumPartialNoops;
1701 // Clone the call into each predecessor that has a non-null value.
1702 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001703 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1705 Value *Incoming =
1706 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001707 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001708 CallInst *Clone = cast<CallInst>(CInst->clone());
1709 Value *Op = PN->getIncomingValue(i);
1710 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1711 if (Op->getType() != ParamTy)
1712 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1713 Clone->setArgOperand(0, Op);
1714 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001715
Michael Gottesman89279f82013-04-05 18:10:41 +00001716 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001717 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001718 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001719 Worklist.push_back(std::make_pair(Clone, Incoming));
1720 }
1721 }
1722 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001723 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001724 EraseInstruction(CInst);
1725 continue;
1726 }
1727 }
1728 } while (!Worklist.empty());
1729 }
1730}
1731
Michael Gottesman323964c2013-04-18 05:39:45 +00001732/// If we have a top down pointer in the S_Use state, make sure that there are
1733/// no CFG hazards by checking the states of various bottom up pointers.
1734static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1735 const bool SuccSRRIKnownSafe,
1736 PtrState &S,
1737 bool &SomeSuccHasSame,
1738 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001739 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001740 bool &ShouldContinue) {
1741 switch (SuccSSeq) {
1742 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001743 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001744 S.ClearSequenceProgress();
1745 break;
1746 }
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001747 S.RRI.CFGHazardAfflicted = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001748 ShouldContinue = true;
1749 break;
1750 }
1751 case S_Use:
1752 SomeSuccHasSame = true;
1753 break;
1754 case S_Stop:
1755 case S_Release:
1756 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001757 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001758 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001759 else
1760 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001761 break;
1762 case S_Retain:
1763 llvm_unreachable("bottom-up pointer in retain state!");
1764 case S_None:
1765 llvm_unreachable("This should have been handled earlier.");
1766 }
1767}
1768
1769/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1770/// there are no CFG hazards by checking the states of various bottom up
1771/// pointers.
1772static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1773 const bool SuccSRRIKnownSafe,
1774 PtrState &S,
1775 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001776 bool &AllSuccsHaveSame,
1777 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001778 switch (SuccSSeq) {
1779 case S_CanRelease:
1780 SomeSuccHasSame = true;
1781 break;
1782 case S_Stop:
1783 case S_Release:
1784 case S_MovableRelease:
1785 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001786 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001787 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001788 else
1789 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001790 break;
1791 case S_Retain:
1792 llvm_unreachable("bottom-up pointer in retain state!");
1793 case S_None:
1794 llvm_unreachable("This should have been handled earlier.");
1795 }
1796}
1797
Michael Gottesman97e3df02013-01-14 00:35:14 +00001798/// Check for critical edges, loop boundaries, irreducible control flow, or
1799/// other CFG structures where moving code across the edge would result in it
1800/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001801void
1802ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1803 DenseMap<const BasicBlock *, BBState> &BBStates,
1804 BBState &MyStates) const {
1805 // If any top-down local-use or possible-dec has a succ which is earlier in
1806 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001807 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001808 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1809 PtrState &S = I->second;
1810 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001811
Michael Gottesman323964c2013-04-18 05:39:45 +00001812 // We only care about S_Retain, S_CanRelease, and S_Use.
1813 if (Seq == S_None)
1814 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001815
Michael Gottesman323964c2013-04-18 05:39:45 +00001816 // Make sure that if extra top down states are added in the future that this
1817 // code is updated to handle it.
1818 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1819 "Unknown top down sequence state.");
1820
1821 const Value *Arg = I->first;
1822 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1823 bool SomeSuccHasSame = false;
1824 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001825 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001826
1827 succ_const_iterator SI(TI), SE(TI, false);
1828
1829 for (; SI != SE; ++SI) {
1830 // If VisitBottomUp has pointer information for this successor, take
1831 // what we know about it.
1832 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1833 BBStates.find(*SI);
1834 assert(BBI != BBStates.end());
1835 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1836 const Sequence SuccSSeq = SuccS.GetSeq();
1837
1838 // If bottom up, the pointer is in an S_None state, clear the sequence
1839 // progress since the sequence in the bottom up state finished
1840 // suggesting a mismatch in between retains/releases. This is true for
1841 // all three cases that we are handling here: S_Retain, S_Use, and
1842 // S_CanRelease.
1843 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001844 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001845 continue;
1846 }
1847
1848 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1849 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001850 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001851
1852 // *NOTE* We do not use Seq from above here since we are allowing for
1853 // S.GetSeq() to change while we are visiting basic blocks.
1854 switch(S.GetSeq()) {
1855 case S_Use: {
1856 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001857 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1858 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001859 ShouldContinue);
1860 if (ShouldContinue)
1861 continue;
1862 break;
1863 }
1864 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001865 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1866 SomeSuccHasSame, AllSuccsHaveSame,
1867 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001868 break;
1869 }
1870 case S_Retain:
1871 case S_None:
1872 case S_Stop:
1873 case S_Release:
1874 case S_MovableRelease:
1875 break;
1876 }
John McCalld935e9c2011-06-15 23:37:01 +00001877 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001878
1879 // If the state at the other end of any of the successor edges
1880 // matches the current state, require all edges to match. This
1881 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001882 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001883 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001884 } else if (NotAllSeqEqualButKnownSafe) {
1885 // If we would have cleared the state foregoing the fact that we are known
1886 // safe, stop code motion. This is because whether or not it is safe to
1887 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1888 // are allowed to perform code motion.
1889 S.RRI.CFGHazardAfflicted = true;
1890 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001891 }
John McCalld935e9c2011-06-15 23:37:01 +00001892}
1893
1894bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001895ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001896 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001897 MapVector<Value *, RRInfo> &Retains,
1898 BBState &MyStates) {
1899 bool NestingDetected = false;
1900 InstructionClass Class = GetInstructionClass(Inst);
1901 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001902
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001903 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001904
Dan Gohman817a7c62012-03-22 18:24:56 +00001905 switch (Class) {
1906 case IC_Release: {
1907 Arg = GetObjCArg(Inst);
1908
1909 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1910
1911 // If we see two releases in a row on the same pointer. If so, make
1912 // a note, and we'll cicle back to revisit it after we've
1913 // hopefully eliminated the second release, which may allow us to
1914 // eliminate the first release too.
1915 // Theoretically we could implement removal of nested retain+release
1916 // pairs by making PtrState hold a stack of states, but this is
1917 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001918 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001919 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001920 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001921 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001922
Dan Gohman817a7c62012-03-22 18:24:56 +00001923 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001924 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1925 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1926 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001927 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman93132252013-06-21 06:59:02 +00001928 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001929 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Dan Gohman817a7c62012-03-22 18:24:56 +00001930 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001931 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001932 break;
1933 }
1934 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001935 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1936 // objc_retainBlocks to objc_retains. Thus at this point any
1937 // objc_retainBlocks that we see are not optimizable.
1938 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001939 case IC_Retain:
1940 case IC_RetainRV: {
1941 Arg = GetObjCArg(Inst);
1942
1943 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001944 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001945
Michael Gottesman81b1d432013-03-26 00:42:04 +00001946 Sequence OldSeq = S.GetSeq();
1947 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001948 case S_Stop:
1949 case S_Release:
1950 case S_MovableRelease:
1951 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001952 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1953 // imprecise release, clear our reverse insertion points.
1954 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1955 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001956 // FALL THROUGH
1957 case S_CanRelease:
1958 // Don't do retain+release tracking for IC_RetainRV, because it's
1959 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001960 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001961 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001962 S.ClearSequenceProgress();
1963 break;
1964 case S_None:
1965 break;
1966 case S_Retain:
1967 llvm_unreachable("bottom-up pointer in retain state!");
1968 }
Michael Gottesman79249972013-04-05 23:46:45 +00001969 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001970 // A retain moving bottom up can be a use.
1971 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001972 }
1973 case IC_AutoreleasepoolPop:
1974 // Conservatively, clear MyStates for all known pointers.
1975 MyStates.clearBottomUpPointers();
1976 return NestingDetected;
1977 case IC_AutoreleasepoolPush:
1978 case IC_None:
1979 // These are irrelevant.
1980 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001981 case IC_User:
1982 // If we have a store into an alloca of a pointer we are tracking, the
1983 // pointer has multiple owners implying that we must be more conservative.
1984 //
1985 // This comes up in the context of a pointer being ``KnownSafe''. In the
1986 // presense of a block being initialized, the frontend will emit the
1987 // objc_retain on the original pointer and the release on the pointer loaded
1988 // from the alloca. The optimizer will through the provenance analysis
1989 // realize that the two are related, but since we only require KnownSafe in
1990 // one direction, will match the inner retain on the original pointer with
1991 // the guard release on the original pointer. This is fixed by ensuring that
1992 // in the presense of allocas we only unconditionally remove pointers if
1993 // both our retain and our release are KnownSafe.
1994 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1995 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1996 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1997 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1998 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001999 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002000 }
2001 }
2002 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002003 default:
2004 break;
2005 }
2006
2007 // Consider any other possible effects of this instruction on each
2008 // pointer being tracked.
2009 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2010 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2011 const Value *Ptr = MI->first;
2012 if (Ptr == Arg)
2013 continue; // Handled above.
2014 PtrState &S = MI->second;
2015 Sequence Seq = S.GetSeq();
2016
2017 // Check for possible releases.
2018 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002019 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2020 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002021 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002022 switch (Seq) {
2023 case S_Use:
2024 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002025 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00002026 continue;
2027 case S_CanRelease:
2028 case S_Release:
2029 case S_MovableRelease:
2030 case S_Stop:
2031 case S_None:
2032 break;
2033 case S_Retain:
2034 llvm_unreachable("bottom-up pointer in retain state!");
2035 }
2036 }
2037
2038 // Check for possible direct uses.
2039 switch (Seq) {
2040 case S_Release:
2041 case S_MovableRelease:
2042 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002043 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2044 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002045 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002046 // If this is an invoke instruction, we're scanning it as part of
2047 // one of its successor blocks, since we can't insert code after it
2048 // in its own block, and we don't want to split critical edges.
2049 if (isa<InvokeInst>(Inst))
2050 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2051 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002052 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002053 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002054 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002055 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002056 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2057 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002058 // Non-movable releases depend on any possible objc pointer use.
2059 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002060 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00002061 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002062 // As above; handle invoke specially.
2063 if (isa<InvokeInst>(Inst))
2064 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2065 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002066 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002067 }
2068 break;
2069 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002070 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002071 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2072 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002073 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002074 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2075 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002076 break;
2077 case S_CanRelease:
2078 case S_Use:
2079 case S_None:
2080 break;
2081 case S_Retain:
2082 llvm_unreachable("bottom-up pointer in retain state!");
2083 }
2084 }
2085
2086 return NestingDetected;
2087}
2088
2089bool
John McCalld935e9c2011-06-15 23:37:01 +00002090ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2091 DenseMap<const BasicBlock *, BBState> &BBStates,
2092 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002093
2094 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002095
John McCalld935e9c2011-06-15 23:37:01 +00002096 bool NestingDetected = false;
2097 BBState &MyStates = BBStates[BB];
2098
2099 // Merge the states from each successor to compute the initial state
2100 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002101 BBState::edge_iterator SI(MyStates.succ_begin()),
2102 SE(MyStates.succ_end());
2103 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002104 const BasicBlock *Succ = *SI;
2105 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2106 assert(I != BBStates.end());
2107 MyStates.InitFromSucc(I->second);
2108 ++SI;
2109 for (; SI != SE; ++SI) {
2110 Succ = *SI;
2111 I = BBStates.find(Succ);
2112 assert(I != BBStates.end());
2113 MyStates.MergeSucc(I->second);
2114 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002115 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002116
Michael Gottesman43e7e002013-04-03 22:41:59 +00002117 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002118 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002119 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002120
John McCalld935e9c2011-06-15 23:37:01 +00002121 // Visit all the instructions, bottom-up.
2122 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2123 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002124
2125 // Invoke instructions are visited as part of their successors (below).
2126 if (isa<InvokeInst>(Inst))
2127 continue;
2128
Michael Gottesman89279f82013-04-05 18:10:41 +00002129 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002130
Dan Gohman5c70fad2012-03-23 17:47:54 +00002131 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2132 }
2133
Dan Gohmandae33492012-04-27 18:56:31 +00002134 // If there's a predecessor with an invoke, visit the invoke as if it were
2135 // part of this block, since we can't insert code after an invoke in its own
2136 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002137 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2138 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002139 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002140 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2141 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002142 }
John McCalld935e9c2011-06-15 23:37:01 +00002143
Michael Gottesman43e7e002013-04-03 22:41:59 +00002144 // If ARC Annotations are enabled, output the current state of pointers at the
2145 // top of the basic block.
2146 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002147
Dan Gohman817a7c62012-03-22 18:24:56 +00002148 return NestingDetected;
2149}
John McCalld935e9c2011-06-15 23:37:01 +00002150
Dan Gohman817a7c62012-03-22 18:24:56 +00002151bool
2152ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2153 DenseMap<Value *, RRInfo> &Releases,
2154 BBState &MyStates) {
2155 bool NestingDetected = false;
2156 InstructionClass Class = GetInstructionClass(Inst);
2157 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002158
Dan Gohman817a7c62012-03-22 18:24:56 +00002159 switch (Class) {
2160 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002161 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2162 // objc_retainBlocks to objc_retains. Thus at this point any
2163 // objc_retainBlocks that we see are not optimizable.
2164 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002165 case IC_Retain:
2166 case IC_RetainRV: {
2167 Arg = GetObjCArg(Inst);
2168
2169 PtrState &S = MyStates.getPtrTopDownState(Arg);
2170
2171 // Don't do retain+release tracking for IC_RetainRV, because it's
2172 // better to let it remain as the first instruction after a call.
2173 if (Class != IC_RetainRV) {
2174 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002175 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002176 // hopefully eliminated the second retain, which may allow us to
2177 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002178 // Theoretically we could implement removal of nested retain+release
2179 // pairs by making PtrState hold a stack of states, but this is
2180 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002181 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002182 NestingDetected = true;
2183
Michael Gottesman81b1d432013-03-26 00:42:04 +00002184 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002185 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002186 S.SetKnownSafe(S.HasKnownPositiveRefCount());
John McCalld935e9c2011-06-15 23:37:01 +00002187 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002188 }
John McCalld935e9c2011-06-15 23:37:01 +00002189
Dan Gohmandf476e52012-09-04 23:16:20 +00002190 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002191
2192 // A retain can be a potential use; procede to the generic checking
2193 // code below.
2194 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002195 }
2196 case IC_Release: {
2197 Arg = GetObjCArg(Inst);
2198
2199 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002200 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002201
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002202 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002203
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002204 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002205
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002206 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002207 case S_Retain:
2208 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002209 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2210 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002211 // FALL THROUGH
2212 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002213 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002214 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Dan Gohman817a7c62012-03-22 18:24:56 +00002215 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002216 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002217 S.ClearSequenceProgress();
2218 break;
2219 case S_None:
2220 break;
2221 case S_Stop:
2222 case S_Release:
2223 case S_MovableRelease:
2224 llvm_unreachable("top-down pointer in release state!");
2225 }
2226 break;
2227 }
2228 case IC_AutoreleasepoolPop:
2229 // Conservatively, clear MyStates for all known pointers.
2230 MyStates.clearTopDownPointers();
2231 return NestingDetected;
2232 case IC_AutoreleasepoolPush:
2233 case IC_None:
2234 // These are irrelevant.
2235 return NestingDetected;
2236 default:
2237 break;
2238 }
2239
2240 // Consider any other possible effects of this instruction on each
2241 // pointer being tracked.
2242 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2243 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2244 const Value *Ptr = MI->first;
2245 if (Ptr == Arg)
2246 continue; // Handled above.
2247 PtrState &S = MI->second;
2248 Sequence Seq = S.GetSeq();
2249
2250 // Check for possible releases.
2251 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002252 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002253 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002254 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002255 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002256 case S_Retain:
2257 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002258 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002259 assert(S.RRI.ReverseInsertPts.empty());
2260 S.RRI.ReverseInsertPts.insert(Inst);
2261
2262 // One call can't cause a transition from S_Retain to S_CanRelease
2263 // and S_CanRelease to S_Use. If we've made the first transition,
2264 // we're done.
2265 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002266 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002267 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002268 case S_None:
2269 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002270 case S_Stop:
2271 case S_Release:
2272 case S_MovableRelease:
2273 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002274 }
2275 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002276
2277 // Check for possible direct uses.
2278 switch (Seq) {
2279 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002280 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002281 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2282 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002283 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002284 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2285 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002286 break;
2287 case S_Retain:
2288 case S_Use:
2289 case S_None:
2290 break;
2291 case S_Stop:
2292 case S_Release:
2293 case S_MovableRelease:
2294 llvm_unreachable("top-down pointer in release state!");
2295 }
John McCalld935e9c2011-06-15 23:37:01 +00002296 }
2297
2298 return NestingDetected;
2299}
2300
2301bool
2302ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2303 DenseMap<const BasicBlock *, BBState> &BBStates,
2304 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002305 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002306 bool NestingDetected = false;
2307 BBState &MyStates = BBStates[BB];
2308
2309 // Merge the states from each predecessor to compute the initial state
2310 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002311 BBState::edge_iterator PI(MyStates.pred_begin()),
2312 PE(MyStates.pred_end());
2313 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002314 const BasicBlock *Pred = *PI;
2315 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2316 assert(I != BBStates.end());
2317 MyStates.InitFromPred(I->second);
2318 ++PI;
2319 for (; PI != PE; ++PI) {
2320 Pred = *PI;
2321 I = BBStates.find(Pred);
2322 assert(I != BBStates.end());
2323 MyStates.MergePred(I->second);
2324 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002325 }
John McCalld935e9c2011-06-15 23:37:01 +00002326
Michael Gottesman43e7e002013-04-03 22:41:59 +00002327 // If ARC Annotations are enabled, output the current state of pointers at the
2328 // top of the basic block.
2329 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002330
John McCalld935e9c2011-06-15 23:37:01 +00002331 // Visit all the instructions, top-down.
2332 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2333 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002334
Michael Gottesman89279f82013-04-05 18:10:41 +00002335 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002336
Dan Gohman817a7c62012-03-22 18:24:56 +00002337 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002338 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002339
Michael Gottesman43e7e002013-04-03 22:41:59 +00002340 // If ARC Annotations are enabled, output the current state of pointers at the
2341 // bottom of the basic block.
2342 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002343
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002344#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002345 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002346#endif
John McCalld935e9c2011-06-15 23:37:01 +00002347 CheckForCFGHazards(BB, BBStates, MyStates);
2348 return NestingDetected;
2349}
2350
Dan Gohmana53a12c2011-12-12 19:42:25 +00002351static void
2352ComputePostOrders(Function &F,
2353 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002354 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2355 unsigned NoObjCARCExceptionsMDKind,
2356 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002357 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002358 SmallPtrSet<BasicBlock *, 16> Visited;
2359
2360 // Do DFS, computing the PostOrder.
2361 SmallPtrSet<BasicBlock *, 16> OnStack;
2362 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002363
2364 // Functions always have exactly one entry block, and we don't have
2365 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002366 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002367 BBState &MyStates = BBStates[EntryBB];
2368 MyStates.SetAsEntry();
2369 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2370 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002371 Visited.insert(EntryBB);
2372 OnStack.insert(EntryBB);
2373 do {
2374 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002375 BasicBlock *CurrBB = SuccStack.back().first;
2376 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2377 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002378
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002379 while (SuccStack.back().second != SE) {
2380 BasicBlock *SuccBB = *SuccStack.back().second++;
2381 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002382 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2383 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002384 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002385 BBState &SuccStates = BBStates[SuccBB];
2386 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002387 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002388 goto dfs_next_succ;
2389 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002390
2391 if (!OnStack.count(SuccBB)) {
2392 BBStates[CurrBB].addSucc(SuccBB);
2393 BBStates[SuccBB].addPred(CurrBB);
2394 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002395 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002396 OnStack.erase(CurrBB);
2397 PostOrder.push_back(CurrBB);
2398 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002399 } while (!SuccStack.empty());
2400
2401 Visited.clear();
2402
Dan Gohmana53a12c2011-12-12 19:42:25 +00002403 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002404 // Functions may have many exits, and there also blocks which we treat
2405 // as exits due to ignored edges.
2406 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2407 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2408 BasicBlock *ExitBB = I;
2409 BBState &MyStates = BBStates[ExitBB];
2410 if (!MyStates.isExit())
2411 continue;
2412
Dan Gohmandae33492012-04-27 18:56:31 +00002413 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002414
2415 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002416 Visited.insert(ExitBB);
2417 while (!PredStack.empty()) {
2418 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002419 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2420 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002421 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002422 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002423 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002424 goto reverse_dfs_next_succ;
2425 }
2426 }
2427 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2428 }
2429 }
2430}
2431
Michael Gottesman97e3df02013-01-14 00:35:14 +00002432// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002433bool
2434ObjCARCOpt::Visit(Function &F,
2435 DenseMap<const BasicBlock *, BBState> &BBStates,
2436 MapVector<Value *, RRInfo> &Retains,
2437 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002438
2439 // Use reverse-postorder traversals, because we magically know that loops
2440 // will be well behaved, i.e. they won't repeatedly call retain on a single
2441 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2442 // class here because we want the reverse-CFG postorder to consider each
2443 // function exit point, and we want to ignore selected cycle edges.
2444 SmallVector<BasicBlock *, 16> PostOrder;
2445 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002446 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2447 NoObjCARCExceptionsMDKind,
2448 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002449
2450 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002451 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002452 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002453 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2454 I != E; ++I)
2455 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002456
Dan Gohmana53a12c2011-12-12 19:42:25 +00002457 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002458 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002459 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2460 PostOrder.rbegin(), E = PostOrder.rend();
2461 I != E; ++I)
2462 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002463
2464 return TopDownNestingDetected && BottomUpNestingDetected;
2465}
2466
Michael Gottesman97e3df02013-01-14 00:35:14 +00002467/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002468void ObjCARCOpt::MoveCalls(Value *Arg,
2469 RRInfo &RetainsToMove,
2470 RRInfo &ReleasesToMove,
2471 MapVector<Value *, RRInfo> &Retains,
2472 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002473 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002474 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002475 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002476 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002477
Michael Gottesman89279f82013-04-05 18:10:41 +00002478 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002479
John McCalld935e9c2011-06-15 23:37:01 +00002480 // Insert the new retain and release calls.
2481 for (SmallPtrSet<Instruction *, 2>::const_iterator
2482 PI = ReleasesToMove.ReverseInsertPts.begin(),
2483 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2484 Instruction *InsertPt = *PI;
2485 Value *MyArg = ArgTy == ParamTy ? Arg :
2486 new BitCastInst(Arg, ParamTy, "", InsertPt);
2487 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002488 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002489 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002490 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002491
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002492 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002493 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002494 }
2495 for (SmallPtrSet<Instruction *, 2>::const_iterator
2496 PI = RetainsToMove.ReverseInsertPts.begin(),
2497 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002498 Instruction *InsertPt = *PI;
2499 Value *MyArg = ArgTy == ParamTy ? Arg :
2500 new BitCastInst(Arg, ParamTy, "", InsertPt);
2501 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2502 "", InsertPt);
2503 // Attach a clang.imprecise_release metadata tag, if appropriate.
2504 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2505 Call->setMetadata(ImpreciseReleaseMDKind, M);
2506 Call->setDoesNotThrow();
2507 if (ReleasesToMove.IsTailCallRelease)
2508 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002509
Michael Gottesman89279f82013-04-05 18:10:41 +00002510 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2511 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002512 }
2513
2514 // Delete the original retain and release calls.
2515 for (SmallPtrSet<Instruction *, 2>::const_iterator
2516 AI = RetainsToMove.Calls.begin(),
2517 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2518 Instruction *OrigRetain = *AI;
2519 Retains.blot(OrigRetain);
2520 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002521 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002522 }
2523 for (SmallPtrSet<Instruction *, 2>::const_iterator
2524 AI = ReleasesToMove.Calls.begin(),
2525 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2526 Instruction *OrigRelease = *AI;
2527 Releases.erase(OrigRelease);
2528 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002529 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002530 }
Michael Gottesman79249972013-04-05 23:46:45 +00002531
John McCalld935e9c2011-06-15 23:37:01 +00002532}
2533
Michael Gottesman9de6f962013-01-22 21:49:00 +00002534bool
2535ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2536 &BBStates,
2537 MapVector<Value *, RRInfo> &Retains,
2538 DenseMap<Value *, RRInfo> &Releases,
2539 Module *M,
2540 SmallVector<Instruction *, 4> &NewRetains,
2541 SmallVector<Instruction *, 4> &NewReleases,
2542 SmallVector<Instruction *, 8> &DeadInsts,
2543 RRInfo &RetainsToMove,
2544 RRInfo &ReleasesToMove,
2545 Value *Arg,
2546 bool KnownSafe,
2547 bool &AnyPairsCompletelyEliminated) {
2548 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002549 // is already incremented, we can similarly ignore possible decrements unless
2550 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002551 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002552 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002553 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002554
2555 // Connect the dots between the top-down-collected RetainsToMove and
2556 // bottom-up-collected ReleasesToMove to form sets of related calls.
2557 // This is an iterative process so that we connect multiple releases
2558 // to multiple retains if needed.
2559 unsigned OldDelta = 0;
2560 unsigned NewDelta = 0;
2561 unsigned OldCount = 0;
2562 unsigned NewCount = 0;
2563 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002564 for (;;) {
2565 for (SmallVectorImpl<Instruction *>::const_iterator
2566 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2567 Instruction *NewRetain = *NI;
2568 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2569 assert(It != Retains.end());
2570 const RRInfo &NewRetainRRI = It->second;
2571 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002572 MultipleOwners =
2573 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002574 for (SmallPtrSet<Instruction *, 2>::const_iterator
2575 LI = NewRetainRRI.Calls.begin(),
2576 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2577 Instruction *NewRetainRelease = *LI;
2578 DenseMap<Value *, RRInfo>::const_iterator Jt =
2579 Releases.find(NewRetainRelease);
2580 if (Jt == Releases.end())
2581 return false;
2582 const RRInfo &NewRetainReleaseRRI = Jt->second;
2583 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2584 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002585
2586 // If we overflow when we compute the path count, don't remove/move
2587 // anything.
2588 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2589 unsigned PathCount;
2590 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2591 return false;
2592 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002593
2594 // Merge the ReleaseMetadata and IsTailCallRelease values.
2595 if (FirstRelease) {
2596 ReleasesToMove.ReleaseMetadata =
2597 NewRetainReleaseRRI.ReleaseMetadata;
2598 ReleasesToMove.IsTailCallRelease =
2599 NewRetainReleaseRRI.IsTailCallRelease;
2600 FirstRelease = false;
2601 } else {
2602 if (ReleasesToMove.ReleaseMetadata !=
2603 NewRetainReleaseRRI.ReleaseMetadata)
2604 ReleasesToMove.ReleaseMetadata = 0;
2605 if (ReleasesToMove.IsTailCallRelease !=
2606 NewRetainReleaseRRI.IsTailCallRelease)
2607 ReleasesToMove.IsTailCallRelease = false;
2608 }
2609
2610 // Collect the optimal insertion points.
2611 if (!KnownSafe)
2612 for (SmallPtrSet<Instruction *, 2>::const_iterator
2613 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2614 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2615 RI != RE; ++RI) {
2616 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002617 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2618 // If we overflow when we compute the path count, don't
2619 // remove/move anything.
2620 const BBState &RIPBBState = BBStates[RIP->getParent()];
2621 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2622 return false;
2623 NewDelta -= PathCount;
2624 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002625 }
2626 NewReleases.push_back(NewRetainRelease);
2627 }
2628 }
2629 }
2630 NewRetains.clear();
2631 if (NewReleases.empty()) break;
2632
2633 // Back the other way.
2634 for (SmallVectorImpl<Instruction *>::const_iterator
2635 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2636 Instruction *NewRelease = *NI;
2637 DenseMap<Value *, RRInfo>::const_iterator It =
2638 Releases.find(NewRelease);
2639 assert(It != Releases.end());
2640 const RRInfo &NewReleaseRRI = It->second;
2641 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002642 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002643 for (SmallPtrSet<Instruction *, 2>::const_iterator
2644 LI = NewReleaseRRI.Calls.begin(),
2645 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2646 Instruction *NewReleaseRetain = *LI;
2647 MapVector<Value *, RRInfo>::const_iterator Jt =
2648 Retains.find(NewReleaseRetain);
2649 if (Jt == Retains.end())
2650 return false;
2651 const RRInfo &NewReleaseRetainRRI = Jt->second;
2652 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2653 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002654
2655 // If we overflow when we compute the path count, don't remove/move
2656 // anything.
2657 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2658 unsigned PathCount;
2659 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2660 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002661 OldDelta += PathCount;
2662 OldCount += PathCount;
2663
Michael Gottesman9de6f962013-01-22 21:49:00 +00002664 // Collect the optimal insertion points.
2665 if (!KnownSafe)
2666 for (SmallPtrSet<Instruction *, 2>::const_iterator
2667 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2668 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2669 RI != RE; ++RI) {
2670 Instruction *RIP = *RI;
2671 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002672 // If we overflow when we compute the path count, don't
2673 // remove/move anything.
2674 const BBState &RIPBBState = BBStates[RIP->getParent()];
2675 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2676 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002677 NewDelta += PathCount;
2678 NewCount += PathCount;
2679 }
2680 }
2681 NewRetains.push_back(NewReleaseRetain);
2682 }
2683 }
2684 }
2685 NewReleases.clear();
2686 if (NewRetains.empty()) break;
2687 }
2688
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002689 // If the pointer is known incremented in 1 direction and we do not have
2690 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2691 // to be known safe in both directions.
2692 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2693 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2694 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002695 RetainsToMove.ReverseInsertPts.clear();
2696 ReleasesToMove.ReverseInsertPts.clear();
2697 NewCount = 0;
2698 } else {
2699 // Determine whether the new insertion points we computed preserve the
2700 // balance of retain and release calls through the program.
2701 // TODO: If the fully aggressive solution isn't valid, try to find a
2702 // less aggressive solution which is.
2703 if (NewDelta != 0)
2704 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002705
2706 // At this point, we are not going to remove any RR pairs, but we still are
2707 // able to move RR pairs. If one of our pointers is afflicted with
2708 // CFGHazards, we cannot perform such code motion so exit early.
2709 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2710 ReleasesToMove.ReverseInsertPts.size();
2711 if (CFGHazardAfflicted && WillPerformCodeMotion)
2712 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002713 }
2714
2715 // Determine whether the original call points are balanced in the retain and
2716 // release calls through the program. If not, conservatively don't touch
2717 // them.
2718 // TODO: It's theoretically possible to do code motion in this case, as
2719 // long as the existing imbalances are maintained.
2720 if (OldDelta != 0)
2721 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002722
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002723#ifdef ARC_ANNOTATIONS
2724 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002725 if (EnableARCAnnotations)
2726 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002727#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002728
2729 Changed = true;
2730 assert(OldCount != 0 && "Unreachable code?");
2731 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002732 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002733 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002734
2735 // We can move calls!
2736 return true;
2737}
2738
Michael Gottesman97e3df02013-01-14 00:35:14 +00002739/// Identify pairings between the retains and releases, and delete and/or move
2740/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002741bool
2742ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2743 &BBStates,
2744 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002745 DenseMap<Value *, RRInfo> &Releases,
2746 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002747 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2748
John McCalld935e9c2011-06-15 23:37:01 +00002749 bool AnyPairsCompletelyEliminated = false;
2750 RRInfo RetainsToMove;
2751 RRInfo ReleasesToMove;
2752 SmallVector<Instruction *, 4> NewRetains;
2753 SmallVector<Instruction *, 4> NewReleases;
2754 SmallVector<Instruction *, 8> DeadInsts;
2755
Dan Gohman670f9372012-04-13 18:57:48 +00002756 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002757 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002758 E = Retains.end(); I != E; ++I) {
2759 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002760 if (!V) continue; // blotted
2761
2762 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002763
Michael Gottesman89279f82013-04-05 18:10:41 +00002764 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002765
John McCalld935e9c2011-06-15 23:37:01 +00002766 Value *Arg = GetObjCArg(Retain);
2767
Dan Gohman728db492012-01-13 00:39:07 +00002768 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002769 // not being managed by ObjC reference counting, so we can delete pairs
2770 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002771 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002772
Dan Gohman56e1cef2011-08-22 17:29:11 +00002773 // A constant pointer can't be pointing to an object on the heap. It may
2774 // be reference-counted, but it won't be deleted.
2775 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2776 if (const GlobalVariable *GV =
2777 dyn_cast<GlobalVariable>(
2778 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2779 if (GV->isConstant())
2780 KnownSafe = true;
2781
John McCalld935e9c2011-06-15 23:37:01 +00002782 // Connect the dots between the top-down-collected RetainsToMove and
2783 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002784 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002785 bool PerformMoveCalls =
2786 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2787 NewReleases, DeadInsts, RetainsToMove,
2788 ReleasesToMove, Arg, KnownSafe,
2789 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002790
Michael Gottesman9de6f962013-01-22 21:49:00 +00002791 if (PerformMoveCalls) {
2792 // Ok, everything checks out and we're all set. Let's move/delete some
2793 // code!
2794 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2795 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002796 }
2797
Michael Gottesman9de6f962013-01-22 21:49:00 +00002798 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002799 NewReleases.clear();
2800 NewRetains.clear();
2801 RetainsToMove.clear();
2802 ReleasesToMove.clear();
2803 }
2804
2805 // Now that we're done moving everything, we can delete the newly dead
2806 // instructions, as we no longer need them as insert points.
2807 while (!DeadInsts.empty())
2808 EraseInstruction(DeadInsts.pop_back_val());
2809
2810 return AnyPairsCompletelyEliminated;
2811}
2812
Michael Gottesman97e3df02013-01-14 00:35:14 +00002813/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002814void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002815 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002816
John McCalld935e9c2011-06-15 23:37:01 +00002817 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2818 // itself because it uses AliasAnalysis and we need to do provenance
2819 // queries instead.
2820 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2821 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002822
Michael Gottesman89279f82013-04-05 18:10:41 +00002823 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002824
John McCalld935e9c2011-06-15 23:37:01 +00002825 InstructionClass Class = GetBasicInstructionClass(Inst);
2826 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2827 continue;
2828
2829 // Delete objc_loadWeak calls with no users.
2830 if (Class == IC_LoadWeak && Inst->use_empty()) {
2831 Inst->eraseFromParent();
2832 continue;
2833 }
2834
2835 // TODO: For now, just look for an earlier available version of this value
2836 // within the same block. Theoretically, we could do memdep-style non-local
2837 // analysis too, but that would want caching. A better approach would be to
2838 // use the technique that EarlyCSE uses.
2839 inst_iterator Current = llvm::prior(I);
2840 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2841 for (BasicBlock::iterator B = CurrentBB->begin(),
2842 J = Current.getInstructionIterator();
2843 J != B; --J) {
2844 Instruction *EarlierInst = &*llvm::prior(J);
2845 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2846 switch (EarlierClass) {
2847 case IC_LoadWeak:
2848 case IC_LoadWeakRetained: {
2849 // If this is loading from the same pointer, replace this load's value
2850 // with that one.
2851 CallInst *Call = cast<CallInst>(Inst);
2852 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2853 Value *Arg = Call->getArgOperand(0);
2854 Value *EarlierArg = EarlierCall->getArgOperand(0);
2855 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2856 case AliasAnalysis::MustAlias:
2857 Changed = true;
2858 // If the load has a builtin retain, insert a plain retain for it.
2859 if (Class == IC_LoadWeakRetained) {
2860 CallInst *CI =
2861 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2862 "", Call);
2863 CI->setTailCall();
2864 }
2865 // Zap the fully redundant load.
2866 Call->replaceAllUsesWith(EarlierCall);
2867 Call->eraseFromParent();
2868 goto clobbered;
2869 case AliasAnalysis::MayAlias:
2870 case AliasAnalysis::PartialAlias:
2871 goto clobbered;
2872 case AliasAnalysis::NoAlias:
2873 break;
2874 }
2875 break;
2876 }
2877 case IC_StoreWeak:
2878 case IC_InitWeak: {
2879 // If this is storing to the same pointer and has the same size etc.
2880 // replace this load's value with the stored value.
2881 CallInst *Call = cast<CallInst>(Inst);
2882 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2883 Value *Arg = Call->getArgOperand(0);
2884 Value *EarlierArg = EarlierCall->getArgOperand(0);
2885 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2886 case AliasAnalysis::MustAlias:
2887 Changed = true;
2888 // If the load has a builtin retain, insert a plain retain for it.
2889 if (Class == IC_LoadWeakRetained) {
2890 CallInst *CI =
2891 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2892 "", Call);
2893 CI->setTailCall();
2894 }
2895 // Zap the fully redundant load.
2896 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2897 Call->eraseFromParent();
2898 goto clobbered;
2899 case AliasAnalysis::MayAlias:
2900 case AliasAnalysis::PartialAlias:
2901 goto clobbered;
2902 case AliasAnalysis::NoAlias:
2903 break;
2904 }
2905 break;
2906 }
2907 case IC_MoveWeak:
2908 case IC_CopyWeak:
2909 // TOOD: Grab the copied value.
2910 goto clobbered;
2911 case IC_AutoreleasepoolPush:
2912 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002913 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002914 case IC_User:
2915 // Weak pointers are only modified through the weak entry points
2916 // (and arbitrary calls, which could call the weak entry points).
2917 break;
2918 default:
2919 // Anything else could modify the weak pointer.
2920 goto clobbered;
2921 }
2922 }
2923 clobbered:;
2924 }
2925
2926 // Then, for each destroyWeak with an alloca operand, check to see if
2927 // the alloca and all its users can be zapped.
2928 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2929 Instruction *Inst = &*I++;
2930 InstructionClass Class = GetBasicInstructionClass(Inst);
2931 if (Class != IC_DestroyWeak)
2932 continue;
2933
2934 CallInst *Call = cast<CallInst>(Inst);
2935 Value *Arg = Call->getArgOperand(0);
2936 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2937 for (Value::use_iterator UI = Alloca->use_begin(),
2938 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002939 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002940 switch (GetBasicInstructionClass(UserInst)) {
2941 case IC_InitWeak:
2942 case IC_StoreWeak:
2943 case IC_DestroyWeak:
2944 continue;
2945 default:
2946 goto done;
2947 }
2948 }
2949 Changed = true;
2950 for (Value::use_iterator UI = Alloca->use_begin(),
2951 UE = Alloca->use_end(); UI != UE; ) {
2952 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002953 switch (GetBasicInstructionClass(UserInst)) {
2954 case IC_InitWeak:
2955 case IC_StoreWeak:
2956 // These functions return their second argument.
2957 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2958 break;
2959 case IC_DestroyWeak:
2960 // No return value.
2961 break;
2962 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002963 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002964 }
John McCalld935e9c2011-06-15 23:37:01 +00002965 UserInst->eraseFromParent();
2966 }
2967 Alloca->eraseFromParent();
2968 done:;
2969 }
2970 }
2971}
2972
Michael Gottesman97e3df02013-01-14 00:35:14 +00002973/// Identify program paths which execute sequences of retains and releases which
2974/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002975bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002976 // Releases, Retains - These are used to store the results of the main flow
2977 // analysis. These use Value* as the key instead of Instruction* so that the
2978 // map stays valid when we get around to rewriting code and calls get
2979 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002980 DenseMap<Value *, RRInfo> Releases;
2981 MapVector<Value *, RRInfo> Retains;
2982
Michael Gottesman740db972013-05-23 02:35:21 +00002983 // This is used during the traversal of the function to track the
2984 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002985 DenseMap<const BasicBlock *, BBState> BBStates;
2986
2987 // Analyze the CFG of the function, and all instructions.
2988 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2989
2990 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002991 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2992 Releases,
2993 F.getParent());
2994
2995 // Cleanup.
2996 MultiOwnersSet.clear();
2997
2998 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002999}
3000
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003001/// Check if there is a dependent call earlier that does not have anything in
3002/// between the Retain and the call that can affect the reference count of their
3003/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003004static bool
3005HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3006 SmallPtrSet<Instruction *, 4> &DepInsts,
3007 SmallPtrSet<const BasicBlock *, 4> &Visited,
3008 ProvenanceAnalysis &PA) {
3009 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3010 DepInsts, Visited, PA);
3011 if (DepInsts.size() != 1)
3012 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003013
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003014 CallInst *Call =
3015 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003016
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003017 // Check that the pointer is the return value of the call.
3018 if (!Call || Arg != Call)
3019 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003020
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003021 // Check that the call is a regular call.
3022 InstructionClass Class = GetBasicInstructionClass(Call);
3023 if (Class != IC_CallOrUser && Class != IC_Call)
3024 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003025
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003026 return true;
3027}
3028
Michael Gottesman6908db12013-04-03 23:16:05 +00003029/// Find a dependent retain that precedes the given autorelease for which there
3030/// is nothing in between the two instructions that can affect the ref count of
3031/// Arg.
3032static CallInst *
3033FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3034 Instruction *Autorelease,
3035 SmallPtrSet<Instruction *, 4> &DepInsts,
3036 SmallPtrSet<const BasicBlock *, 4> &Visited,
3037 ProvenanceAnalysis &PA) {
3038 FindDependencies(CanChangeRetainCount, Arg,
3039 BB, Autorelease, DepInsts, Visited, PA);
3040 if (DepInsts.size() != 1)
3041 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003042
Michael Gottesman6908db12013-04-03 23:16:05 +00003043 CallInst *Retain =
3044 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00003045
Michael Gottesman6908db12013-04-03 23:16:05 +00003046 // Check that we found a retain with the same argument.
3047 if (!Retain ||
3048 !IsRetain(GetBasicInstructionClass(Retain)) ||
3049 GetObjCArg(Retain) != Arg) {
3050 return 0;
3051 }
Michael Gottesman79249972013-04-05 23:46:45 +00003052
Michael Gottesman6908db12013-04-03 23:16:05 +00003053 return Retain;
3054}
3055
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003056/// Look for an ``autorelease'' instruction dependent on Arg such that there are
3057/// no instructions dependent on Arg that need a positive ref count in between
3058/// the autorelease and the ret.
3059static CallInst *
3060FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3061 ReturnInst *Ret,
3062 SmallPtrSet<Instruction *, 4> &DepInsts,
3063 SmallPtrSet<const BasicBlock *, 4> &V,
3064 ProvenanceAnalysis &PA) {
3065 FindDependencies(NeedsPositiveRetainCount, Arg,
3066 BB, Ret, DepInsts, V, PA);
3067 if (DepInsts.size() != 1)
3068 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003069
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003070 CallInst *Autorelease =
3071 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3072 if (!Autorelease)
3073 return 0;
3074 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3075 if (!IsAutorelease(AutoreleaseClass))
3076 return 0;
3077 if (GetObjCArg(Autorelease) != Arg)
3078 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003079
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003080 return Autorelease;
3081}
3082
Michael Gottesman97e3df02013-01-14 00:35:14 +00003083/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003084/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003085/// %call = call i8* @something(...)
3086/// %2 = call i8* @objc_retain(i8* %call)
3087/// %3 = call i8* @objc_autorelease(i8* %2)
3088/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003089/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003090/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003091void ObjCARCOpt::OptimizeReturns(Function &F) {
3092 if (!F.getReturnType()->isPointerTy())
3093 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003094
Michael Gottesman89279f82013-04-05 18:10:41 +00003095 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003096
John McCalld935e9c2011-06-15 23:37:01 +00003097 SmallPtrSet<Instruction *, 4> DependingInstructions;
3098 SmallPtrSet<const BasicBlock *, 4> Visited;
3099 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3100 BasicBlock *BB = FI;
3101 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003102
Michael Gottesman89279f82013-04-05 18:10:41 +00003103 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003104
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003105 if (!Ret)
3106 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003107
John McCalld935e9c2011-06-15 23:37:01 +00003108 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003109
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003110 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003111 // dependent on Arg such that there are no instructions dependent on Arg
3112 // that need a positive ref count in between the autorelease and Ret.
3113 CallInst *Autorelease =
3114 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3115 DependingInstructions, Visited,
3116 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003117 DependingInstructions.clear();
3118 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003119
3120 if (!Autorelease)
3121 continue;
3122
3123 CallInst *Retain =
3124 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3125 DependingInstructions, Visited, PA);
3126 DependingInstructions.clear();
3127 Visited.clear();
3128
3129 if (!Retain)
3130 continue;
3131
3132 // Check that there is nothing that can affect the reference count
3133 // between the retain and the call. Note that Retain need not be in BB.
3134 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3135 DependingInstructions,
3136 Visited, PA);
3137 DependingInstructions.clear();
3138 Visited.clear();
3139
3140 if (!HasSafePathToCall)
3141 continue;
3142
3143 // If so, we can zap the retain and autorelease.
3144 Changed = true;
3145 ++NumRets;
3146 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3147 << *Autorelease << "\n");
3148 EraseInstruction(Retain);
3149 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003150 }
3151}
3152
Michael Gottesman9c118152013-04-29 06:16:57 +00003153#ifndef NDEBUG
3154void
3155ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3156 llvm::Statistic &NumRetains =
3157 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3158 llvm::Statistic &NumReleases =
3159 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3160
3161 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3162 Instruction *Inst = &*I++;
3163 switch (GetBasicInstructionClass(Inst)) {
3164 default:
3165 break;
3166 case IC_Retain:
3167 ++NumRetains;
3168 break;
3169 case IC_Release:
3170 ++NumReleases;
3171 break;
3172 }
3173 }
3174}
3175#endif
3176
John McCalld935e9c2011-06-15 23:37:01 +00003177bool ObjCARCOpt::doInitialization(Module &M) {
3178 if (!EnableARCOpts)
3179 return false;
3180
Dan Gohman670f9372012-04-13 18:57:48 +00003181 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003182 Run = ModuleHasARC(M);
3183 if (!Run)
3184 return false;
3185
John McCalld935e9c2011-06-15 23:37:01 +00003186 // Identify the imprecise release metadata kind.
3187 ImpreciseReleaseMDKind =
3188 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003189 CopyOnEscapeMDKind =
3190 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003191 NoObjCARCExceptionsMDKind =
3192 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003193#ifdef ARC_ANNOTATIONS
3194 ARCAnnotationBottomUpMDKind =
3195 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3196 ARCAnnotationTopDownMDKind =
3197 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3198 ARCAnnotationProvenanceSourceMDKind =
3199 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3200#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003201
John McCalld935e9c2011-06-15 23:37:01 +00003202 // Intuitively, objc_retain and others are nocapture, however in practice
3203 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003204 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003205
3206 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003207 AutoreleaseRVCallee = 0;
3208 ReleaseCallee = 0;
3209 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003210 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003211 AutoreleaseCallee = 0;
3212
3213 return false;
3214}
3215
3216bool ObjCARCOpt::runOnFunction(Function &F) {
3217 if (!EnableARCOpts)
3218 return false;
3219
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003220 // If nothing in the Module uses ARC, don't do anything.
3221 if (!Run)
3222 return false;
3223
John McCalld935e9c2011-06-15 23:37:01 +00003224 Changed = false;
3225
Michael Gottesman89279f82013-04-05 18:10:41 +00003226 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3227 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003228
John McCalld935e9c2011-06-15 23:37:01 +00003229 PA.setAA(&getAnalysis<AliasAnalysis>());
3230
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003231#ifndef NDEBUG
3232 if (AreStatisticsEnabled()) {
3233 GatherStatistics(F, false);
3234 }
3235#endif
3236
John McCalld935e9c2011-06-15 23:37:01 +00003237 // This pass performs several distinct transformations. As a compile-time aid
3238 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3239 // library functions aren't declared.
3240
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003241 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003242 OptimizeIndividualCalls(F);
3243
3244 // Optimizations for weak pointers.
3245 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3246 (1 << IC_LoadWeakRetained) |
3247 (1 << IC_StoreWeak) |
3248 (1 << IC_InitWeak) |
3249 (1 << IC_CopyWeak) |
3250 (1 << IC_MoveWeak) |
3251 (1 << IC_DestroyWeak)))
3252 OptimizeWeakCalls(F);
3253
3254 // Optimizations for retain+release pairs.
3255 if (UsedInThisFunction & ((1 << IC_Retain) |
3256 (1 << IC_RetainRV) |
3257 (1 << IC_RetainBlock)))
3258 if (UsedInThisFunction & (1 << IC_Release))
3259 // Run OptimizeSequences until it either stops making changes or
3260 // no retain+release pair nesting is detected.
3261 while (OptimizeSequences(F)) {}
3262
3263 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003264 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3265 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003266 OptimizeReturns(F);
3267
Michael Gottesman9c118152013-04-29 06:16:57 +00003268 // Gather statistics after optimization.
3269#ifndef NDEBUG
3270 if (AreStatisticsEnabled()) {
3271 GatherStatistics(F, true);
3272 }
3273#endif
3274
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003275 DEBUG(dbgs() << "\n");
3276
John McCalld935e9c2011-06-15 23:37:01 +00003277 return Changed;
3278}
3279
3280void ObjCARCOpt::releaseMemory() {
3281 PA.clear();
3282}
3283
Michael Gottesman97e3df02013-01-14 00:35:14 +00003284/// @}
3285///