blob: 91490d1b2d06f0d7418a70fff6c710eb89664f1c [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
458 RRInfo() :
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000459 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000460
461 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000462
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000463 bool IsTrackingImpreciseReleases() {
464 return ReleaseMetadata != 0;
465 }
John McCalld935e9c2011-06-15 23:37:01 +0000466 };
467}
468
469void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000470 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000471 IsTailCallRelease = false;
472 ReleaseMetadata = 0;
473 Calls.clear();
474 ReverseInsertPts.clear();
475}
476
477namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000478 /// \brief This class summarizes several per-pointer runtime properties which
479 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000480 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000481 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000482 bool KnownPositiveRefCount;
483
Bob Wilson798a7702013-04-09 22:15:51 +0000484 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000485 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000486 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000487
Michael Gottesman97e3df02013-01-14 00:35:14 +0000488 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000489 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000490
491 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000492 /// Unidirectional information about the current sequence.
493 ///
John McCalld935e9c2011-06-15 23:37:01 +0000494 /// TODO: Encapsulate this better.
495 RRInfo RRI;
496
Dan Gohmandf476e52012-09-04 23:16:20 +0000497 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000498 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000499
Michael Gottesman415ddd72013-02-05 19:32:18 +0000500 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000501 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000502 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000503 }
504
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000505 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000506 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000507 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000508 }
509
Michael Gottesman07beea42013-03-23 05:31:01 +0000510 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000511 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000512 }
513
Michael Gottesman415ddd72013-02-05 19:32:18 +0000514 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000515 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000516 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000517 }
518
Michael Gottesman415ddd72013-02-05 19:32:18 +0000519 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000520 return Seq;
521 }
522
Michael Gottesman415ddd72013-02-05 19:32:18 +0000523 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000524 ResetSequenceProgress(S_None);
525 }
526
Michael Gottesman415ddd72013-02-05 19:32:18 +0000527 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000528 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000529 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000530 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000531 RRI.clear();
532 }
533
534 void Merge(const PtrState &Other, bool TopDown);
535 };
536}
537
538void
539PtrState::Merge(const PtrState &Other, bool TopDown) {
540 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000541 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000542
Dan Gohman1736c142011-10-17 18:48:25 +0000543 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000544 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000545 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000546 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000547 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000548 // If we're doing a merge on a path that's previously seen a partial
549 // merge, conservatively drop the sequence, to avoid doing partial
550 // RR elimination. If the branch predicates for the two merge differ,
551 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000552 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000553 } else {
554 // Conservatively merge the ReleaseMetadata information.
555 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
556 RRI.ReleaseMetadata = 0;
557
Dan Gohmanb3894012011-08-19 00:26:36 +0000558 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000559 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
560 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000561 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000562
563 // Merge the insert point sets. If there are any differences,
564 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000565 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000566 for (SmallPtrSet<Instruction *, 2>::const_iterator
567 I = Other.RRI.ReverseInsertPts.begin(),
568 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000569 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000570 }
571}
572
573namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000575 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000576 /// The number of unique control paths from the entry which can reach this
577 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000578 unsigned TopDownPathCount;
579
Michael Gottesman97e3df02013-01-14 00:35:14 +0000580 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000581 unsigned BottomUpPathCount;
582
Michael Gottesman97e3df02013-01-14 00:35:14 +0000583 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000584 typedef MapVector<const Value *, PtrState> MapTy;
585
Michael Gottesman97e3df02013-01-14 00:35:14 +0000586 /// The top-down traversal uses this to record information known about a
587 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000588 MapTy PerPtrTopDown;
589
Michael Gottesman97e3df02013-01-14 00:35:14 +0000590 /// The bottom-up traversal uses this to record information known about a
591 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000592 MapTy PerPtrBottomUp;
593
Michael Gottesman97e3df02013-01-14 00:35:14 +0000594 /// Effective predecessors of the current block ignoring ignorable edges and
595 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000596 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000597 /// Effective successors of the current block ignoring ignorable edges and
598 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000599 SmallVector<BasicBlock *, 2> Succs;
600
John McCalld935e9c2011-06-15 23:37:01 +0000601 public:
602 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
603
604 typedef MapTy::iterator ptr_iterator;
605 typedef MapTy::const_iterator ptr_const_iterator;
606
607 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
608 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
609 ptr_const_iterator top_down_ptr_begin() const {
610 return PerPtrTopDown.begin();
611 }
612 ptr_const_iterator top_down_ptr_end() const {
613 return PerPtrTopDown.end();
614 }
615
616 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
617 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
618 ptr_const_iterator bottom_up_ptr_begin() const {
619 return PerPtrBottomUp.begin();
620 }
621 ptr_const_iterator bottom_up_ptr_end() const {
622 return PerPtrBottomUp.end();
623 }
624
Michael Gottesman97e3df02013-01-14 00:35:14 +0000625 /// Mark this block as being an entry block, which has one path from the
626 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000627 void SetAsEntry() { TopDownPathCount = 1; }
628
Michael Gottesman97e3df02013-01-14 00:35:14 +0000629 /// Mark this block as being an exit block, which has one path to an exit by
630 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000631 void SetAsExit() { BottomUpPathCount = 1; }
632
Michael Gottesman993fbf72013-05-13 19:40:39 +0000633 /// Attempt to find the PtrState object describing the top down state for
634 /// pointer Arg. Return a new initialized PtrState describing the top down
635 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000636 PtrState &getPtrTopDownState(const Value *Arg) {
637 return PerPtrTopDown[Arg];
638 }
639
Michael Gottesman993fbf72013-05-13 19:40:39 +0000640 /// Attempt to find the PtrState object describing the bottom up state for
641 /// pointer Arg. Return a new initialized PtrState describing the bottom up
642 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000643 PtrState &getPtrBottomUpState(const Value *Arg) {
644 return PerPtrBottomUp[Arg];
645 }
646
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000647 /// Attempt to find the PtrState object describing the bottom up state for
648 /// pointer Arg.
649 ptr_iterator findPtrBottomUpState(const Value *Arg) {
650 return PerPtrBottomUp.find(Arg);
651 }
652
John McCalld935e9c2011-06-15 23:37:01 +0000653 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000654 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000655 }
656
657 void clearTopDownPointers() {
658 PerPtrTopDown.clear();
659 }
660
661 void InitFromPred(const BBState &Other);
662 void InitFromSucc(const BBState &Other);
663 void MergePred(const BBState &Other);
664 void MergeSucc(const BBState &Other);
665
Michael Gottesman97e3df02013-01-14 00:35:14 +0000666 /// Return the number of possible unique paths from an entry to an exit
667 /// which pass through this block. This is only valid after both the
668 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000669 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000670 assert(TopDownPathCount != 0);
671 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000672 return TopDownPathCount * BottomUpPathCount;
673 }
Dan Gohman12130272011-08-12 00:26:31 +0000674
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000675 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000676 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000677 edge_iterator pred_begin() { return Preds.begin(); }
678 edge_iterator pred_end() { return Preds.end(); }
679 edge_iterator succ_begin() { return Succs.begin(); }
680 edge_iterator succ_end() { return Succs.end(); }
681
682 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
683 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
684
685 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000686 };
687}
688
689void BBState::InitFromPred(const BBState &Other) {
690 PerPtrTopDown = Other.PerPtrTopDown;
691 TopDownPathCount = Other.TopDownPathCount;
692}
693
694void BBState::InitFromSucc(const BBState &Other) {
695 PerPtrBottomUp = Other.PerPtrBottomUp;
696 BottomUpPathCount = Other.BottomUpPathCount;
697}
698
Michael Gottesman97e3df02013-01-14 00:35:14 +0000699/// The top-down traversal uses this to merge information about predecessors to
700/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000701void BBState::MergePred(const BBState &Other) {
702 // Other.TopDownPathCount can be 0, in which case it is either dead or a
703 // loop backedge. Loop backedges are special.
704 TopDownPathCount += Other.TopDownPathCount;
705
Michael Gottesman4385edf2013-01-14 01:47:53 +0000706 // Check for overflow. If we have overflow, fall back to conservative
707 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000708 if (TopDownPathCount < Other.TopDownPathCount) {
709 clearTopDownPointers();
710 return;
711 }
712
John McCalld935e9c2011-06-15 23:37:01 +0000713 // For each entry in the other set, if our set has an entry with the same key,
714 // merge the entries. Otherwise, copy the entry and merge it with an empty
715 // entry.
716 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
717 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
718 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
719 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
720 /*TopDown=*/true);
721 }
722
Dan Gohman7e315fc32011-08-11 21:06:32 +0000723 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000724 // same key, force it to merge with an empty entry.
725 for (ptr_iterator MI = top_down_ptr_begin(),
726 ME = top_down_ptr_end(); MI != ME; ++MI)
727 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
728 MI->second.Merge(PtrState(), /*TopDown=*/true);
729}
730
Michael Gottesman97e3df02013-01-14 00:35:14 +0000731/// The bottom-up traversal uses this to merge information about successors to
732/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000733void BBState::MergeSucc(const BBState &Other) {
734 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
735 // loop backedge. Loop backedges are special.
736 BottomUpPathCount += Other.BottomUpPathCount;
737
Michael Gottesman4385edf2013-01-14 01:47:53 +0000738 // Check for overflow. If we have overflow, fall back to conservative
739 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000740 if (BottomUpPathCount < Other.BottomUpPathCount) {
741 clearBottomUpPointers();
742 return;
743 }
744
John McCalld935e9c2011-06-15 23:37:01 +0000745 // For each entry in the other set, if our set has an entry with the
746 // same key, merge the entries. Otherwise, copy the entry and merge
747 // it with an empty entry.
748 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
749 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
750 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
751 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
752 /*TopDown=*/false);
753 }
754
Dan Gohman7e315fc32011-08-11 21:06:32 +0000755 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000756 // with the same key, force it to merge with an empty entry.
757 for (ptr_iterator MI = bottom_up_ptr_begin(),
758 ME = bottom_up_ptr_end(); MI != ME; ++MI)
759 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
760 MI->second.Merge(PtrState(), /*TopDown=*/false);
761}
762
Michael Gottesman81b1d432013-03-26 00:42:04 +0000763// Only enable ARC Annotations if we are building a debug version of
764// libObjCARCOpts.
765#ifndef NDEBUG
766#define ARC_ANNOTATIONS
767#endif
768
769// Define some macros along the lines of DEBUG and some helper functions to make
770// it cleaner to create annotations in the source code and to no-op when not
771// building in debug mode.
772#ifdef ARC_ANNOTATIONS
773
774#include "llvm/Support/CommandLine.h"
775
776/// Enable/disable ARC sequence annotations.
777static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000778EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
779 cl::desc("Enable emission of arc data flow analysis "
780 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000781static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000782DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
783 cl::desc("Disable check for cfg hazards when "
784 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000785static cl::opt<std::string>
786ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
787 cl::init(""),
788 cl::desc("filter out all data flow annotations "
789 "but those that apply to the given "
790 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000791
792/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
793/// instruction so that we can track backwards when post processing via the llvm
794/// arc annotation processor tool. If the function is an
795static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
796 Value *Ptr) {
797 MDString *Hash = 0;
798
799 // If pointer is a result of an instruction and it does not have a source
800 // MDNode it, attach a new MDNode onto it. If pointer is a result of
801 // an instruction and does have a source MDNode attached to it, return a
802 // reference to said Node. Otherwise just return 0.
803 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
804 MDNode *Node;
805 if (!(Node = Inst->getMetadata(NodeId))) {
806 // We do not have any node. Generate and attatch the hash MDString to the
807 // instruction.
808
809 // We just use an MDString to ensure that this metadata gets written out
810 // of line at the module level and to provide a very simple format
811 // encoding the information herein. Both of these makes it simpler to
812 // parse the annotations by a simple external program.
813 std::string Str;
814 raw_string_ostream os(Str);
815 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
816 << Inst->getName() << ")";
817
818 Hash = MDString::get(Inst->getContext(), os.str());
819 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
820 } else {
821 // We have a node. Grab its hash and return it.
822 assert(Node->getNumOperands() == 1 &&
823 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
824 Hash = cast<MDString>(Node->getOperand(0));
825 }
826 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
827 std::string str;
828 raw_string_ostream os(str);
829 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
830 << ")";
831 Hash = MDString::get(Arg->getContext(), os.str());
832 }
833
834 return Hash;
835}
836
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000837static std::string SequenceToString(Sequence A) {
838 std::string str;
839 raw_string_ostream os(str);
840 os << A;
841 return os.str();
842}
843
Michael Gottesman81b1d432013-03-26 00:42:04 +0000844/// Helper function to change a Sequence into a String object using our overload
845/// for raw_ostream so we only have printing code in one location.
846static MDString *SequenceToMDString(LLVMContext &Context,
847 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000848 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000849}
850
851/// A simple function to generate a MDNode which describes the change in state
852/// for Value *Ptr caused by Instruction *Inst.
853static void AppendMDNodeToInstForPtr(unsigned NodeId,
854 Instruction *Inst,
855 Value *Ptr,
856 MDString *PtrSourceMDNodeID,
857 Sequence OldSeq,
858 Sequence NewSeq) {
859 MDNode *Node = 0;
860 Value *tmp[3] = {PtrSourceMDNodeID,
861 SequenceToMDString(Inst->getContext(),
862 OldSeq),
863 SequenceToMDString(Inst->getContext(),
864 NewSeq)};
865 Node = MDNode::get(Inst->getContext(),
866 ArrayRef<Value*>(tmp, 3));
867
868 Inst->setMetadata(NodeId, Node);
869}
870
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000871/// Add to the beginning of the basic block llvm.ptr.annotations which show the
872/// state of a pointer at the entrance to a basic block.
873static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
874 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000875 // If we have a target identifier, make sure that we match it before
876 // continuing.
877 if(!ARCAnnotationTargetIdentifier.empty() &&
878 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
879 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000880
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000881 Module *M = BB->getParent()->getParent();
882 LLVMContext &C = M->getContext();
883 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
884 Type *I8XX = PointerType::getUnqual(I8X);
885 Type *Params[] = {I8XX, I8XX};
886 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
887 ArrayRef<Type*>(Params, 2),
888 /*isVarArg=*/false);
889 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000890
891 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
892
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000893 Value *PtrName;
894 StringRef Tmp = Ptr->getName();
895 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
896 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
897 Tmp + "_STR");
898 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000899 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000900 }
901
902 Value *S;
903 std::string SeqStr = SequenceToString(Seq);
904 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
905 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
906 SeqStr + "_STR");
907 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
908 cast<Constant>(ActualPtrName), SeqStr);
909 }
910
911 Builder.CreateCall2(Callee, PtrName, S);
912}
913
914/// Add to the end of the basic block llvm.ptr.annotations which show the state
915/// of the pointer at the bottom of the basic block.
916static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
917 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000918 // If we have a target identifier, make sure that we match it before emitting
919 // an annotation.
920 if(!ARCAnnotationTargetIdentifier.empty() &&
921 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
922 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000923
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000924 Module *M = BB->getParent()->getParent();
925 LLVMContext &C = M->getContext();
926 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
927 Type *I8XX = PointerType::getUnqual(I8X);
928 Type *Params[] = {I8XX, I8XX};
929 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
930 ArrayRef<Type*>(Params, 2),
931 /*isVarArg=*/false);
932 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000933
934 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
935
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000936 Value *PtrName;
937 StringRef Tmp = Ptr->getName();
938 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
939 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
940 Tmp + "_STR");
941 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000942 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000943 }
944
945 Value *S;
946 std::string SeqStr = SequenceToString(Seq);
947 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
948 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
949 SeqStr + "_STR");
950 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
951 cast<Constant>(ActualPtrName), SeqStr);
952 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000953 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000954}
955
Michael Gottesman81b1d432013-03-26 00:42:04 +0000956/// Adds a source annotation to pointer and a state change annotation to Inst
957/// referencing the source annotation and the old/new state of pointer.
958static void GenerateARCAnnotation(unsigned InstMDId,
959 unsigned PtrMDId,
960 Instruction *Inst,
961 Value *Ptr,
962 Sequence OldSeq,
963 Sequence NewSeq) {
964 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000965 // If we have a target identifier, make sure that we match it before
966 // emitting an annotation.
967 if(!ARCAnnotationTargetIdentifier.empty() &&
968 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
969 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000970
Michael Gottesman81b1d432013-03-26 00:42:04 +0000971 // First generate the source annotation on our pointer. This will return an
972 // MDString* if Ptr actually comes from an instruction implying we can put
973 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
974 // then we know that our pointer is from an Argument so we put a reference
975 // to the argument number.
976 //
977 // The point of this is to make it easy for the
978 // llvm-arc-annotation-processor tool to cross reference where the source
979 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
980 // information via debug info for backends to use (since why would anyone
981 // need such a thing from LLVM IR besides in non standard cases
982 // [i.e. this]).
983 MDString *SourcePtrMDNode =
984 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
985 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
986 NewSeq);
987 }
988}
989
990// The actual interface for accessing the above functionality is defined via
991// some simple macros which are defined below. We do this so that the user does
992// not need to pass in what metadata id is needed resulting in cleaner code and
993// additionally since it provides an easy way to conditionally no-op all
994// annotation support in a non-debug build.
995
996/// Use this macro to annotate a sequence state change when processing
997/// instructions bottom up,
998#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
999 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1000 ARCAnnotationProvenanceSourceMDKind, (inst), \
1001 const_cast<Value*>(ptr), (old), (new))
1002/// Use this macro to annotate a sequence state change when processing
1003/// instructions top down.
1004#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1005 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1006 ARCAnnotationProvenanceSourceMDKind, (inst), \
1007 const_cast<Value*>(ptr), (old), (new))
1008
Michael Gottesman43e7e002013-04-03 22:41:59 +00001009#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1010 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001011 if (EnableARCAnnotations) { \
1012 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001013 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001014 Value *Ptr = const_cast<Value*>(I->first); \
1015 Sequence Seq = I->second.GetSeq(); \
1016 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1017 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001018 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001019 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001020
Michael Gottesman89279f82013-04-05 18:10:41 +00001021#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001022 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1023 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001024#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1025 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001026 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001027#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1028 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001029 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001030#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1031 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001032 Terminator, top_down)
1033
Michael Gottesman81b1d432013-03-26 00:42:04 +00001034#else // !ARC_ANNOTATION
1035// If annotations are off, noop.
1036#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1037#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001038#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1039#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1040#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1041#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001042#endif // !ARC_ANNOTATION
1043
John McCalld935e9c2011-06-15 23:37:01 +00001044namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001045 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001046 class ObjCARCOpt : public FunctionPass {
1047 bool Changed;
1048 ProvenanceAnalysis PA;
1049
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001050 // This is used to track if a pointer is stored into an alloca.
1051 DenseSet<const Value *> MultiOwnersSet;
1052
Michael Gottesman97e3df02013-01-14 00:35:14 +00001053 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001054 bool Run;
1055
Michael Gottesman97e3df02013-01-14 00:35:14 +00001056 /// Declarations for ObjC runtime functions, for use in creating calls to
1057 /// them. These are initialized lazily to avoid cluttering up the Module
1058 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001059
Michael Gottesman97e3df02013-01-14 00:35:14 +00001060 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1061 Constant *AutoreleaseRVCallee;
1062 /// Declaration for ObjC runtime function objc_release.
1063 Constant *ReleaseCallee;
1064 /// Declaration for ObjC runtime function objc_retain.
1065 Constant *RetainCallee;
1066 /// Declaration for ObjC runtime function objc_retainBlock.
1067 Constant *RetainBlockCallee;
1068 /// Declaration for ObjC runtime function objc_autorelease.
1069 Constant *AutoreleaseCallee;
1070
1071 /// Flags which determine whether each of the interesting runtine functions
1072 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001073 unsigned UsedInThisFunction;
1074
Michael Gottesman97e3df02013-01-14 00:35:14 +00001075 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001076 unsigned ImpreciseReleaseMDKind;
1077
Michael Gottesman97e3df02013-01-14 00:35:14 +00001078 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001079 unsigned CopyOnEscapeMDKind;
1080
Michael Gottesman97e3df02013-01-14 00:35:14 +00001081 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001082 unsigned NoObjCARCExceptionsMDKind;
1083
Michael Gottesman81b1d432013-03-26 00:42:04 +00001084#ifdef ARC_ANNOTATIONS
1085 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1086 unsigned ARCAnnotationBottomUpMDKind;
1087 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1088 unsigned ARCAnnotationTopDownMDKind;
1089 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1090 unsigned ARCAnnotationProvenanceSourceMDKind;
1091#endif // ARC_ANNOATIONS
1092
John McCalld935e9c2011-06-15 23:37:01 +00001093 Constant *getAutoreleaseRVCallee(Module *M);
1094 Constant *getReleaseCallee(Module *M);
1095 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001096 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001097 Constant *getAutoreleaseCallee(Module *M);
1098
Dan Gohman728db492012-01-13 00:39:07 +00001099 bool IsRetainBlockOptimizable(const Instruction *Inst);
1100
John McCalld935e9c2011-06-15 23:37:01 +00001101 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001102 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1103 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001104 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1105 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001106 void OptimizeIndividualCalls(Function &F);
1107
1108 void CheckForCFGHazards(const BasicBlock *BB,
1109 DenseMap<const BasicBlock *, BBState> &BBStates,
1110 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001111 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001112 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001113 MapVector<Value *, RRInfo> &Retains,
1114 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001115 bool VisitBottomUp(BasicBlock *BB,
1116 DenseMap<const BasicBlock *, BBState> &BBStates,
1117 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001118 bool VisitInstructionTopDown(Instruction *Inst,
1119 DenseMap<Value *, RRInfo> &Releases,
1120 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001121 bool VisitTopDown(BasicBlock *BB,
1122 DenseMap<const BasicBlock *, BBState> &BBStates,
1123 DenseMap<Value *, RRInfo> &Releases);
1124 bool Visit(Function &F,
1125 DenseMap<const BasicBlock *, BBState> &BBStates,
1126 MapVector<Value *, RRInfo> &Retains,
1127 DenseMap<Value *, RRInfo> &Releases);
1128
1129 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1130 MapVector<Value *, RRInfo> &Retains,
1131 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001132 SmallVectorImpl<Instruction *> &DeadInsts,
1133 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001134
Michael Gottesman9de6f962013-01-22 21:49:00 +00001135 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1136 MapVector<Value *, RRInfo> &Retains,
1137 DenseMap<Value *, RRInfo> &Releases,
1138 Module *M,
1139 SmallVector<Instruction *, 4> &NewRetains,
1140 SmallVector<Instruction *, 4> &NewReleases,
1141 SmallVector<Instruction *, 8> &DeadInsts,
1142 RRInfo &RetainsToMove,
1143 RRInfo &ReleasesToMove,
1144 Value *Arg,
1145 bool KnownSafe,
1146 bool &AnyPairsCompletelyEliminated);
1147
John McCalld935e9c2011-06-15 23:37:01 +00001148 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1149 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001150 DenseMap<Value *, RRInfo> &Releases,
1151 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001152
1153 void OptimizeWeakCalls(Function &F);
1154
1155 bool OptimizeSequences(Function &F);
1156
1157 void OptimizeReturns(Function &F);
1158
Michael Gottesman9c118152013-04-29 06:16:57 +00001159#ifndef NDEBUG
1160 void GatherStatistics(Function &F, bool AfterOptimization = false);
1161#endif
1162
John McCalld935e9c2011-06-15 23:37:01 +00001163 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1164 virtual bool doInitialization(Module &M);
1165 virtual bool runOnFunction(Function &F);
1166 virtual void releaseMemory();
1167
1168 public:
1169 static char ID;
1170 ObjCARCOpt() : FunctionPass(ID) {
1171 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1172 }
1173 };
1174}
1175
1176char ObjCARCOpt::ID = 0;
1177INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1178 "objc-arc", "ObjC ARC optimization", false, false)
1179INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1180INITIALIZE_PASS_END(ObjCARCOpt,
1181 "objc-arc", "ObjC ARC optimization", false, false)
1182
1183Pass *llvm::createObjCARCOptPass() {
1184 return new ObjCARCOpt();
1185}
1186
1187void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1188 AU.addRequired<ObjCARCAliasAnalysis>();
1189 AU.addRequired<AliasAnalysis>();
1190 // ARC optimization doesn't currently split critical edges.
1191 AU.setPreservesCFG();
1192}
1193
Dan Gohman728db492012-01-13 00:39:07 +00001194bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1195 // Without the magic metadata tag, we have to assume this might be an
1196 // objc_retainBlock call inserted to convert a block pointer to an id,
1197 // in which case it really is needed.
1198 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1199 return false;
1200
1201 // If the pointer "escapes" (not including being used in a call),
1202 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001203 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001204 return false;
1205
1206 // Otherwise, it's not needed.
1207 return true;
1208}
1209
John McCalld935e9c2011-06-15 23:37:01 +00001210Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1211 if (!AutoreleaseRVCallee) {
1212 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001213 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001214 Type *Params[] = { I8X };
1215 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001216 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001217 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1218 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001219 AutoreleaseRVCallee =
1220 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001221 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001222 }
1223 return AutoreleaseRVCallee;
1224}
1225
1226Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1227 if (!ReleaseCallee) {
1228 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001229 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001230 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001231 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1232 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001233 ReleaseCallee =
1234 M->getOrInsertFunction(
1235 "objc_release",
1236 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001237 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001238 }
1239 return ReleaseCallee;
1240}
1241
1242Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1243 if (!RetainCallee) {
1244 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001245 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001246 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001247 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1248 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001249 RetainCallee =
1250 M->getOrInsertFunction(
1251 "objc_retain",
1252 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001253 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001254 }
1255 return RetainCallee;
1256}
1257
Dan Gohman6320f522011-07-22 22:29:21 +00001258Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1259 if (!RetainBlockCallee) {
1260 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001261 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001262 // objc_retainBlock is not nounwind because it calls user copy constructors
1263 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001264 RetainBlockCallee =
1265 M->getOrInsertFunction(
1266 "objc_retainBlock",
1267 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001268 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001269 }
1270 return RetainBlockCallee;
1271}
1272
John McCalld935e9c2011-06-15 23:37:01 +00001273Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1274 if (!AutoreleaseCallee) {
1275 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001276 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001277 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001278 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1279 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001280 AutoreleaseCallee =
1281 M->getOrInsertFunction(
1282 "objc_autorelease",
1283 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001284 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001285 }
1286 return AutoreleaseCallee;
1287}
1288
Michael Gottesman97e3df02013-01-14 00:35:14 +00001289/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1290/// not a return value. Or, if it can be paired with an
1291/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001292bool
1293ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001294 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001295 const Value *Arg = GetObjCArg(RetainRV);
1296 ImmutableCallSite CS(Arg);
1297 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001298 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001299 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001300 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001301 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001302 if (&*I == RetainRV)
1303 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001304 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001305 BasicBlock *RetainRVParent = RetainRV->getParent();
1306 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001307 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001308 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001309 if (&*I == RetainRV)
1310 return false;
1311 }
John McCalld935e9c2011-06-15 23:37:01 +00001312 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001313 }
John McCalld935e9c2011-06-15 23:37:01 +00001314
1315 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1316 // pointer. In this case, we can delete the pair.
1317 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1318 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001319 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001320 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1321 GetObjCArg(I) == Arg) {
1322 Changed = true;
1323 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001324
Michael Gottesman89279f82013-04-05 18:10:41 +00001325 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1326 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001327
John McCalld935e9c2011-06-15 23:37:01 +00001328 EraseInstruction(I);
1329 EraseInstruction(RetainRV);
1330 return true;
1331 }
1332 }
1333
1334 // Turn it to a plain objc_retain.
1335 Changed = true;
1336 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001337
Michael Gottesman89279f82013-04-05 18:10:41 +00001338 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001339 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001340 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001341
John McCalld935e9c2011-06-15 23:37:01 +00001342 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001343
Michael Gottesman89279f82013-04-05 18:10:41 +00001344 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001345
John McCalld935e9c2011-06-15 23:37:01 +00001346 return false;
1347}
1348
Michael Gottesman97e3df02013-01-14 00:35:14 +00001349/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1350/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001351void
Michael Gottesman556ff612013-01-12 01:25:19 +00001352ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1353 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001354 // Check for a return of the pointer value.
1355 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001356 SmallVector<const Value *, 2> Users;
1357 Users.push_back(Ptr);
1358 do {
1359 Ptr = Users.pop_back_val();
1360 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1361 UI != UE; ++UI) {
1362 const User *I = *UI;
1363 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1364 return;
1365 if (isa<BitCastInst>(I))
1366 Users.push_back(I);
1367 }
1368 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001369
1370 Changed = true;
1371 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001372
Michael Gottesman89279f82013-04-05 18:10:41 +00001373 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001374 "objc_autorelease since its operand is not used as a return "
1375 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001376 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001377
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001378 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1379 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001380 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001381 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001382 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001383
Michael Gottesman89279f82013-04-05 18:10:41 +00001384 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001385
John McCalld935e9c2011-06-15 23:37:01 +00001386}
1387
Michael Gottesman158fdf62013-03-28 20:11:19 +00001388// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1389// calls.
1390//
1391// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1392// does not escape (following the rules of block escaping), strength reduce the
1393// objc_retainBlock to an objc_retain.
1394//
1395// TODO: If an objc_retainBlock call is dominated period by a previous
1396// objc_retainBlock call, strength reduce the objc_retainBlock to an
1397// objc_retain.
1398bool
1399ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1400 InstructionClass &Class) {
1401 assert(GetBasicInstructionClass(Inst) == Class);
1402 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001403
Michael Gottesman158fdf62013-03-28 20:11:19 +00001404 // If we can not optimize Inst, return false.
1405 if (!IsRetainBlockOptimizable(Inst))
1406 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001407
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001408 Changed = true;
1409 ++NumPeeps;
1410
1411 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1412 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001413 CallInst *RetainBlock = cast<CallInst>(Inst);
1414 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1415 // Remove copy_on_escape metadata.
1416 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1417 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001418 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001419 return true;
1420}
1421
Michael Gottesman97e3df02013-01-14 00:35:14 +00001422/// Visit each call, one at a time, and make simplifications without doing any
1423/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001424void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001425 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001426 // Reset all the flags in preparation for recomputing them.
1427 UsedInThisFunction = 0;
1428
1429 // Visit all objc_* calls in F.
1430 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1431 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001432
John McCalld935e9c2011-06-15 23:37:01 +00001433 InstructionClass Class = GetBasicInstructionClass(Inst);
1434
Michael Gottesman89279f82013-04-05 18:10:41 +00001435 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001436
John McCalld935e9c2011-06-15 23:37:01 +00001437 switch (Class) {
1438 default: break;
1439
1440 // Delete no-op casts. These function calls have special semantics, but
1441 // the semantics are entirely implemented via lowering in the front-end,
1442 // so by the time they reach the optimizer, they are just no-op calls
1443 // which return their argument.
1444 //
1445 // There are gray areas here, as the ability to cast reference-counted
1446 // pointers to raw void* and back allows code to break ARC assumptions,
1447 // however these are currently considered to be unimportant.
1448 case IC_NoopCast:
1449 Changed = true;
1450 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001451 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001452 EraseInstruction(Inst);
1453 continue;
1454
1455 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1456 case IC_StoreWeak:
1457 case IC_LoadWeak:
1458 case IC_LoadWeakRetained:
1459 case IC_InitWeak:
1460 case IC_DestroyWeak: {
1461 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001462 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001463 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001464 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001465 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1466 Constant::getNullValue(Ty),
1467 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001468 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001469 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1470 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001471 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001472 CI->eraseFromParent();
1473 continue;
1474 }
1475 break;
1476 }
1477 case IC_CopyWeak:
1478 case IC_MoveWeak: {
1479 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001480 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1481 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001482 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001483 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001484 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1485 Constant::getNullValue(Ty),
1486 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001487
1488 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001489 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1490 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001491
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001492 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001493 CI->eraseFromParent();
1494 continue;
1495 }
1496 break;
1497 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001498 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001499 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001500 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001501 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001502 break;
1503 case IC_RetainRV:
1504 if (OptimizeRetainRVCall(F, Inst))
1505 continue;
1506 break;
1507 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001508 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001509 break;
1510 }
1511
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001512 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001513 if (IsAutorelease(Class) && Inst->use_empty()) {
1514 CallInst *Call = cast<CallInst>(Inst);
1515 const Value *Arg = Call->getArgOperand(0);
1516 Arg = FindSingleUseIdentifiedObject(Arg);
1517 if (Arg) {
1518 Changed = true;
1519 ++NumAutoreleases;
1520
1521 // Create the declaration lazily.
1522 LLVMContext &C = Inst->getContext();
1523 CallInst *NewCall =
1524 CallInst::Create(getReleaseCallee(F.getParent()),
1525 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001526 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001527
Michael Gottesman89279f82013-04-05 18:10:41 +00001528 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1529 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1530 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001531
John McCalld935e9c2011-06-15 23:37:01 +00001532 EraseInstruction(Call);
1533 Inst = NewCall;
1534 Class = IC_Release;
1535 }
1536 }
1537
1538 // For functions which can never be passed stack arguments, add
1539 // a tail keyword.
1540 if (IsAlwaysTail(Class)) {
1541 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001542 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1543 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001544 cast<CallInst>(Inst)->setTailCall();
1545 }
1546
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001547 // Ensure that functions that can never have a "tail" keyword due to the
1548 // semantics of ARC truly do not do so.
1549 if (IsNeverTail(Class)) {
1550 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001551 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001552 "\n");
1553 cast<CallInst>(Inst)->setTailCall(false);
1554 }
1555
John McCalld935e9c2011-06-15 23:37:01 +00001556 // Set nounwind as needed.
1557 if (IsNoThrow(Class)) {
1558 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001559 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1560 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001561 cast<CallInst>(Inst)->setDoesNotThrow();
1562 }
1563
1564 if (!IsNoopOnNull(Class)) {
1565 UsedInThisFunction |= 1 << Class;
1566 continue;
1567 }
1568
1569 const Value *Arg = GetObjCArg(Inst);
1570
1571 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001572 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001573 Changed = true;
1574 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001575 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1576 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001577 EraseInstruction(Inst);
1578 continue;
1579 }
1580
1581 // Keep track of which of retain, release, autorelease, and retain_block
1582 // are actually present in this function.
1583 UsedInThisFunction |= 1 << Class;
1584
1585 // If Arg is a PHI, and one or more incoming values to the
1586 // PHI are null, and the call is control-equivalent to the PHI, and there
1587 // are no relevant side effects between the PHI and the call, the call
1588 // could be pushed up to just those paths with non-null incoming values.
1589 // For now, don't bother splitting critical edges for this.
1590 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1591 Worklist.push_back(std::make_pair(Inst, Arg));
1592 do {
1593 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1594 Inst = Pair.first;
1595 Arg = Pair.second;
1596
1597 const PHINode *PN = dyn_cast<PHINode>(Arg);
1598 if (!PN) continue;
1599
1600 // Determine if the PHI has any null operands, or any incoming
1601 // critical edges.
1602 bool HasNull = false;
1603 bool HasCriticalEdges = false;
1604 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1605 Value *Incoming =
1606 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001607 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001608 HasNull = true;
1609 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1610 .getNumSuccessors() != 1) {
1611 HasCriticalEdges = true;
1612 break;
1613 }
1614 }
1615 // If we have null operands and no critical edges, optimize.
1616 if (!HasCriticalEdges && HasNull) {
1617 SmallPtrSet<Instruction *, 4> DependingInstructions;
1618 SmallPtrSet<const BasicBlock *, 4> Visited;
1619
1620 // Check that there is nothing that cares about the reference
1621 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001622 switch (Class) {
1623 case IC_Retain:
1624 case IC_RetainBlock:
1625 // These can always be moved up.
1626 break;
1627 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001628 // These can't be moved across things that care about the retain
1629 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001630 FindDependencies(NeedsPositiveRetainCount, Arg,
1631 Inst->getParent(), Inst,
1632 DependingInstructions, Visited, PA);
1633 break;
1634 case IC_Autorelease:
1635 // These can't be moved across autorelease pool scope boundaries.
1636 FindDependencies(AutoreleasePoolBoundary, Arg,
1637 Inst->getParent(), Inst,
1638 DependingInstructions, Visited, PA);
1639 break;
1640 case IC_RetainRV:
1641 case IC_AutoreleaseRV:
1642 // Don't move these; the RV optimization depends on the autoreleaseRV
1643 // being tail called, and the retainRV being immediately after a call
1644 // (which might still happen if we get lucky with codegen layout, but
1645 // it's not worth taking the chance).
1646 continue;
1647 default:
1648 llvm_unreachable("Invalid dependence flavor");
1649 }
1650
John McCalld935e9c2011-06-15 23:37:01 +00001651 if (DependingInstructions.size() == 1 &&
1652 *DependingInstructions.begin() == PN) {
1653 Changed = true;
1654 ++NumPartialNoops;
1655 // Clone the call into each predecessor that has a non-null value.
1656 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001657 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001658 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1659 Value *Incoming =
1660 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001661 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001662 CallInst *Clone = cast<CallInst>(CInst->clone());
1663 Value *Op = PN->getIncomingValue(i);
1664 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1665 if (Op->getType() != ParamTy)
1666 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1667 Clone->setArgOperand(0, Op);
1668 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001669
Michael Gottesman89279f82013-04-05 18:10:41 +00001670 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001671 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001672 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001673 Worklist.push_back(std::make_pair(Clone, Incoming));
1674 }
1675 }
1676 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001677 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001678 EraseInstruction(CInst);
1679 continue;
1680 }
1681 }
1682 } while (!Worklist.empty());
1683 }
1684}
1685
Michael Gottesman323964c2013-04-18 05:39:45 +00001686/// If we have a top down pointer in the S_Use state, make sure that there are
1687/// no CFG hazards by checking the states of various bottom up pointers.
1688static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1689 const bool SuccSRRIKnownSafe,
1690 PtrState &S,
1691 bool &SomeSuccHasSame,
1692 bool &AllSuccsHaveSame,
1693 bool &ShouldContinue) {
1694 switch (SuccSSeq) {
1695 case S_CanRelease: {
1696 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1697 S.ClearSequenceProgress();
1698 break;
1699 }
1700 ShouldContinue = true;
1701 break;
1702 }
1703 case S_Use:
1704 SomeSuccHasSame = true;
1705 break;
1706 case S_Stop:
1707 case S_Release:
1708 case S_MovableRelease:
1709 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1710 AllSuccsHaveSame = false;
1711 break;
1712 case S_Retain:
1713 llvm_unreachable("bottom-up pointer in retain state!");
1714 case S_None:
1715 llvm_unreachable("This should have been handled earlier.");
1716 }
1717}
1718
1719/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1720/// there are no CFG hazards by checking the states of various bottom up
1721/// pointers.
1722static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1723 const bool SuccSRRIKnownSafe,
1724 PtrState &S,
1725 bool &SomeSuccHasSame,
1726 bool &AllSuccsHaveSame) {
1727 switch (SuccSSeq) {
1728 case S_CanRelease:
1729 SomeSuccHasSame = true;
1730 break;
1731 case S_Stop:
1732 case S_Release:
1733 case S_MovableRelease:
1734 case S_Use:
1735 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1736 AllSuccsHaveSame = false;
1737 break;
1738 case S_Retain:
1739 llvm_unreachable("bottom-up pointer in retain state!");
1740 case S_None:
1741 llvm_unreachable("This should have been handled earlier.");
1742 }
1743}
1744
Michael Gottesman97e3df02013-01-14 00:35:14 +00001745/// Check for critical edges, loop boundaries, irreducible control flow, or
1746/// other CFG structures where moving code across the edge would result in it
1747/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001748void
1749ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1750 DenseMap<const BasicBlock *, BBState> &BBStates,
1751 BBState &MyStates) const {
1752 // If any top-down local-use or possible-dec has a succ which is earlier in
1753 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001754 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001755 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1756 PtrState &S = I->second;
1757 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001758
Michael Gottesman323964c2013-04-18 05:39:45 +00001759 // We only care about S_Retain, S_CanRelease, and S_Use.
1760 if (Seq == S_None)
1761 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001762
Michael Gottesman323964c2013-04-18 05:39:45 +00001763 // Make sure that if extra top down states are added in the future that this
1764 // code is updated to handle it.
1765 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1766 "Unknown top down sequence state.");
1767
1768 const Value *Arg = I->first;
1769 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1770 bool SomeSuccHasSame = false;
1771 bool AllSuccsHaveSame = true;
1772
1773 succ_const_iterator SI(TI), SE(TI, false);
1774
1775 for (; SI != SE; ++SI) {
1776 // If VisitBottomUp has pointer information for this successor, take
1777 // what we know about it.
1778 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1779 BBStates.find(*SI);
1780 assert(BBI != BBStates.end());
1781 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1782 const Sequence SuccSSeq = SuccS.GetSeq();
1783
1784 // If bottom up, the pointer is in an S_None state, clear the sequence
1785 // progress since the sequence in the bottom up state finished
1786 // suggesting a mismatch in between retains/releases. This is true for
1787 // all three cases that we are handling here: S_Retain, S_Use, and
1788 // S_CanRelease.
1789 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001790 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001791 continue;
1792 }
1793
1794 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1795 // checks.
1796 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1797
1798 // *NOTE* We do not use Seq from above here since we are allowing for
1799 // S.GetSeq() to change while we are visiting basic blocks.
1800 switch(S.GetSeq()) {
1801 case S_Use: {
1802 bool ShouldContinue = false;
1803 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1804 SomeSuccHasSame, AllSuccsHaveSame,
1805 ShouldContinue);
1806 if (ShouldContinue)
1807 continue;
1808 break;
1809 }
1810 case S_CanRelease: {
1811 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe,
1812 S, SomeSuccHasSame,
1813 AllSuccsHaveSame);
1814 break;
1815 }
1816 case S_Retain:
1817 case S_None:
1818 case S_Stop:
1819 case S_Release:
1820 case S_MovableRelease:
1821 break;
1822 }
John McCalld935e9c2011-06-15 23:37:01 +00001823 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001824
1825 // If the state at the other end of any of the successor edges
1826 // matches the current state, require all edges to match. This
1827 // guards against loops in the middle of a sequence.
1828 if (SomeSuccHasSame && !AllSuccsHaveSame)
1829 S.ClearSequenceProgress();
1830 }
John McCalld935e9c2011-06-15 23:37:01 +00001831}
1832
1833bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001834ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001835 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001836 MapVector<Value *, RRInfo> &Retains,
1837 BBState &MyStates) {
1838 bool NestingDetected = false;
1839 InstructionClass Class = GetInstructionClass(Inst);
1840 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001841
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001842 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001843
Dan Gohman817a7c62012-03-22 18:24:56 +00001844 switch (Class) {
1845 case IC_Release: {
1846 Arg = GetObjCArg(Inst);
1847
1848 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1849
1850 // If we see two releases in a row on the same pointer. If so, make
1851 // a note, and we'll cicle back to revisit it after we've
1852 // hopefully eliminated the second release, which may allow us to
1853 // eliminate the first release too.
1854 // Theoretically we could implement removal of nested retain+release
1855 // pairs by making PtrState hold a stack of states, but this is
1856 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001857 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001858 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001859 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001860 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001861
Dan Gohman817a7c62012-03-22 18:24:56 +00001862 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001863 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1864 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1865 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001866 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001867 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001868 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1869 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001870 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001871 break;
1872 }
1873 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001874 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1875 // objc_retainBlocks to objc_retains. Thus at this point any
1876 // objc_retainBlocks that we see are not optimizable.
1877 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001878 case IC_Retain:
1879 case IC_RetainRV: {
1880 Arg = GetObjCArg(Inst);
1881
1882 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001883 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001884
Michael Gottesman81b1d432013-03-26 00:42:04 +00001885 Sequence OldSeq = S.GetSeq();
1886 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001887 case S_Stop:
1888 case S_Release:
1889 case S_MovableRelease:
1890 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001891 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1892 // imprecise release, clear our reverse insertion points.
1893 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1894 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001895 // FALL THROUGH
1896 case S_CanRelease:
1897 // Don't do retain+release tracking for IC_RetainRV, because it's
1898 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001899 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001900 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001901 S.ClearSequenceProgress();
1902 break;
1903 case S_None:
1904 break;
1905 case S_Retain:
1906 llvm_unreachable("bottom-up pointer in retain state!");
1907 }
Michael Gottesman79249972013-04-05 23:46:45 +00001908 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001909 // A retain moving bottom up can be a use.
1910 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001911 }
1912 case IC_AutoreleasepoolPop:
1913 // Conservatively, clear MyStates for all known pointers.
1914 MyStates.clearBottomUpPointers();
1915 return NestingDetected;
1916 case IC_AutoreleasepoolPush:
1917 case IC_None:
1918 // These are irrelevant.
1919 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001920 case IC_User:
1921 // If we have a store into an alloca of a pointer we are tracking, the
1922 // pointer has multiple owners implying that we must be more conservative.
1923 //
1924 // This comes up in the context of a pointer being ``KnownSafe''. In the
1925 // presense of a block being initialized, the frontend will emit the
1926 // objc_retain on the original pointer and the release on the pointer loaded
1927 // from the alloca. The optimizer will through the provenance analysis
1928 // realize that the two are related, but since we only require KnownSafe in
1929 // one direction, will match the inner retain on the original pointer with
1930 // the guard release on the original pointer. This is fixed by ensuring that
1931 // in the presense of allocas we only unconditionally remove pointers if
1932 // both our retain and our release are KnownSafe.
1933 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1934 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1935 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1936 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1937 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001938 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001939 }
1940 }
1941 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001942 default:
1943 break;
1944 }
1945
1946 // Consider any other possible effects of this instruction on each
1947 // pointer being tracked.
1948 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1949 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1950 const Value *Ptr = MI->first;
1951 if (Ptr == Arg)
1952 continue; // Handled above.
1953 PtrState &S = MI->second;
1954 Sequence Seq = S.GetSeq();
1955
1956 // Check for possible releases.
1957 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001958 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1959 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001960 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001961 switch (Seq) {
1962 case S_Use:
1963 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001964 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001965 continue;
1966 case S_CanRelease:
1967 case S_Release:
1968 case S_MovableRelease:
1969 case S_Stop:
1970 case S_None:
1971 break;
1972 case S_Retain:
1973 llvm_unreachable("bottom-up pointer in retain state!");
1974 }
1975 }
1976
1977 // Check for possible direct uses.
1978 switch (Seq) {
1979 case S_Release:
1980 case S_MovableRelease:
1981 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001982 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1983 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001984 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001985 // If this is an invoke instruction, we're scanning it as part of
1986 // one of its successor blocks, since we can't insert code after it
1987 // in its own block, and we don't want to split critical edges.
1988 if (isa<InvokeInst>(Inst))
1989 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1990 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001991 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001992 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001993 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001994 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001995 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1996 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001997 // Non-movable releases depend on any possible objc pointer use.
1998 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001999 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00002000 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002001 // As above; handle invoke specially.
2002 if (isa<InvokeInst>(Inst))
2003 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2004 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002005 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002006 }
2007 break;
2008 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002009 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002010 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2011 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002012 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002013 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2014 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002015 break;
2016 case S_CanRelease:
2017 case S_Use:
2018 case S_None:
2019 break;
2020 case S_Retain:
2021 llvm_unreachable("bottom-up pointer in retain state!");
2022 }
2023 }
2024
2025 return NestingDetected;
2026}
2027
2028bool
John McCalld935e9c2011-06-15 23:37:01 +00002029ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2030 DenseMap<const BasicBlock *, BBState> &BBStates,
2031 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002032
2033 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002034
John McCalld935e9c2011-06-15 23:37:01 +00002035 bool NestingDetected = false;
2036 BBState &MyStates = BBStates[BB];
2037
2038 // Merge the states from each successor to compute the initial state
2039 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002040 BBState::edge_iterator SI(MyStates.succ_begin()),
2041 SE(MyStates.succ_end());
2042 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002043 const BasicBlock *Succ = *SI;
2044 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2045 assert(I != BBStates.end());
2046 MyStates.InitFromSucc(I->second);
2047 ++SI;
2048 for (; SI != SE; ++SI) {
2049 Succ = *SI;
2050 I = BBStates.find(Succ);
2051 assert(I != BBStates.end());
2052 MyStates.MergeSucc(I->second);
2053 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002054 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002055
Michael Gottesman43e7e002013-04-03 22:41:59 +00002056 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002057 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002058 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002059
John McCalld935e9c2011-06-15 23:37:01 +00002060 // Visit all the instructions, bottom-up.
2061 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2062 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002063
2064 // Invoke instructions are visited as part of their successors (below).
2065 if (isa<InvokeInst>(Inst))
2066 continue;
2067
Michael Gottesman89279f82013-04-05 18:10:41 +00002068 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002069
Dan Gohman5c70fad2012-03-23 17:47:54 +00002070 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2071 }
2072
Dan Gohmandae33492012-04-27 18:56:31 +00002073 // If there's a predecessor with an invoke, visit the invoke as if it were
2074 // part of this block, since we can't insert code after an invoke in its own
2075 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002076 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2077 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002078 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002079 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2080 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002081 }
John McCalld935e9c2011-06-15 23:37:01 +00002082
Michael Gottesman43e7e002013-04-03 22:41:59 +00002083 // If ARC Annotations are enabled, output the current state of pointers at the
2084 // top of the basic block.
2085 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002086
Dan Gohman817a7c62012-03-22 18:24:56 +00002087 return NestingDetected;
2088}
John McCalld935e9c2011-06-15 23:37:01 +00002089
Dan Gohman817a7c62012-03-22 18:24:56 +00002090bool
2091ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2092 DenseMap<Value *, RRInfo> &Releases,
2093 BBState &MyStates) {
2094 bool NestingDetected = false;
2095 InstructionClass Class = GetInstructionClass(Inst);
2096 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002097
Dan Gohman817a7c62012-03-22 18:24:56 +00002098 switch (Class) {
2099 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002100 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2101 // objc_retainBlocks to objc_retains. Thus at this point any
2102 // objc_retainBlocks that we see are not optimizable.
2103 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002104 case IC_Retain:
2105 case IC_RetainRV: {
2106 Arg = GetObjCArg(Inst);
2107
2108 PtrState &S = MyStates.getPtrTopDownState(Arg);
2109
2110 // Don't do retain+release tracking for IC_RetainRV, because it's
2111 // better to let it remain as the first instruction after a call.
2112 if (Class != IC_RetainRV) {
2113 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002114 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002115 // hopefully eliminated the second retain, which may allow us to
2116 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002117 // Theoretically we could implement removal of nested retain+release
2118 // pairs by making PtrState hold a stack of states, but this is
2119 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002120 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002121 NestingDetected = true;
2122
Michael Gottesman81b1d432013-03-26 00:42:04 +00002123 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002124 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002125 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002126 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002127 }
John McCalld935e9c2011-06-15 23:37:01 +00002128
Dan Gohmandf476e52012-09-04 23:16:20 +00002129 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002130
2131 // A retain can be a potential use; procede to the generic checking
2132 // code below.
2133 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002134 }
2135 case IC_Release: {
2136 Arg = GetObjCArg(Inst);
2137
2138 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002139 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002140
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002141 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002142
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002143 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002144
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002145 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002146 case S_Retain:
2147 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002148 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2149 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002150 // FALL THROUGH
2151 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002152 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002153 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2154 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002155 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002156 S.ClearSequenceProgress();
2157 break;
2158 case S_None:
2159 break;
2160 case S_Stop:
2161 case S_Release:
2162 case S_MovableRelease:
2163 llvm_unreachable("top-down pointer in release state!");
2164 }
2165 break;
2166 }
2167 case IC_AutoreleasepoolPop:
2168 // Conservatively, clear MyStates for all known pointers.
2169 MyStates.clearTopDownPointers();
2170 return NestingDetected;
2171 case IC_AutoreleasepoolPush:
2172 case IC_None:
2173 // These are irrelevant.
2174 return NestingDetected;
2175 default:
2176 break;
2177 }
2178
2179 // Consider any other possible effects of this instruction on each
2180 // pointer being tracked.
2181 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2182 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2183 const Value *Ptr = MI->first;
2184 if (Ptr == Arg)
2185 continue; // Handled above.
2186 PtrState &S = MI->second;
2187 Sequence Seq = S.GetSeq();
2188
2189 // Check for possible releases.
2190 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002191 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002192 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002193 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002194 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002195 case S_Retain:
2196 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002197 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002198 assert(S.RRI.ReverseInsertPts.empty());
2199 S.RRI.ReverseInsertPts.insert(Inst);
2200
2201 // One call can't cause a transition from S_Retain to S_CanRelease
2202 // and S_CanRelease to S_Use. If we've made the first transition,
2203 // we're done.
2204 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002205 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002206 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002207 case S_None:
2208 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002209 case S_Stop:
2210 case S_Release:
2211 case S_MovableRelease:
2212 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002213 }
2214 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002215
2216 // Check for possible direct uses.
2217 switch (Seq) {
2218 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002219 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002220 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2221 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002222 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002223 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2224 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002225 break;
2226 case S_Retain:
2227 case S_Use:
2228 case S_None:
2229 break;
2230 case S_Stop:
2231 case S_Release:
2232 case S_MovableRelease:
2233 llvm_unreachable("top-down pointer in release state!");
2234 }
John McCalld935e9c2011-06-15 23:37:01 +00002235 }
2236
2237 return NestingDetected;
2238}
2239
2240bool
2241ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2242 DenseMap<const BasicBlock *, BBState> &BBStates,
2243 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002244 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002245 bool NestingDetected = false;
2246 BBState &MyStates = BBStates[BB];
2247
2248 // Merge the states from each predecessor to compute the initial state
2249 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002250 BBState::edge_iterator PI(MyStates.pred_begin()),
2251 PE(MyStates.pred_end());
2252 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002253 const BasicBlock *Pred = *PI;
2254 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2255 assert(I != BBStates.end());
2256 MyStates.InitFromPred(I->second);
2257 ++PI;
2258 for (; PI != PE; ++PI) {
2259 Pred = *PI;
2260 I = BBStates.find(Pred);
2261 assert(I != BBStates.end());
2262 MyStates.MergePred(I->second);
2263 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002264 }
John McCalld935e9c2011-06-15 23:37:01 +00002265
Michael Gottesman43e7e002013-04-03 22:41:59 +00002266 // If ARC Annotations are enabled, output the current state of pointers at the
2267 // top of the basic block.
2268 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002269
John McCalld935e9c2011-06-15 23:37:01 +00002270 // Visit all the instructions, top-down.
2271 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2272 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002273
Michael Gottesman89279f82013-04-05 18:10:41 +00002274 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002275
Dan Gohman817a7c62012-03-22 18:24:56 +00002276 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002277 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002278
Michael Gottesman43e7e002013-04-03 22:41:59 +00002279 // If ARC Annotations are enabled, output the current state of pointers at the
2280 // bottom of the basic block.
2281 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002282
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002283#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002284 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002285#endif
John McCalld935e9c2011-06-15 23:37:01 +00002286 CheckForCFGHazards(BB, BBStates, MyStates);
2287 return NestingDetected;
2288}
2289
Dan Gohmana53a12c2011-12-12 19:42:25 +00002290static void
2291ComputePostOrders(Function &F,
2292 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002293 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2294 unsigned NoObjCARCExceptionsMDKind,
2295 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002296 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002297 SmallPtrSet<BasicBlock *, 16> Visited;
2298
2299 // Do DFS, computing the PostOrder.
2300 SmallPtrSet<BasicBlock *, 16> OnStack;
2301 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002302
2303 // Functions always have exactly one entry block, and we don't have
2304 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002305 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002306 BBState &MyStates = BBStates[EntryBB];
2307 MyStates.SetAsEntry();
2308 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2309 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002310 Visited.insert(EntryBB);
2311 OnStack.insert(EntryBB);
2312 do {
2313 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002314 BasicBlock *CurrBB = SuccStack.back().first;
2315 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2316 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002317
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002318 while (SuccStack.back().second != SE) {
2319 BasicBlock *SuccBB = *SuccStack.back().second++;
2320 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002321 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2322 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002323 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002324 BBState &SuccStates = BBStates[SuccBB];
2325 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002326 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002327 goto dfs_next_succ;
2328 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002329
2330 if (!OnStack.count(SuccBB)) {
2331 BBStates[CurrBB].addSucc(SuccBB);
2332 BBStates[SuccBB].addPred(CurrBB);
2333 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002334 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002335 OnStack.erase(CurrBB);
2336 PostOrder.push_back(CurrBB);
2337 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002338 } while (!SuccStack.empty());
2339
2340 Visited.clear();
2341
Dan Gohmana53a12c2011-12-12 19:42:25 +00002342 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002343 // Functions may have many exits, and there also blocks which we treat
2344 // as exits due to ignored edges.
2345 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2346 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2347 BasicBlock *ExitBB = I;
2348 BBState &MyStates = BBStates[ExitBB];
2349 if (!MyStates.isExit())
2350 continue;
2351
Dan Gohmandae33492012-04-27 18:56:31 +00002352 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002353
2354 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002355 Visited.insert(ExitBB);
2356 while (!PredStack.empty()) {
2357 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002358 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2359 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002360 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002361 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002362 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002363 goto reverse_dfs_next_succ;
2364 }
2365 }
2366 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2367 }
2368 }
2369}
2370
Michael Gottesman97e3df02013-01-14 00:35:14 +00002371// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002372bool
2373ObjCARCOpt::Visit(Function &F,
2374 DenseMap<const BasicBlock *, BBState> &BBStates,
2375 MapVector<Value *, RRInfo> &Retains,
2376 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002377
2378 // Use reverse-postorder traversals, because we magically know that loops
2379 // will be well behaved, i.e. they won't repeatedly call retain on a single
2380 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2381 // class here because we want the reverse-CFG postorder to consider each
2382 // function exit point, and we want to ignore selected cycle edges.
2383 SmallVector<BasicBlock *, 16> PostOrder;
2384 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002385 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2386 NoObjCARCExceptionsMDKind,
2387 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002388
2389 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002390 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002391 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002392 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2393 I != E; ++I)
2394 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002395
Dan Gohmana53a12c2011-12-12 19:42:25 +00002396 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002397 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002398 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2399 PostOrder.rbegin(), E = PostOrder.rend();
2400 I != E; ++I)
2401 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002402
2403 return TopDownNestingDetected && BottomUpNestingDetected;
2404}
2405
Michael Gottesman97e3df02013-01-14 00:35:14 +00002406/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002407void ObjCARCOpt::MoveCalls(Value *Arg,
2408 RRInfo &RetainsToMove,
2409 RRInfo &ReleasesToMove,
2410 MapVector<Value *, RRInfo> &Retains,
2411 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002412 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002413 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002414 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002415 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002416
Michael Gottesman89279f82013-04-05 18:10:41 +00002417 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002418
John McCalld935e9c2011-06-15 23:37:01 +00002419 // Insert the new retain and release calls.
2420 for (SmallPtrSet<Instruction *, 2>::const_iterator
2421 PI = ReleasesToMove.ReverseInsertPts.begin(),
2422 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2423 Instruction *InsertPt = *PI;
2424 Value *MyArg = ArgTy == ParamTy ? Arg :
2425 new BitCastInst(Arg, ParamTy, "", InsertPt);
2426 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002427 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002428 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002429 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002430
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002431 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002432 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002433 }
2434 for (SmallPtrSet<Instruction *, 2>::const_iterator
2435 PI = RetainsToMove.ReverseInsertPts.begin(),
2436 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002437 Instruction *InsertPt = *PI;
2438 Value *MyArg = ArgTy == ParamTy ? Arg :
2439 new BitCastInst(Arg, ParamTy, "", InsertPt);
2440 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2441 "", InsertPt);
2442 // Attach a clang.imprecise_release metadata tag, if appropriate.
2443 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2444 Call->setMetadata(ImpreciseReleaseMDKind, M);
2445 Call->setDoesNotThrow();
2446 if (ReleasesToMove.IsTailCallRelease)
2447 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002448
Michael Gottesman89279f82013-04-05 18:10:41 +00002449 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2450 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002451 }
2452
2453 // Delete the original retain and release calls.
2454 for (SmallPtrSet<Instruction *, 2>::const_iterator
2455 AI = RetainsToMove.Calls.begin(),
2456 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2457 Instruction *OrigRetain = *AI;
2458 Retains.blot(OrigRetain);
2459 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002460 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002461 }
2462 for (SmallPtrSet<Instruction *, 2>::const_iterator
2463 AI = ReleasesToMove.Calls.begin(),
2464 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2465 Instruction *OrigRelease = *AI;
2466 Releases.erase(OrigRelease);
2467 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002468 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002469 }
Michael Gottesman79249972013-04-05 23:46:45 +00002470
John McCalld935e9c2011-06-15 23:37:01 +00002471}
2472
Michael Gottesman9de6f962013-01-22 21:49:00 +00002473bool
2474ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2475 &BBStates,
2476 MapVector<Value *, RRInfo> &Retains,
2477 DenseMap<Value *, RRInfo> &Releases,
2478 Module *M,
2479 SmallVector<Instruction *, 4> &NewRetains,
2480 SmallVector<Instruction *, 4> &NewReleases,
2481 SmallVector<Instruction *, 8> &DeadInsts,
2482 RRInfo &RetainsToMove,
2483 RRInfo &ReleasesToMove,
2484 Value *Arg,
2485 bool KnownSafe,
2486 bool &AnyPairsCompletelyEliminated) {
2487 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002488 // is already incremented, we can similarly ignore possible decrements unless
2489 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002490 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002491 bool MultipleOwners = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002492
2493 // Connect the dots between the top-down-collected RetainsToMove and
2494 // bottom-up-collected ReleasesToMove to form sets of related calls.
2495 // This is an iterative process so that we connect multiple releases
2496 // to multiple retains if needed.
2497 unsigned OldDelta = 0;
2498 unsigned NewDelta = 0;
2499 unsigned OldCount = 0;
2500 unsigned NewCount = 0;
2501 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002502 for (;;) {
2503 for (SmallVectorImpl<Instruction *>::const_iterator
2504 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2505 Instruction *NewRetain = *NI;
2506 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2507 assert(It != Retains.end());
2508 const RRInfo &NewRetainRRI = It->second;
2509 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002510 MultipleOwners =
2511 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002512 for (SmallPtrSet<Instruction *, 2>::const_iterator
2513 LI = NewRetainRRI.Calls.begin(),
2514 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2515 Instruction *NewRetainRelease = *LI;
2516 DenseMap<Value *, RRInfo>::const_iterator Jt =
2517 Releases.find(NewRetainRelease);
2518 if (Jt == Releases.end())
2519 return false;
2520 const RRInfo &NewRetainReleaseRRI = Jt->second;
2521 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2522 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2523 OldDelta -=
2524 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2525
2526 // Merge the ReleaseMetadata and IsTailCallRelease values.
2527 if (FirstRelease) {
2528 ReleasesToMove.ReleaseMetadata =
2529 NewRetainReleaseRRI.ReleaseMetadata;
2530 ReleasesToMove.IsTailCallRelease =
2531 NewRetainReleaseRRI.IsTailCallRelease;
2532 FirstRelease = false;
2533 } else {
2534 if (ReleasesToMove.ReleaseMetadata !=
2535 NewRetainReleaseRRI.ReleaseMetadata)
2536 ReleasesToMove.ReleaseMetadata = 0;
2537 if (ReleasesToMove.IsTailCallRelease !=
2538 NewRetainReleaseRRI.IsTailCallRelease)
2539 ReleasesToMove.IsTailCallRelease = false;
2540 }
2541
2542 // Collect the optimal insertion points.
2543 if (!KnownSafe)
2544 for (SmallPtrSet<Instruction *, 2>::const_iterator
2545 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2546 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2547 RI != RE; ++RI) {
2548 Instruction *RIP = *RI;
2549 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2550 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2551 }
2552 NewReleases.push_back(NewRetainRelease);
2553 }
2554 }
2555 }
2556 NewRetains.clear();
2557 if (NewReleases.empty()) break;
2558
2559 // Back the other way.
2560 for (SmallVectorImpl<Instruction *>::const_iterator
2561 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2562 Instruction *NewRelease = *NI;
2563 DenseMap<Value *, RRInfo>::const_iterator It =
2564 Releases.find(NewRelease);
2565 assert(It != Releases.end());
2566 const RRInfo &NewReleaseRRI = It->second;
2567 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2568 for (SmallPtrSet<Instruction *, 2>::const_iterator
2569 LI = NewReleaseRRI.Calls.begin(),
2570 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2571 Instruction *NewReleaseRetain = *LI;
2572 MapVector<Value *, RRInfo>::const_iterator Jt =
2573 Retains.find(NewReleaseRetain);
2574 if (Jt == Retains.end())
2575 return false;
2576 const RRInfo &NewReleaseRetainRRI = Jt->second;
2577 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2578 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2579 unsigned PathCount =
2580 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2581 OldDelta += PathCount;
2582 OldCount += PathCount;
2583
Michael Gottesman9de6f962013-01-22 21:49:00 +00002584 // Collect the optimal insertion points.
2585 if (!KnownSafe)
2586 for (SmallPtrSet<Instruction *, 2>::const_iterator
2587 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2588 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2589 RI != RE; ++RI) {
2590 Instruction *RIP = *RI;
2591 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2592 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2593 NewDelta += PathCount;
2594 NewCount += PathCount;
2595 }
2596 }
2597 NewRetains.push_back(NewReleaseRetain);
2598 }
2599 }
2600 }
2601 NewReleases.clear();
2602 if (NewRetains.empty()) break;
2603 }
2604
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002605 // If the pointer is known incremented in 1 direction and we do not have
2606 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2607 // to be known safe in both directions.
2608 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2609 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2610 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002611 RetainsToMove.ReverseInsertPts.clear();
2612 ReleasesToMove.ReverseInsertPts.clear();
2613 NewCount = 0;
2614 } else {
2615 // Determine whether the new insertion points we computed preserve the
2616 // balance of retain and release calls through the program.
2617 // TODO: If the fully aggressive solution isn't valid, try to find a
2618 // less aggressive solution which is.
2619 if (NewDelta != 0)
2620 return false;
2621 }
2622
2623 // Determine whether the original call points are balanced in the retain and
2624 // release calls through the program. If not, conservatively don't touch
2625 // them.
2626 // TODO: It's theoretically possible to do code motion in this case, as
2627 // long as the existing imbalances are maintained.
2628 if (OldDelta != 0)
2629 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002630
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002631#ifdef ARC_ANNOTATIONS
2632 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002633 if (EnableARCAnnotations)
2634 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002635#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002636
2637 Changed = true;
2638 assert(OldCount != 0 && "Unreachable code?");
2639 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002640 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002641 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002642
2643 // We can move calls!
2644 return true;
2645}
2646
Michael Gottesman97e3df02013-01-14 00:35:14 +00002647/// Identify pairings between the retains and releases, and delete and/or move
2648/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002649bool
2650ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2651 &BBStates,
2652 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002653 DenseMap<Value *, RRInfo> &Releases,
2654 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002655 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2656
John McCalld935e9c2011-06-15 23:37:01 +00002657 bool AnyPairsCompletelyEliminated = false;
2658 RRInfo RetainsToMove;
2659 RRInfo ReleasesToMove;
2660 SmallVector<Instruction *, 4> NewRetains;
2661 SmallVector<Instruction *, 4> NewReleases;
2662 SmallVector<Instruction *, 8> DeadInsts;
2663
Dan Gohman670f9372012-04-13 18:57:48 +00002664 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002665 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002666 E = Retains.end(); I != E; ++I) {
2667 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002668 if (!V) continue; // blotted
2669
2670 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002671
Michael Gottesman89279f82013-04-05 18:10:41 +00002672 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002673
John McCalld935e9c2011-06-15 23:37:01 +00002674 Value *Arg = GetObjCArg(Retain);
2675
Dan Gohman728db492012-01-13 00:39:07 +00002676 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002677 // not being managed by ObjC reference counting, so we can delete pairs
2678 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002679 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002680
Dan Gohman56e1cef2011-08-22 17:29:11 +00002681 // A constant pointer can't be pointing to an object on the heap. It may
2682 // be reference-counted, but it won't be deleted.
2683 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2684 if (const GlobalVariable *GV =
2685 dyn_cast<GlobalVariable>(
2686 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2687 if (GV->isConstant())
2688 KnownSafe = true;
2689
John McCalld935e9c2011-06-15 23:37:01 +00002690 // Connect the dots between the top-down-collected RetainsToMove and
2691 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002692 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002693 bool PerformMoveCalls =
2694 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2695 NewReleases, DeadInsts, RetainsToMove,
2696 ReleasesToMove, Arg, KnownSafe,
2697 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002698
Michael Gottesman9de6f962013-01-22 21:49:00 +00002699 if (PerformMoveCalls) {
2700 // Ok, everything checks out and we're all set. Let's move/delete some
2701 // code!
2702 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2703 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002704 }
2705
Michael Gottesman9de6f962013-01-22 21:49:00 +00002706 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002707 NewReleases.clear();
2708 NewRetains.clear();
2709 RetainsToMove.clear();
2710 ReleasesToMove.clear();
2711 }
2712
2713 // Now that we're done moving everything, we can delete the newly dead
2714 // instructions, as we no longer need them as insert points.
2715 while (!DeadInsts.empty())
2716 EraseInstruction(DeadInsts.pop_back_val());
2717
2718 return AnyPairsCompletelyEliminated;
2719}
2720
Michael Gottesman97e3df02013-01-14 00:35:14 +00002721/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002722void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002723 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002724
John McCalld935e9c2011-06-15 23:37:01 +00002725 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2726 // itself because it uses AliasAnalysis and we need to do provenance
2727 // queries instead.
2728 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2729 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002730
Michael Gottesman89279f82013-04-05 18:10:41 +00002731 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002732
John McCalld935e9c2011-06-15 23:37:01 +00002733 InstructionClass Class = GetBasicInstructionClass(Inst);
2734 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2735 continue;
2736
2737 // Delete objc_loadWeak calls with no users.
2738 if (Class == IC_LoadWeak && Inst->use_empty()) {
2739 Inst->eraseFromParent();
2740 continue;
2741 }
2742
2743 // TODO: For now, just look for an earlier available version of this value
2744 // within the same block. Theoretically, we could do memdep-style non-local
2745 // analysis too, but that would want caching. A better approach would be to
2746 // use the technique that EarlyCSE uses.
2747 inst_iterator Current = llvm::prior(I);
2748 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2749 for (BasicBlock::iterator B = CurrentBB->begin(),
2750 J = Current.getInstructionIterator();
2751 J != B; --J) {
2752 Instruction *EarlierInst = &*llvm::prior(J);
2753 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2754 switch (EarlierClass) {
2755 case IC_LoadWeak:
2756 case IC_LoadWeakRetained: {
2757 // If this is loading from the same pointer, replace this load's value
2758 // with that one.
2759 CallInst *Call = cast<CallInst>(Inst);
2760 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2761 Value *Arg = Call->getArgOperand(0);
2762 Value *EarlierArg = EarlierCall->getArgOperand(0);
2763 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2764 case AliasAnalysis::MustAlias:
2765 Changed = true;
2766 // If the load has a builtin retain, insert a plain retain for it.
2767 if (Class == IC_LoadWeakRetained) {
2768 CallInst *CI =
2769 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2770 "", Call);
2771 CI->setTailCall();
2772 }
2773 // Zap the fully redundant load.
2774 Call->replaceAllUsesWith(EarlierCall);
2775 Call->eraseFromParent();
2776 goto clobbered;
2777 case AliasAnalysis::MayAlias:
2778 case AliasAnalysis::PartialAlias:
2779 goto clobbered;
2780 case AliasAnalysis::NoAlias:
2781 break;
2782 }
2783 break;
2784 }
2785 case IC_StoreWeak:
2786 case IC_InitWeak: {
2787 // If this is storing to the same pointer and has the same size etc.
2788 // replace this load's value with the stored value.
2789 CallInst *Call = cast<CallInst>(Inst);
2790 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2791 Value *Arg = Call->getArgOperand(0);
2792 Value *EarlierArg = EarlierCall->getArgOperand(0);
2793 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2794 case AliasAnalysis::MustAlias:
2795 Changed = true;
2796 // If the load has a builtin retain, insert a plain retain for it.
2797 if (Class == IC_LoadWeakRetained) {
2798 CallInst *CI =
2799 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2800 "", Call);
2801 CI->setTailCall();
2802 }
2803 // Zap the fully redundant load.
2804 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2805 Call->eraseFromParent();
2806 goto clobbered;
2807 case AliasAnalysis::MayAlias:
2808 case AliasAnalysis::PartialAlias:
2809 goto clobbered;
2810 case AliasAnalysis::NoAlias:
2811 break;
2812 }
2813 break;
2814 }
2815 case IC_MoveWeak:
2816 case IC_CopyWeak:
2817 // TOOD: Grab the copied value.
2818 goto clobbered;
2819 case IC_AutoreleasepoolPush:
2820 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002821 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002822 case IC_User:
2823 // Weak pointers are only modified through the weak entry points
2824 // (and arbitrary calls, which could call the weak entry points).
2825 break;
2826 default:
2827 // Anything else could modify the weak pointer.
2828 goto clobbered;
2829 }
2830 }
2831 clobbered:;
2832 }
2833
2834 // Then, for each destroyWeak with an alloca operand, check to see if
2835 // the alloca and all its users can be zapped.
2836 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2837 Instruction *Inst = &*I++;
2838 InstructionClass Class = GetBasicInstructionClass(Inst);
2839 if (Class != IC_DestroyWeak)
2840 continue;
2841
2842 CallInst *Call = cast<CallInst>(Inst);
2843 Value *Arg = Call->getArgOperand(0);
2844 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2845 for (Value::use_iterator UI = Alloca->use_begin(),
2846 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002847 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002848 switch (GetBasicInstructionClass(UserInst)) {
2849 case IC_InitWeak:
2850 case IC_StoreWeak:
2851 case IC_DestroyWeak:
2852 continue;
2853 default:
2854 goto done;
2855 }
2856 }
2857 Changed = true;
2858 for (Value::use_iterator UI = Alloca->use_begin(),
2859 UE = Alloca->use_end(); UI != UE; ) {
2860 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002861 switch (GetBasicInstructionClass(UserInst)) {
2862 case IC_InitWeak:
2863 case IC_StoreWeak:
2864 // These functions return their second argument.
2865 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2866 break;
2867 case IC_DestroyWeak:
2868 // No return value.
2869 break;
2870 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002871 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002872 }
John McCalld935e9c2011-06-15 23:37:01 +00002873 UserInst->eraseFromParent();
2874 }
2875 Alloca->eraseFromParent();
2876 done:;
2877 }
2878 }
2879}
2880
Michael Gottesman97e3df02013-01-14 00:35:14 +00002881/// Identify program paths which execute sequences of retains and releases which
2882/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002883bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002884 // Releases, Retains - These are used to store the results of the main flow
2885 // analysis. These use Value* as the key instead of Instruction* so that the
2886 // map stays valid when we get around to rewriting code and calls get
2887 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002888 DenseMap<Value *, RRInfo> Releases;
2889 MapVector<Value *, RRInfo> Retains;
2890
Michael Gottesman740db972013-05-23 02:35:21 +00002891 // This is used during the traversal of the function to track the
2892 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002893 DenseMap<const BasicBlock *, BBState> BBStates;
2894
2895 // Analyze the CFG of the function, and all instructions.
2896 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2897
2898 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002899 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2900 Releases,
2901 F.getParent());
2902
2903 // Cleanup.
2904 MultiOwnersSet.clear();
2905
2906 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002907}
2908
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002909/// Check if there is a dependent call earlier that does not have anything in
2910/// between the Retain and the call that can affect the reference count of their
2911/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002912static bool
2913HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2914 SmallPtrSet<Instruction *, 4> &DepInsts,
2915 SmallPtrSet<const BasicBlock *, 4> &Visited,
2916 ProvenanceAnalysis &PA) {
2917 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2918 DepInsts, Visited, PA);
2919 if (DepInsts.size() != 1)
2920 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002921
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002922 CallInst *Call =
2923 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002924
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002925 // Check that the pointer is the return value of the call.
2926 if (!Call || Arg != Call)
2927 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002928
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002929 // Check that the call is a regular call.
2930 InstructionClass Class = GetBasicInstructionClass(Call);
2931 if (Class != IC_CallOrUser && Class != IC_Call)
2932 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002933
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002934 return true;
2935}
2936
Michael Gottesman6908db12013-04-03 23:16:05 +00002937/// Find a dependent retain that precedes the given autorelease for which there
2938/// is nothing in between the two instructions that can affect the ref count of
2939/// Arg.
2940static CallInst *
2941FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2942 Instruction *Autorelease,
2943 SmallPtrSet<Instruction *, 4> &DepInsts,
2944 SmallPtrSet<const BasicBlock *, 4> &Visited,
2945 ProvenanceAnalysis &PA) {
2946 FindDependencies(CanChangeRetainCount, Arg,
2947 BB, Autorelease, DepInsts, Visited, PA);
2948 if (DepInsts.size() != 1)
2949 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002950
Michael Gottesman6908db12013-04-03 23:16:05 +00002951 CallInst *Retain =
2952 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002953
Michael Gottesman6908db12013-04-03 23:16:05 +00002954 // Check that we found a retain with the same argument.
2955 if (!Retain ||
2956 !IsRetain(GetBasicInstructionClass(Retain)) ||
2957 GetObjCArg(Retain) != Arg) {
2958 return 0;
2959 }
Michael Gottesman79249972013-04-05 23:46:45 +00002960
Michael Gottesman6908db12013-04-03 23:16:05 +00002961 return Retain;
2962}
2963
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002964/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2965/// no instructions dependent on Arg that need a positive ref count in between
2966/// the autorelease and the ret.
2967static CallInst *
2968FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2969 ReturnInst *Ret,
2970 SmallPtrSet<Instruction *, 4> &DepInsts,
2971 SmallPtrSet<const BasicBlock *, 4> &V,
2972 ProvenanceAnalysis &PA) {
2973 FindDependencies(NeedsPositiveRetainCount, Arg,
2974 BB, Ret, DepInsts, V, PA);
2975 if (DepInsts.size() != 1)
2976 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002977
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002978 CallInst *Autorelease =
2979 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2980 if (!Autorelease)
2981 return 0;
2982 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2983 if (!IsAutorelease(AutoreleaseClass))
2984 return 0;
2985 if (GetObjCArg(Autorelease) != Arg)
2986 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002987
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002988 return Autorelease;
2989}
2990
Michael Gottesman97e3df02013-01-14 00:35:14 +00002991/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002992/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002993/// %call = call i8* @something(...)
2994/// %2 = call i8* @objc_retain(i8* %call)
2995/// %3 = call i8* @objc_autorelease(i8* %2)
2996/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002997/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002998/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002999void ObjCARCOpt::OptimizeReturns(Function &F) {
3000 if (!F.getReturnType()->isPointerTy())
3001 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003002
Michael Gottesman89279f82013-04-05 18:10:41 +00003003 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003004
John McCalld935e9c2011-06-15 23:37:01 +00003005 SmallPtrSet<Instruction *, 4> DependingInstructions;
3006 SmallPtrSet<const BasicBlock *, 4> Visited;
3007 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3008 BasicBlock *BB = FI;
3009 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003010
Michael Gottesman89279f82013-04-05 18:10:41 +00003011 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003012
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003013 if (!Ret)
3014 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003015
John McCalld935e9c2011-06-15 23:37:01 +00003016 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003017
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003018 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003019 // dependent on Arg such that there are no instructions dependent on Arg
3020 // that need a positive ref count in between the autorelease and Ret.
3021 CallInst *Autorelease =
3022 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3023 DependingInstructions, Visited,
3024 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003025 DependingInstructions.clear();
3026 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003027
3028 if (!Autorelease)
3029 continue;
3030
3031 CallInst *Retain =
3032 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3033 DependingInstructions, Visited, PA);
3034 DependingInstructions.clear();
3035 Visited.clear();
3036
3037 if (!Retain)
3038 continue;
3039
3040 // Check that there is nothing that can affect the reference count
3041 // between the retain and the call. Note that Retain need not be in BB.
3042 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3043 DependingInstructions,
3044 Visited, PA);
3045 DependingInstructions.clear();
3046 Visited.clear();
3047
3048 if (!HasSafePathToCall)
3049 continue;
3050
3051 // If so, we can zap the retain and autorelease.
3052 Changed = true;
3053 ++NumRets;
3054 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3055 << *Autorelease << "\n");
3056 EraseInstruction(Retain);
3057 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003058 }
3059}
3060
Michael Gottesman9c118152013-04-29 06:16:57 +00003061#ifndef NDEBUG
3062void
3063ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3064 llvm::Statistic &NumRetains =
3065 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3066 llvm::Statistic &NumReleases =
3067 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3068
3069 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3070 Instruction *Inst = &*I++;
3071 switch (GetBasicInstructionClass(Inst)) {
3072 default:
3073 break;
3074 case IC_Retain:
3075 ++NumRetains;
3076 break;
3077 case IC_Release:
3078 ++NumReleases;
3079 break;
3080 }
3081 }
3082}
3083#endif
3084
John McCalld935e9c2011-06-15 23:37:01 +00003085bool ObjCARCOpt::doInitialization(Module &M) {
3086 if (!EnableARCOpts)
3087 return false;
3088
Dan Gohman670f9372012-04-13 18:57:48 +00003089 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003090 Run = ModuleHasARC(M);
3091 if (!Run)
3092 return false;
3093
John McCalld935e9c2011-06-15 23:37:01 +00003094 // Identify the imprecise release metadata kind.
3095 ImpreciseReleaseMDKind =
3096 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003097 CopyOnEscapeMDKind =
3098 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003099 NoObjCARCExceptionsMDKind =
3100 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003101#ifdef ARC_ANNOTATIONS
3102 ARCAnnotationBottomUpMDKind =
3103 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3104 ARCAnnotationTopDownMDKind =
3105 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3106 ARCAnnotationProvenanceSourceMDKind =
3107 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3108#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003109
John McCalld935e9c2011-06-15 23:37:01 +00003110 // Intuitively, objc_retain and others are nocapture, however in practice
3111 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003112 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003113
3114 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003115 AutoreleaseRVCallee = 0;
3116 ReleaseCallee = 0;
3117 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003118 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003119 AutoreleaseCallee = 0;
3120
3121 return false;
3122}
3123
3124bool ObjCARCOpt::runOnFunction(Function &F) {
3125 if (!EnableARCOpts)
3126 return false;
3127
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003128 // If nothing in the Module uses ARC, don't do anything.
3129 if (!Run)
3130 return false;
3131
John McCalld935e9c2011-06-15 23:37:01 +00003132 Changed = false;
3133
Michael Gottesman89279f82013-04-05 18:10:41 +00003134 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3135 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003136
John McCalld935e9c2011-06-15 23:37:01 +00003137 PA.setAA(&getAnalysis<AliasAnalysis>());
3138
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003139#ifndef NDEBUG
3140 if (AreStatisticsEnabled()) {
3141 GatherStatistics(F, false);
3142 }
3143#endif
3144
John McCalld935e9c2011-06-15 23:37:01 +00003145 // This pass performs several distinct transformations. As a compile-time aid
3146 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3147 // library functions aren't declared.
3148
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003149 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003150 OptimizeIndividualCalls(F);
3151
3152 // Optimizations for weak pointers.
3153 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3154 (1 << IC_LoadWeakRetained) |
3155 (1 << IC_StoreWeak) |
3156 (1 << IC_InitWeak) |
3157 (1 << IC_CopyWeak) |
3158 (1 << IC_MoveWeak) |
3159 (1 << IC_DestroyWeak)))
3160 OptimizeWeakCalls(F);
3161
3162 // Optimizations for retain+release pairs.
3163 if (UsedInThisFunction & ((1 << IC_Retain) |
3164 (1 << IC_RetainRV) |
3165 (1 << IC_RetainBlock)))
3166 if (UsedInThisFunction & (1 << IC_Release))
3167 // Run OptimizeSequences until it either stops making changes or
3168 // no retain+release pair nesting is detected.
3169 while (OptimizeSequences(F)) {}
3170
3171 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003172 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3173 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003174 OptimizeReturns(F);
3175
Michael Gottesman9c118152013-04-29 06:16:57 +00003176 // Gather statistics after optimization.
3177#ifndef NDEBUG
3178 if (AreStatisticsEnabled()) {
3179 GatherStatistics(F, true);
3180 }
3181#endif
3182
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003183 DEBUG(dbgs() << "\n");
3184
John McCalld935e9c2011-06-15 23:37:01 +00003185 return Changed;
3186}
3187
3188void ObjCARCOpt::releaseMemory() {
3189 PA.clear();
3190}
3191
Michael Gottesman97e3df02013-01-14 00:35:14 +00003192/// @}
3193///