Michael Gottesman | 79d8d81 | 2013-01-28 01:35:51 +0000 | [diff] [blame] | 1 | //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2 | // |
| 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 Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 9 | /// \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 Gottesman | 697d8b9 | 2013-02-07 04:12:57 +0000 | [diff] [blame] | 16 | /// redundant weak pointer operations, and numerous minor simplifications. |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 17 | /// |
| 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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 25 | //===----------------------------------------------------------------------===// |
| 26 | |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 27 | #define DEBUG_TYPE "objc-arc-opts" |
| 28 | #include "ObjCARC.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 29 | #include "DependencyAnalysis.h" |
Michael Gottesman | 294e7da | 2013-01-28 05:51:54 +0000 | [diff] [blame] | 30 | #include "ObjCARCAliasAnalysis.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 31 | #include "ProvenanceAnalysis.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/DenseMap.h" |
Michael Gottesman | 5a91bbf | 2013-05-24 20:44:02 +0000 | [diff] [blame] | 33 | #include "llvm/ADT/DenseSet.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 34 | #include "llvm/ADT/STLExtras.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/SmallPtrSet.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 36 | #include "llvm/ADT/Statistic.h" |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 37 | #include "llvm/IR/IRBuilder.h" |
Michael Gottesman | 278266f | 2013-01-29 04:20:52 +0000 | [diff] [blame] | 38 | #include "llvm/IR/LLVMContext.h" |
Michael Gottesman | 778138e | 2013-01-29 03:03:03 +0000 | [diff] [blame] | 39 | #include "llvm/Support/CFG.h" |
Michael Gottesman | 13a5f1a | 2013-01-29 04:51:59 +0000 | [diff] [blame] | 40 | #include "llvm/Support/Debug.h" |
Timur Iskhodzhanov | 5d7ff00 | 2013-01-29 09:09:27 +0000 | [diff] [blame] | 41 | #include "llvm/Support/raw_ostream.h" |
Michael Gottesman | fa0939f | 2013-01-28 04:12:07 +0000 | [diff] [blame] | 42 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 43 | using namespace llvm; |
Michael Gottesman | 08904e3 | 2013-01-28 03:28:38 +0000 | [diff] [blame] | 44 | using namespace llvm::objcarc; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 45 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 46 | /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific. |
| 47 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 48 | |
| 49 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 50 | /// \brief An associative container with fast insertion-order (deterministic) |
| 51 | /// iteration over its elements. Plus the special blot operation. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 52 | template<class KeyT, class ValueT> |
| 53 | class MapVector { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 54 | /// Map keys to indices in Vector. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 55 | typedef DenseMap<KeyT, size_t> MapTy; |
| 56 | MapTy Map; |
| 57 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 58 | typedef std::vector<std::pair<KeyT, ValueT> > VectorTy; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 59 | /// Keys and values. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 60 | 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 Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 86 | ValueT &operator[](const KeyT &Arg) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 87 | std::pair<typename MapTy::iterator, bool> Pair = |
| 88 | Map.insert(std::make_pair(Arg, size_t(0))); |
| 89 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 90 | size_t Num = Vector.size(); |
| 91 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 92 | Vector.push_back(std::make_pair(Arg, ValueT())); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 93 | return Vector[Num].second; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 94 | } |
| 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 Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 103 | size_t Num = Vector.size(); |
| 104 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 105 | Vector.push_back(InsertPair); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 106 | return std::make_pair(Vector.begin() + Num, true); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 107 | } |
| 108 | return std::make_pair(Vector.begin() + Pair.first->second, false); |
| 109 | } |
| 110 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 111 | 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 Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 117 | const_iterator find(const KeyT &Key) const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 118 | 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 Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 123 | /// 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 Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 126 | void blot(const KeyT &Key) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 127 | 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 Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 140 | /// @} |
| 141 | /// |
| 142 | /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. |
| 143 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 144 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 145 | /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon |
| 146 | /// as it finds a value with multiple uses. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 147 | static 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 Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 162 | // 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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 164 | 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 Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 178 | /// \brief Test whether the given retainable object pointer escapes. |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 179 | /// |
| 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 Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 183 | static bool DoesRetainableObjPtrEscape(const User *Ptr) { |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 184 | DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 185 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 186 | // Walk the def-use chains. |
| 187 | SmallVector<const Value *, 4> Worklist; |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 188 | Worklist.push_back(Ptr); |
| 189 | // If Ptr has any operands add them as well. |
Michael Gottesman | 23cda0c | 2013-01-29 21:07:53 +0000 | [diff] [blame] | 190 | for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E; |
| 191 | ++I) { |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 192 | Worklist.push_back(*I); |
| 193 | } |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 194 | |
| 195 | // Ensure we do not visit any value twice. |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 196 | SmallPtrSet<const Value *, 8> VisitedSet; |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 197 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 198 | do { |
| 199 | const Value *V = Worklist.pop_back_val(); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 200 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 201 | DEBUG(dbgs() << "Visiting: " << *V << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 202 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 203 | for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); |
| 204 | UI != UE; ++UI) { |
| 205 | const User *UUser = *UI; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 206 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 207 | DEBUG(dbgs() << "User: " << *UUser << "\n"); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 208 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 209 | // Special - Use by a call (callee or argument) is not considered |
| 210 | // to be an escape. |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 211 | switch (GetBasicInstructionClass(UUser)) { |
| 212 | case IC_StoreWeak: |
| 213 | case IC_InitWeak: |
| 214 | case IC_StoreStrong: |
| 215 | case IC_Autorelease: |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 216 | case IC_AutoreleaseRV: { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 217 | DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n"); |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 218 | // These special functions make copies of their pointer arguments. |
| 219 | return true; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 220 | } |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 221 | case IC_IntrinsicUser: |
| 222 | // Use by the use intrinsic is not an escape. |
| 223 | continue; |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 224 | 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 Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 230 | |
Michael Gottesman | f4b7761 | 2013-02-23 00:31:32 +0000 | [diff] [blame] | 231 | if (VisitedSet.insert(UUser)) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 232 | DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes." |
| 233 | " Adding to list.\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 234 | Worklist.push_back(UUser); |
| 235 | } else { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 236 | DEBUG(dbgs() << "Already visited node.\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 237 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 238 | 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 Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 250 | continue; |
| 251 | } |
Dan Gohman | eb6e015 | 2012-02-13 22:57:02 +0000 | [diff] [blame] | 252 | // Otherwise, conservatively assume an escape. |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 253 | DEBUG(dbgs() << "Assuming ptr escapes.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 254 | return true; |
| 255 | } |
| 256 | } while (!Worklist.empty()); |
| 257 | |
| 258 | // No escapes found. |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 259 | DEBUG(dbgs() << "Ptr does not escape.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 260 | return false; |
| 261 | } |
| 262 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 263 | /// This is a wrapper around getUnderlyingObjCPtr along the lines of |
| 264 | /// GetUnderlyingObjects except that it returns early when it sees the first |
| 265 | /// alloca. |
| 266 | static 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 Gottesman | 0c8b562 | 2013-05-14 06:40:10 +0000 | [diff] [blame] | 273 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 274 | if (isa<AllocaInst>(P)) |
| 275 | return true; |
Michael Gottesman | 0c8b562 | 2013-05-14 06:40:10 +0000 | [diff] [blame] | 276 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 277 | if (!Visited.insert(P)) |
| 278 | continue; |
Michael Gottesman | 0c8b562 | 2013-05-14 06:40:10 +0000 | [diff] [blame] | 279 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 280 | 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 Gottesman | 0c8b562 | 2013-05-14 06:40:10 +0000 | [diff] [blame] | 285 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 286 | 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 Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 297 | /// @} |
| 298 | /// |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 299 | /// \defgroup ARCOpt ARC Optimization. |
| 300 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 301 | |
| 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 Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 336 | // TODO: The pointer returned from objc_loadWeakRetained is retained. |
| 337 | |
| 338 | // TODO: Delete release+retain pairs (rare). |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 339 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 340 | STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); |
| 341 | STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); |
| 342 | STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); |
| 343 | STATISTIC(NumRets, "Number of return value forwarding " |
Michael Gottesman | b4e7f4d | 2013-05-15 17:43:03 +0000 | [diff] [blame] | 344 | "retain+autoreleases eliminated"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 345 | STATISTIC(NumRRs, "Number of retain+release paths eliminated"); |
| 346 | STATISTIC(NumPeeps, "Number of calls peephole-optimized"); |
Matt Beaumont-Gay | e55d949 | 2013-05-13 21:10:49 +0000 | [diff] [blame] | 347 | #ifndef NDEBUG |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 348 | STATISTIC(NumRetainsBeforeOpt, |
Michael Gottesman | b4e7f4d | 2013-05-15 17:43:03 +0000 | [diff] [blame] | 349 | "Number of retains before optimization"); |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 350 | STATISTIC(NumReleasesBeforeOpt, |
Michael Gottesman | b4e7f4d | 2013-05-15 17:43:03 +0000 | [diff] [blame] | 351 | "Number of releases before optimization"); |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 352 | STATISTIC(NumRetainsAfterOpt, |
Michael Gottesman | b4e7f4d | 2013-05-15 17:43:03 +0000 | [diff] [blame] | 353 | "Number of retains after optimization"); |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 354 | STATISTIC(NumReleasesAfterOpt, |
Michael Gottesman | b4e7f4d | 2013-05-15 17:43:03 +0000 | [diff] [blame] | 355 | "Number of releases after optimization"); |
Michael Gottesman | 03cf3c8 | 2013-04-29 07:29:08 +0000 | [diff] [blame] | 356 | #endif |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 357 | |
| 358 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 359 | /// \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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 363 | enum Sequence { |
| 364 | S_None, |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 365 | 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 Gottesman | 386241c | 2013-01-29 21:39:02 +0000 | [diff] [blame] | 368 | S_Stop, ///< like S_Release, but code motion is stopped. |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 369 | S_Release, ///< objc_release(x). |
Michael Gottesman | 9bdab2b | 2013-01-29 21:41:44 +0000 | [diff] [blame] | 370 | S_MovableRelease ///< objc_release(x), !clang.imprecise_release. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 371 | }; |
Michael Gottesman | 53fd20b | 2013-01-29 21:07:51 +0000 | [diff] [blame] | 372 | |
| 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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 394 | } |
| 395 | |
| 396 | static 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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 403 | if (A > B) std::swap(A, B); |
| 404 | if (TopDown) { |
| 405 | // Choose the side which is further along in the sequence. |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 406 | if ((A == S_Retain || A == S_CanRelease) && |
| 407 | (B == S_CanRelease || B == S_Use)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 408 | return B; |
| 409 | } else { |
| 410 | // Choose the side which is further along in the sequence. |
| 411 | if ((A == S_Use || A == S_CanRelease) && |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 412 | (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 413 | 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 | |
| 424 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 425 | /// \brief Unidirectional information about either a |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 426 | /// retain-decrement-use-release sequence or release-use-decrement-retain |
Bob Wilson | 798a770 | 2013-04-09 22:15:51 +0000 | [diff] [blame] | 427 | /// reverse sequence. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 428 | struct RRInfo { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 429 | /// After an objc_retain, the reference count of the referenced |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 430 | /// 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 McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 442 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 443 | /// True of the objc_release calls are all marked with the "tail" keyword. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 444 | bool IsTailCallRelease; |
| 445 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 446 | /// If the Calls are objc_release calls and they all have a |
| 447 | /// clang.imprecise_release tag, this is the metadata tag. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 448 | MDNode *ReleaseMetadata; |
| 449 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 450 | /// For a top-down sequence, the set of objc_retains or |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 451 | /// objc_retainBlocks. For bottom-up, the set of objc_releases. |
| 452 | SmallPtrSet<Instruction *, 2> Calls; |
| 453 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 454 | /// The set of optimal insert positions for moving calls in the opposite |
| 455 | /// sequence. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 456 | SmallPtrSet<Instruction *, 2> ReverseInsertPts; |
| 457 | |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 458 | /// If this is true, we cannot perform code motion but can still remove |
| 459 | /// retain/release pairs. |
| 460 | bool CFGHazardAfflicted; |
| 461 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 462 | RRInfo() : |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 463 | KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0), |
| 464 | CFGHazardAfflicted(false) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 465 | |
| 466 | void clear(); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 467 | |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 468 | bool IsTrackingImpreciseReleases() { |
| 469 | return ReleaseMetadata != 0; |
| 470 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 471 | }; |
| 472 | } |
| 473 | |
| 474 | void RRInfo::clear() { |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 475 | KnownSafe = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 476 | IsTailCallRelease = false; |
| 477 | ReleaseMetadata = 0; |
| 478 | Calls.clear(); |
| 479 | ReverseInsertPts.clear(); |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 480 | CFGHazardAfflicted = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 481 | } |
| 482 | |
| 483 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 484 | /// \brief This class summarizes several per-pointer runtime properties which |
| 485 | /// are propogated through the flow graph. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 486 | class PtrState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 487 | /// True if the reference count is known to be incremented. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 488 | bool KnownPositiveRefCount; |
| 489 | |
Bob Wilson | 798a770 | 2013-04-09 22:15:51 +0000 | [diff] [blame] | 490 | /// True if we've seen an opportunity for partial RR elimination, such as |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 491 | /// pushing calls into a CFG triangle or into one side of a CFG diamond. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 492 | bool Partial; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 493 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 494 | /// The current position in the sequence. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 495 | Sequence Seq : 8; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 496 | |
| 497 | public: |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 498 | /// Unidirectional information about the current sequence. |
| 499 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 500 | /// TODO: Encapsulate this better. |
| 501 | RRInfo RRI; |
| 502 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 503 | PtrState() : KnownPositiveRefCount(false), Partial(false), |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 504 | Seq(S_None) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 505 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 506 | void SetKnownPositiveRefCount() { |
Michael Gottesman | f3f9e3b | 2013-05-14 00:08:09 +0000 | [diff] [blame] | 507 | DEBUG(dbgs() << "Setting Known Positive.\n"); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 508 | KnownPositiveRefCount = true; |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 509 | } |
| 510 | |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 511 | void ClearKnownPositiveRefCount() { |
Michael Gottesman | f3f9e3b | 2013-05-14 00:08:09 +0000 | [diff] [blame] | 512 | DEBUG(dbgs() << "Clearing Known Positive.\n"); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 513 | KnownPositiveRefCount = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 514 | } |
| 515 | |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 516 | bool HasKnownPositiveRefCount() const { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 517 | return KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 518 | } |
| 519 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 520 | void SetSeq(Sequence NewSeq) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 521 | DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 522 | Seq = NewSeq; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 523 | } |
| 524 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 525 | Sequence GetSeq() const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 526 | return Seq; |
| 527 | } |
| 528 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 529 | void ClearSequenceProgress() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 530 | ResetSequenceProgress(S_None); |
| 531 | } |
| 532 | |
Michael Gottesman | 415ddd7 | 2013-02-05 19:32:18 +0000 | [diff] [blame] | 533 | void ResetSequenceProgress(Sequence NewSeq) { |
Michael Gottesman | 01338a4 | 2013-04-20 23:36:57 +0000 | [diff] [blame] | 534 | DEBUG(dbgs() << "Resetting sequence progress.\n"); |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 535 | SetSeq(NewSeq); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 536 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 537 | RRI.clear(); |
| 538 | } |
| 539 | |
| 540 | void Merge(const PtrState &Other, bool TopDown); |
| 541 | }; |
| 542 | } |
| 543 | |
| 544 | void |
| 545 | PtrState::Merge(const PtrState &Other, bool TopDown) { |
| 546 | Seq = MergeSeqs(Seq, Other.Seq, TopDown); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 547 | KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount; |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 548 | |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 549 | // If we're not in a sequence (anymore), drop all associated state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 550 | if (Seq == S_None) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 551 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 552 | RRI.clear(); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 553 | } else if (Partial || Other.Partial) { |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 554 | // If we're doing a merge on a path that's previously seen a partial |
| 555 | // merge, conservatively drop the sequence, to avoid doing partial |
| 556 | // RR elimination. If the branch predicates for the two merge differ, |
| 557 | // mixing them is unsafe. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 558 | ClearSequenceProgress(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 559 | } else { |
| 560 | // Conservatively merge the ReleaseMetadata information. |
| 561 | if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata) |
| 562 | RRI.ReleaseMetadata = 0; |
| 563 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 564 | RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 565 | RRI.IsTailCallRelease = RRI.IsTailCallRelease && |
| 566 | Other.RRI.IsTailCallRelease; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 567 | RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end()); |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 568 | RRI.CFGHazardAfflicted |= Other.RRI.CFGHazardAfflicted; |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 569 | |
| 570 | // Merge the insert point sets. If there are any differences, |
| 571 | // that makes this a partial merge. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 572 | Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size(); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 573 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 574 | I = Other.RRI.ReverseInsertPts.begin(), |
| 575 | E = Other.RRI.ReverseInsertPts.end(); I != E; ++I) |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 576 | Partial |= RRI.ReverseInsertPts.insert(*I); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 577 | } |
| 578 | } |
| 579 | |
| 580 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 581 | /// \brief Per-BasicBlock state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 582 | class BBState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 583 | /// The number of unique control paths from the entry which can reach this |
| 584 | /// block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 585 | unsigned TopDownPathCount; |
| 586 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 587 | /// The number of unique control paths to exits from this block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 588 | unsigned BottomUpPathCount; |
| 589 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 590 | /// A type for PerPtrTopDown and PerPtrBottomUp. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 591 | typedef MapVector<const Value *, PtrState> MapTy; |
| 592 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 593 | /// The top-down traversal uses this to record information known about a |
| 594 | /// pointer at the bottom of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 595 | MapTy PerPtrTopDown; |
| 596 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 597 | /// The bottom-up traversal uses this to record information known about a |
| 598 | /// pointer at the top of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 599 | MapTy PerPtrBottomUp; |
| 600 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 601 | /// Effective predecessors of the current block ignoring ignorable edges and |
| 602 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 603 | SmallVector<BasicBlock *, 2> Preds; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 604 | /// Effective successors of the current block ignoring ignorable edges and |
| 605 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 606 | SmallVector<BasicBlock *, 2> Succs; |
| 607 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 608 | public: |
| 609 | BBState() : TopDownPathCount(0), BottomUpPathCount(0) {} |
| 610 | |
| 611 | typedef MapTy::iterator ptr_iterator; |
| 612 | typedef MapTy::const_iterator ptr_const_iterator; |
| 613 | |
| 614 | ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } |
| 615 | ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } |
| 616 | ptr_const_iterator top_down_ptr_begin() const { |
| 617 | return PerPtrTopDown.begin(); |
| 618 | } |
| 619 | ptr_const_iterator top_down_ptr_end() const { |
| 620 | return PerPtrTopDown.end(); |
| 621 | } |
| 622 | |
| 623 | ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); } |
| 624 | ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } |
| 625 | ptr_const_iterator bottom_up_ptr_begin() const { |
| 626 | return PerPtrBottomUp.begin(); |
| 627 | } |
| 628 | ptr_const_iterator bottom_up_ptr_end() const { |
| 629 | return PerPtrBottomUp.end(); |
| 630 | } |
| 631 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 632 | /// Mark this block as being an entry block, which has one path from the |
| 633 | /// entry by definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 634 | void SetAsEntry() { TopDownPathCount = 1; } |
| 635 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 636 | /// Mark this block as being an exit block, which has one path to an exit by |
| 637 | /// definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 638 | void SetAsExit() { BottomUpPathCount = 1; } |
| 639 | |
Michael Gottesman | 993fbf7 | 2013-05-13 19:40:39 +0000 | [diff] [blame] | 640 | /// Attempt to find the PtrState object describing the top down state for |
| 641 | /// pointer Arg. Return a new initialized PtrState describing the top down |
| 642 | /// state for Arg if we do not find one. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 643 | PtrState &getPtrTopDownState(const Value *Arg) { |
| 644 | return PerPtrTopDown[Arg]; |
| 645 | } |
| 646 | |
Michael Gottesman | 993fbf7 | 2013-05-13 19:40:39 +0000 | [diff] [blame] | 647 | /// Attempt to find the PtrState object describing the bottom up state for |
| 648 | /// pointer Arg. Return a new initialized PtrState describing the bottom up |
| 649 | /// state for Arg if we do not find one. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 650 | PtrState &getPtrBottomUpState(const Value *Arg) { |
| 651 | return PerPtrBottomUp[Arg]; |
| 652 | } |
| 653 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 654 | /// Attempt to find the PtrState object describing the bottom up state for |
| 655 | /// pointer Arg. |
| 656 | ptr_iterator findPtrBottomUpState(const Value *Arg) { |
| 657 | return PerPtrBottomUp.find(Arg); |
| 658 | } |
| 659 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 660 | void clearBottomUpPointers() { |
Evan Cheng | e4df6a2 | 2011-08-04 18:40:26 +0000 | [diff] [blame] | 661 | PerPtrBottomUp.clear(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 662 | } |
| 663 | |
| 664 | void clearTopDownPointers() { |
| 665 | PerPtrTopDown.clear(); |
| 666 | } |
| 667 | |
| 668 | void InitFromPred(const BBState &Other); |
| 669 | void InitFromSucc(const BBState &Other); |
| 670 | void MergePred(const BBState &Other); |
| 671 | void MergeSucc(const BBState &Other); |
| 672 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 673 | /// Return the number of possible unique paths from an entry to an exit |
| 674 | /// which pass through this block. This is only valid after both the |
| 675 | /// top-down and bottom-up traversals are complete. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 676 | unsigned GetAllPathCount() const { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 677 | assert(TopDownPathCount != 0); |
| 678 | assert(BottomUpPathCount != 0); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 679 | return TopDownPathCount * BottomUpPathCount; |
| 680 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 681 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 682 | // Specialized CFG utilities. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 683 | typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 684 | edge_iterator pred_begin() { return Preds.begin(); } |
| 685 | edge_iterator pred_end() { return Preds.end(); } |
| 686 | edge_iterator succ_begin() { return Succs.begin(); } |
| 687 | edge_iterator succ_end() { return Succs.end(); } |
| 688 | |
| 689 | void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } |
| 690 | void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } |
| 691 | |
| 692 | bool isExit() const { return Succs.empty(); } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 693 | }; |
| 694 | } |
| 695 | |
| 696 | void BBState::InitFromPred(const BBState &Other) { |
| 697 | PerPtrTopDown = Other.PerPtrTopDown; |
| 698 | TopDownPathCount = Other.TopDownPathCount; |
| 699 | } |
| 700 | |
| 701 | void BBState::InitFromSucc(const BBState &Other) { |
| 702 | PerPtrBottomUp = Other.PerPtrBottomUp; |
| 703 | BottomUpPathCount = Other.BottomUpPathCount; |
| 704 | } |
| 705 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 706 | /// The top-down traversal uses this to merge information about predecessors to |
| 707 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 708 | void BBState::MergePred(const BBState &Other) { |
| 709 | // Other.TopDownPathCount can be 0, in which case it is either dead or a |
| 710 | // loop backedge. Loop backedges are special. |
| 711 | TopDownPathCount += Other.TopDownPathCount; |
| 712 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 713 | // Check for overflow. If we have overflow, fall back to conservative |
| 714 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 715 | if (TopDownPathCount < Other.TopDownPathCount) { |
| 716 | clearTopDownPointers(); |
| 717 | return; |
| 718 | } |
| 719 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 720 | // For each entry in the other set, if our set has an entry with the same key, |
| 721 | // merge the entries. Otherwise, copy the entry and merge it with an empty |
| 722 | // entry. |
| 723 | for (ptr_const_iterator MI = Other.top_down_ptr_begin(), |
| 724 | ME = Other.top_down_ptr_end(); MI != ME; ++MI) { |
| 725 | std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI); |
| 726 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 727 | /*TopDown=*/true); |
| 728 | } |
| 729 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 730 | // For each entry in our set, if the other set doesn't have an entry with the |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 731 | // same key, force it to merge with an empty entry. |
| 732 | for (ptr_iterator MI = top_down_ptr_begin(), |
| 733 | ME = top_down_ptr_end(); MI != ME; ++MI) |
| 734 | if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) |
| 735 | MI->second.Merge(PtrState(), /*TopDown=*/true); |
| 736 | } |
| 737 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 738 | /// The bottom-up traversal uses this to merge information about successors to |
| 739 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 740 | void BBState::MergeSucc(const BBState &Other) { |
| 741 | // Other.BottomUpPathCount can be 0, in which case it is either dead or a |
| 742 | // loop backedge. Loop backedges are special. |
| 743 | BottomUpPathCount += Other.BottomUpPathCount; |
| 744 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 745 | // Check for overflow. If we have overflow, fall back to conservative |
| 746 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 747 | if (BottomUpPathCount < Other.BottomUpPathCount) { |
| 748 | clearBottomUpPointers(); |
| 749 | return; |
| 750 | } |
| 751 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 752 | // For each entry in the other set, if our set has an entry with the |
| 753 | // same key, merge the entries. Otherwise, copy the entry and merge |
| 754 | // it with an empty entry. |
| 755 | for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(), |
| 756 | ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 757 | std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI); |
| 758 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 759 | /*TopDown=*/false); |
| 760 | } |
| 761 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 762 | // For each entry in our set, if the other set doesn't have an entry |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 763 | // with the same key, force it to merge with an empty entry. |
| 764 | for (ptr_iterator MI = bottom_up_ptr_begin(), |
| 765 | ME = bottom_up_ptr_end(); MI != ME; ++MI) |
| 766 | if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) |
| 767 | MI->second.Merge(PtrState(), /*TopDown=*/false); |
| 768 | } |
| 769 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 770 | // Only enable ARC Annotations if we are building a debug version of |
| 771 | // libObjCARCOpts. |
| 772 | #ifndef NDEBUG |
| 773 | #define ARC_ANNOTATIONS |
| 774 | #endif |
| 775 | |
| 776 | // Define some macros along the lines of DEBUG and some helper functions to make |
| 777 | // it cleaner to create annotations in the source code and to no-op when not |
| 778 | // building in debug mode. |
| 779 | #ifdef ARC_ANNOTATIONS |
| 780 | |
| 781 | #include "llvm/Support/CommandLine.h" |
| 782 | |
| 783 | /// Enable/disable ARC sequence annotations. |
| 784 | static cl::opt<bool> |
Michael Gottesman | 6806b51 | 2013-04-17 20:48:03 +0000 | [diff] [blame] | 785 | EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false), |
| 786 | cl::desc("Enable emission of arc data flow analysis " |
| 787 | "annotations")); |
Michael Gottesman | ffef24f | 2013-04-17 20:48:01 +0000 | [diff] [blame] | 788 | static cl::opt<bool> |
Michael Gottesman | adb921a | 2013-04-17 21:03:53 +0000 | [diff] [blame] | 789 | DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false), |
| 790 | cl::desc("Disable check for cfg hazards when " |
| 791 | "annotating")); |
Michael Gottesman | 4e88ce6 | 2013-04-17 21:59:41 +0000 | [diff] [blame] | 792 | static cl::opt<std::string> |
| 793 | ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier", |
| 794 | cl::init(""), |
| 795 | cl::desc("filter out all data flow annotations " |
| 796 | "but those that apply to the given " |
| 797 | "target llvm identifier.")); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 798 | |
| 799 | /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an |
| 800 | /// instruction so that we can track backwards when post processing via the llvm |
| 801 | /// arc annotation processor tool. If the function is an |
| 802 | static MDString *AppendMDNodeToSourcePtr(unsigned NodeId, |
| 803 | Value *Ptr) { |
| 804 | MDString *Hash = 0; |
| 805 | |
| 806 | // If pointer is a result of an instruction and it does not have a source |
| 807 | // MDNode it, attach a new MDNode onto it. If pointer is a result of |
| 808 | // an instruction and does have a source MDNode attached to it, return a |
| 809 | // reference to said Node. Otherwise just return 0. |
| 810 | if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) { |
| 811 | MDNode *Node; |
| 812 | if (!(Node = Inst->getMetadata(NodeId))) { |
| 813 | // We do not have any node. Generate and attatch the hash MDString to the |
| 814 | // instruction. |
| 815 | |
| 816 | // We just use an MDString to ensure that this metadata gets written out |
| 817 | // of line at the module level and to provide a very simple format |
| 818 | // encoding the information herein. Both of these makes it simpler to |
| 819 | // parse the annotations by a simple external program. |
| 820 | std::string Str; |
| 821 | raw_string_ostream os(Str); |
| 822 | os << "(" << Inst->getParent()->getParent()->getName() << ",%" |
| 823 | << Inst->getName() << ")"; |
| 824 | |
| 825 | Hash = MDString::get(Inst->getContext(), os.str()); |
| 826 | Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash)); |
| 827 | } else { |
| 828 | // We have a node. Grab its hash and return it. |
| 829 | assert(Node->getNumOperands() == 1 && |
| 830 | "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand."); |
| 831 | Hash = cast<MDString>(Node->getOperand(0)); |
| 832 | } |
| 833 | } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) { |
| 834 | std::string str; |
| 835 | raw_string_ostream os(str); |
| 836 | os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName() |
| 837 | << ")"; |
| 838 | Hash = MDString::get(Arg->getContext(), os.str()); |
| 839 | } |
| 840 | |
| 841 | return Hash; |
| 842 | } |
| 843 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 844 | static std::string SequenceToString(Sequence A) { |
| 845 | std::string str; |
| 846 | raw_string_ostream os(str); |
| 847 | os << A; |
| 848 | return os.str(); |
| 849 | } |
| 850 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 851 | /// Helper function to change a Sequence into a String object using our overload |
| 852 | /// for raw_ostream so we only have printing code in one location. |
| 853 | static MDString *SequenceToMDString(LLVMContext &Context, |
| 854 | Sequence A) { |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 855 | return MDString::get(Context, SequenceToString(A)); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 856 | } |
| 857 | |
| 858 | /// A simple function to generate a MDNode which describes the change in state |
| 859 | /// for Value *Ptr caused by Instruction *Inst. |
| 860 | static void AppendMDNodeToInstForPtr(unsigned NodeId, |
| 861 | Instruction *Inst, |
| 862 | Value *Ptr, |
| 863 | MDString *PtrSourceMDNodeID, |
| 864 | Sequence OldSeq, |
| 865 | Sequence NewSeq) { |
| 866 | MDNode *Node = 0; |
| 867 | Value *tmp[3] = {PtrSourceMDNodeID, |
| 868 | SequenceToMDString(Inst->getContext(), |
| 869 | OldSeq), |
| 870 | SequenceToMDString(Inst->getContext(), |
| 871 | NewSeq)}; |
| 872 | Node = MDNode::get(Inst->getContext(), |
| 873 | ArrayRef<Value*>(tmp, 3)); |
| 874 | |
| 875 | Inst->setMetadata(NodeId, Node); |
| 876 | } |
| 877 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 878 | /// Add to the beginning of the basic block llvm.ptr.annotations which show the |
| 879 | /// state of a pointer at the entrance to a basic block. |
| 880 | static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB, |
| 881 | Value *Ptr, Sequence Seq) { |
Michael Gottesman | 4e88ce6 | 2013-04-17 21:59:41 +0000 | [diff] [blame] | 882 | // If we have a target identifier, make sure that we match it before |
| 883 | // continuing. |
| 884 | if(!ARCAnnotationTargetIdentifier.empty() && |
| 885 | !Ptr->getName().equals(ARCAnnotationTargetIdentifier)) |
| 886 | return; |
Michael Gottesman | 9e51813 | 2013-04-18 04:34:11 +0000 | [diff] [blame] | 887 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 888 | Module *M = BB->getParent()->getParent(); |
| 889 | LLVMContext &C = M->getContext(); |
| 890 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 891 | Type *I8XX = PointerType::getUnqual(I8X); |
| 892 | Type *Params[] = {I8XX, I8XX}; |
| 893 | FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), |
| 894 | ArrayRef<Type*>(Params, 2), |
| 895 | /*isVarArg=*/false); |
| 896 | Constant *Callee = M->getOrInsertFunction(Name, FTy); |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 897 | |
| 898 | IRBuilder<> Builder(BB, BB->getFirstInsertionPt()); |
| 899 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 900 | Value *PtrName; |
| 901 | StringRef Tmp = Ptr->getName(); |
| 902 | if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) { |
| 903 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp, |
| 904 | Tmp + "_STR"); |
| 905 | PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 906 | cast<Constant>(ActualPtrName), Tmp); |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 907 | } |
| 908 | |
| 909 | Value *S; |
| 910 | std::string SeqStr = SequenceToString(Seq); |
| 911 | if (0 == (S = M->getGlobalVariable(SeqStr, true))) { |
| 912 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr, |
| 913 | SeqStr + "_STR"); |
| 914 | S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 915 | cast<Constant>(ActualPtrName), SeqStr); |
| 916 | } |
| 917 | |
| 918 | Builder.CreateCall2(Callee, PtrName, S); |
| 919 | } |
| 920 | |
| 921 | /// Add to the end of the basic block llvm.ptr.annotations which show the state |
| 922 | /// of the pointer at the bottom of the basic block. |
| 923 | static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB, |
| 924 | Value *Ptr, Sequence Seq) { |
Michael Gottesman | 4e88ce6 | 2013-04-17 21:59:41 +0000 | [diff] [blame] | 925 | // If we have a target identifier, make sure that we match it before emitting |
| 926 | // an annotation. |
| 927 | if(!ARCAnnotationTargetIdentifier.empty() && |
| 928 | !Ptr->getName().equals(ARCAnnotationTargetIdentifier)) |
| 929 | return; |
Michael Gottesman | 9e51813 | 2013-04-18 04:34:11 +0000 | [diff] [blame] | 930 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 931 | Module *M = BB->getParent()->getParent(); |
| 932 | LLVMContext &C = M->getContext(); |
| 933 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 934 | Type *I8XX = PointerType::getUnqual(I8X); |
| 935 | Type *Params[] = {I8XX, I8XX}; |
| 936 | FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), |
| 937 | ArrayRef<Type*>(Params, 2), |
| 938 | /*isVarArg=*/false); |
| 939 | Constant *Callee = M->getOrInsertFunction(Name, FTy); |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 940 | |
| 941 | IRBuilder<> Builder(BB, llvm::prior(BB->end())); |
| 942 | |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 943 | Value *PtrName; |
| 944 | StringRef Tmp = Ptr->getName(); |
| 945 | if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) { |
| 946 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp, |
| 947 | Tmp + "_STR"); |
| 948 | PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 949 | cast<Constant>(ActualPtrName), Tmp); |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 950 | } |
| 951 | |
| 952 | Value *S; |
| 953 | std::string SeqStr = SequenceToString(Seq); |
| 954 | if (0 == (S = M->getGlobalVariable(SeqStr, true))) { |
| 955 | Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr, |
| 956 | SeqStr + "_STR"); |
| 957 | S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage, |
| 958 | cast<Constant>(ActualPtrName), SeqStr); |
| 959 | } |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 960 | Builder.CreateCall2(Callee, PtrName, S); |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 961 | } |
| 962 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 963 | /// Adds a source annotation to pointer and a state change annotation to Inst |
| 964 | /// referencing the source annotation and the old/new state of pointer. |
| 965 | static void GenerateARCAnnotation(unsigned InstMDId, |
| 966 | unsigned PtrMDId, |
| 967 | Instruction *Inst, |
| 968 | Value *Ptr, |
| 969 | Sequence OldSeq, |
| 970 | Sequence NewSeq) { |
| 971 | if (EnableARCAnnotations) { |
Michael Gottesman | 4e88ce6 | 2013-04-17 21:59:41 +0000 | [diff] [blame] | 972 | // If we have a target identifier, make sure that we match it before |
| 973 | // emitting an annotation. |
| 974 | if(!ARCAnnotationTargetIdentifier.empty() && |
| 975 | !Ptr->getName().equals(ARCAnnotationTargetIdentifier)) |
| 976 | return; |
Michael Gottesman | 9e51813 | 2013-04-18 04:34:11 +0000 | [diff] [blame] | 977 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 978 | // First generate the source annotation on our pointer. This will return an |
| 979 | // MDString* if Ptr actually comes from an instruction implying we can put |
| 980 | // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL), |
| 981 | // then we know that our pointer is from an Argument so we put a reference |
| 982 | // to the argument number. |
| 983 | // |
| 984 | // The point of this is to make it easy for the |
| 985 | // llvm-arc-annotation-processor tool to cross reference where the source |
| 986 | // pointer is in the LLVM IR since the LLVM IR parser does not submit such |
| 987 | // information via debug info for backends to use (since why would anyone |
| 988 | // need such a thing from LLVM IR besides in non standard cases |
| 989 | // [i.e. this]). |
| 990 | MDString *SourcePtrMDNode = |
| 991 | AppendMDNodeToSourcePtr(PtrMDId, Ptr); |
| 992 | AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq, |
| 993 | NewSeq); |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | // The actual interface for accessing the above functionality is defined via |
| 998 | // some simple macros which are defined below. We do this so that the user does |
| 999 | // not need to pass in what metadata id is needed resulting in cleaner code and |
| 1000 | // additionally since it provides an easy way to conditionally no-op all |
| 1001 | // annotation support in a non-debug build. |
| 1002 | |
| 1003 | /// Use this macro to annotate a sequence state change when processing |
| 1004 | /// instructions bottom up, |
| 1005 | #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \ |
| 1006 | GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \ |
| 1007 | ARCAnnotationProvenanceSourceMDKind, (inst), \ |
| 1008 | const_cast<Value*>(ptr), (old), (new)) |
| 1009 | /// Use this macro to annotate a sequence state change when processing |
| 1010 | /// instructions top down. |
| 1011 | #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \ |
| 1012 | GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \ |
| 1013 | ARCAnnotationProvenanceSourceMDKind, (inst), \ |
| 1014 | const_cast<Value*>(ptr), (old), (new)) |
| 1015 | |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1016 | #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \ |
| 1017 | do { \ |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1018 | if (EnableARCAnnotations) { \ |
| 1019 | for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1020 | E = (_states)._direction##_ptr_end(); I != E; ++I) { \ |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1021 | Value *Ptr = const_cast<Value*>(I->first); \ |
| 1022 | Sequence Seq = I->second.GetSeq(); \ |
| 1023 | GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \ |
| 1024 | } \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1025 | } \ |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1026 | } while (0) |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1027 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1028 | #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1029 | ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \ |
| 1030 | Entrance, bottom_up) |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1031 | #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \ |
| 1032 | ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1033 | Terminator, bottom_up) |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1034 | #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \ |
| 1035 | ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1036 | Entrance, top_down) |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1037 | #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \ |
| 1038 | ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \ |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1039 | Terminator, top_down) |
| 1040 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1041 | #else // !ARC_ANNOTATION |
| 1042 | // If annotations are off, noop. |
| 1043 | #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) |
| 1044 | #define ANNOTATE_TOPDOWN(inst, ptr, old, new) |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 1045 | #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock) |
| 1046 | #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock) |
| 1047 | #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock) |
| 1048 | #define ANNOTATE_TOPDOWN_BBEND(states, basicblock) |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1049 | #endif // !ARC_ANNOTATION |
| 1050 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1051 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1052 | /// \brief The main ARC optimization pass. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1053 | class ObjCARCOpt : public FunctionPass { |
| 1054 | bool Changed; |
| 1055 | ProvenanceAnalysis PA; |
| 1056 | |
Michael Gottesman | 5a91bbf | 2013-05-24 20:44:02 +0000 | [diff] [blame] | 1057 | // This is used to track if a pointer is stored into an alloca. |
| 1058 | DenseSet<const Value *> MultiOwnersSet; |
| 1059 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1060 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 1061 | bool Run; |
| 1062 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1063 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 1064 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 1065 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1066 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1067 | /// Declaration for ObjC runtime function objc_autoreleaseReturnValue. |
| 1068 | Constant *AutoreleaseRVCallee; |
| 1069 | /// Declaration for ObjC runtime function objc_release. |
| 1070 | Constant *ReleaseCallee; |
| 1071 | /// Declaration for ObjC runtime function objc_retain. |
| 1072 | Constant *RetainCallee; |
| 1073 | /// Declaration for ObjC runtime function objc_retainBlock. |
| 1074 | Constant *RetainBlockCallee; |
| 1075 | /// Declaration for ObjC runtime function objc_autorelease. |
| 1076 | Constant *AutoreleaseCallee; |
| 1077 | |
| 1078 | /// Flags which determine whether each of the interesting runtine functions |
| 1079 | /// is in fact used in the current function. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1080 | unsigned UsedInThisFunction; |
| 1081 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1082 | /// The Metadata Kind for clang.imprecise_release metadata. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1083 | unsigned ImpreciseReleaseMDKind; |
| 1084 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1085 | /// The Metadata Kind for clang.arc.copy_on_escape metadata. |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 1086 | unsigned CopyOnEscapeMDKind; |
| 1087 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1088 | /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata. |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1089 | unsigned NoObjCARCExceptionsMDKind; |
| 1090 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1091 | #ifdef ARC_ANNOTATIONS |
| 1092 | /// The Metadata Kind for llvm.arc.annotation.bottomup metadata. |
| 1093 | unsigned ARCAnnotationBottomUpMDKind; |
| 1094 | /// The Metadata Kind for llvm.arc.annotation.topdown metadata. |
| 1095 | unsigned ARCAnnotationTopDownMDKind; |
| 1096 | /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata. |
| 1097 | unsigned ARCAnnotationProvenanceSourceMDKind; |
| 1098 | #endif // ARC_ANNOATIONS |
| 1099 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1100 | Constant *getAutoreleaseRVCallee(Module *M); |
| 1101 | Constant *getReleaseCallee(Module *M); |
| 1102 | Constant *getRetainCallee(Module *M); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1103 | Constant *getRetainBlockCallee(Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1104 | Constant *getAutoreleaseCallee(Module *M); |
| 1105 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1106 | bool IsRetainBlockOptimizable(const Instruction *Inst); |
| 1107 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1108 | bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1109 | void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1110 | InstructionClass &Class); |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1111 | bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock, |
| 1112 | InstructionClass &Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1113 | void OptimizeIndividualCalls(Function &F); |
| 1114 | |
| 1115 | void CheckForCFGHazards(const BasicBlock *BB, |
| 1116 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1117 | BBState &MyStates) const; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1118 | bool VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1119 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1120 | MapVector<Value *, RRInfo> &Retains, |
| 1121 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1122 | bool VisitBottomUp(BasicBlock *BB, |
| 1123 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1124 | MapVector<Value *, RRInfo> &Retains); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1125 | bool VisitInstructionTopDown(Instruction *Inst, |
| 1126 | DenseMap<Value *, RRInfo> &Releases, |
| 1127 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1128 | bool VisitTopDown(BasicBlock *BB, |
| 1129 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1130 | DenseMap<Value *, RRInfo> &Releases); |
| 1131 | bool Visit(Function &F, |
| 1132 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1133 | MapVector<Value *, RRInfo> &Retains, |
| 1134 | DenseMap<Value *, RRInfo> &Releases); |
| 1135 | |
| 1136 | void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, |
| 1137 | MapVector<Value *, RRInfo> &Retains, |
| 1138 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1139 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 1140 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1141 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 1142 | bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1143 | MapVector<Value *, RRInfo> &Retains, |
| 1144 | DenseMap<Value *, RRInfo> &Releases, |
| 1145 | Module *M, |
| 1146 | SmallVector<Instruction *, 4> &NewRetains, |
| 1147 | SmallVector<Instruction *, 4> &NewReleases, |
| 1148 | SmallVector<Instruction *, 8> &DeadInsts, |
| 1149 | RRInfo &RetainsToMove, |
| 1150 | RRInfo &ReleasesToMove, |
| 1151 | Value *Arg, |
| 1152 | bool KnownSafe, |
| 1153 | bool &AnyPairsCompletelyEliminated); |
| 1154 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1155 | bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1156 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1157 | DenseMap<Value *, RRInfo> &Releases, |
| 1158 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1159 | |
| 1160 | void OptimizeWeakCalls(Function &F); |
| 1161 | |
| 1162 | bool OptimizeSequences(Function &F); |
| 1163 | |
| 1164 | void OptimizeReturns(Function &F); |
| 1165 | |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 1166 | #ifndef NDEBUG |
| 1167 | void GatherStatistics(Function &F, bool AfterOptimization = false); |
| 1168 | #endif |
| 1169 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1170 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1171 | virtual bool doInitialization(Module &M); |
| 1172 | virtual bool runOnFunction(Function &F); |
| 1173 | virtual void releaseMemory(); |
| 1174 | |
| 1175 | public: |
| 1176 | static char ID; |
| 1177 | ObjCARCOpt() : FunctionPass(ID) { |
| 1178 | initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); |
| 1179 | } |
| 1180 | }; |
| 1181 | } |
| 1182 | |
| 1183 | char ObjCARCOpt::ID = 0; |
| 1184 | INITIALIZE_PASS_BEGIN(ObjCARCOpt, |
| 1185 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1186 | INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis) |
| 1187 | INITIALIZE_PASS_END(ObjCARCOpt, |
| 1188 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1189 | |
| 1190 | Pass *llvm::createObjCARCOptPass() { |
| 1191 | return new ObjCARCOpt(); |
| 1192 | } |
| 1193 | |
| 1194 | void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1195 | AU.addRequired<ObjCARCAliasAnalysis>(); |
| 1196 | AU.addRequired<AliasAnalysis>(); |
| 1197 | // ARC optimization doesn't currently split critical edges. |
| 1198 | AU.setPreservesCFG(); |
| 1199 | } |
| 1200 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1201 | bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) { |
| 1202 | // Without the magic metadata tag, we have to assume this might be an |
| 1203 | // objc_retainBlock call inserted to convert a block pointer to an id, |
| 1204 | // in which case it really is needed. |
| 1205 | if (!Inst->getMetadata(CopyOnEscapeMDKind)) |
| 1206 | return false; |
| 1207 | |
| 1208 | // If the pointer "escapes" (not including being used in a call), |
| 1209 | // the copy may be needed. |
Michael Gottesman | 774d2c0 | 2013-01-29 21:00:52 +0000 | [diff] [blame] | 1210 | if (DoesRetainableObjPtrEscape(Inst)) |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1211 | return false; |
| 1212 | |
| 1213 | // Otherwise, it's not needed. |
| 1214 | return true; |
| 1215 | } |
| 1216 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1217 | Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) { |
| 1218 | if (!AutoreleaseRVCallee) { |
| 1219 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1220 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1221 | Type *Params[] = { I8X }; |
| 1222 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1223 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1224 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1225 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1226 | AutoreleaseRVCallee = |
| 1227 | M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1228 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1229 | } |
| 1230 | return AutoreleaseRVCallee; |
| 1231 | } |
| 1232 | |
| 1233 | Constant *ObjCARCOpt::getReleaseCallee(Module *M) { |
| 1234 | if (!ReleaseCallee) { |
| 1235 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1236 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1237 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1238 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1239 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1240 | ReleaseCallee = |
| 1241 | M->getOrInsertFunction( |
| 1242 | "objc_release", |
| 1243 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1244 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1245 | } |
| 1246 | return ReleaseCallee; |
| 1247 | } |
| 1248 | |
| 1249 | Constant *ObjCARCOpt::getRetainCallee(Module *M) { |
| 1250 | if (!RetainCallee) { |
| 1251 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1252 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1253 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1254 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1255 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1256 | RetainCallee = |
| 1257 | M->getOrInsertFunction( |
| 1258 | "objc_retain", |
| 1259 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1260 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1261 | } |
| 1262 | return RetainCallee; |
| 1263 | } |
| 1264 | |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1265 | Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) { |
| 1266 | if (!RetainBlockCallee) { |
| 1267 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1268 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Dan Gohman | fca43c2 | 2011-09-14 18:33:34 +0000 | [diff] [blame] | 1269 | // objc_retainBlock is not nounwind because it calls user copy constructors |
| 1270 | // which could theoretically throw. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1271 | RetainBlockCallee = |
| 1272 | M->getOrInsertFunction( |
| 1273 | "objc_retainBlock", |
| 1274 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1275 | AttributeSet()); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1276 | } |
| 1277 | return RetainBlockCallee; |
| 1278 | } |
| 1279 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1280 | Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) { |
| 1281 | if (!AutoreleaseCallee) { |
| 1282 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1283 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1284 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1285 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1286 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1287 | AutoreleaseCallee = |
| 1288 | M->getOrInsertFunction( |
| 1289 | "objc_autorelease", |
| 1290 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1291 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1292 | } |
| 1293 | return AutoreleaseCallee; |
| 1294 | } |
| 1295 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1296 | /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is |
| 1297 | /// not a return value. Or, if it can be paired with an |
| 1298 | /// objc_autoreleaseReturnValue, delete the pair and return true. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1299 | bool |
| 1300 | ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1301 | // Check for the argument being from an immediately preceding call or invoke. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1302 | const Value *Arg = GetObjCArg(RetainRV); |
| 1303 | ImmutableCallSite CS(Arg); |
| 1304 | if (const Instruction *Call = CS.getInstruction()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1305 | if (Call->getParent() == RetainRV->getParent()) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1306 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1307 | ++I; |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1308 | while (IsNoopInstruction(I)) ++I; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1309 | if (&*I == RetainRV) |
| 1310 | return false; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1311 | } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1312 | BasicBlock *RetainRVParent = RetainRV->getParent(); |
| 1313 | if (II->getNormalDest() == RetainRVParent) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1314 | BasicBlock::const_iterator I = RetainRVParent->begin(); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1315 | while (IsNoopInstruction(I)) ++I; |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1316 | if (&*I == RetainRV) |
| 1317 | return false; |
| 1318 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1319 | } |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 1320 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1321 | |
| 1322 | // Check for being preceded by an objc_autoreleaseReturnValue on the same |
| 1323 | // pointer. In this case, we can delete the pair. |
| 1324 | BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin(); |
| 1325 | if (I != Begin) { |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1326 | do --I; while (I != Begin && IsNoopInstruction(I)); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1327 | if (GetBasicInstructionClass(I) == IC_AutoreleaseRV && |
| 1328 | GetObjCArg(I) == Arg) { |
| 1329 | Changed = true; |
| 1330 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1331 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1332 | DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n" |
| 1333 | << "Erasing " << *RetainRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1334 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1335 | EraseInstruction(I); |
| 1336 | EraseInstruction(RetainRV); |
| 1337 | return true; |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | // Turn it to a plain objc_retain. |
| 1342 | Changed = true; |
| 1343 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1344 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1345 | DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => " |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1346 | "objc_retain since the operand is not a return value.\n" |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1347 | "Old = " << *RetainRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1348 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1349 | cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent())); |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1350 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1351 | DEBUG(dbgs() << "New = " << *RetainRV << "\n"); |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 1352 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1353 | return false; |
| 1354 | } |
| 1355 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1356 | /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not |
| 1357 | /// used as a return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1358 | void |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1359 | ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1360 | InstructionClass &Class) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1361 | // Check for a return of the pointer value. |
| 1362 | const Value *Ptr = GetObjCArg(AutoreleaseRV); |
Dan Gohman | 10a18d5 | 2011-08-12 00:36:31 +0000 | [diff] [blame] | 1363 | SmallVector<const Value *, 2> Users; |
| 1364 | Users.push_back(Ptr); |
| 1365 | do { |
| 1366 | Ptr = Users.pop_back_val(); |
| 1367 | for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); |
| 1368 | UI != UE; ++UI) { |
| 1369 | const User *I = *UI; |
| 1370 | if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV) |
| 1371 | return; |
| 1372 | if (isa<BitCastInst>(I)) |
| 1373 | Users.push_back(I); |
| 1374 | } |
| 1375 | } while (!Users.empty()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1376 | |
| 1377 | Changed = true; |
| 1378 | ++NumPeeps; |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1379 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1380 | DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => " |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1381 | "objc_autorelease since its operand is not used as a return " |
| 1382 | "value.\n" |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1383 | "Old = " << *AutoreleaseRV << "\n"); |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 1384 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1385 | CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); |
| 1386 | AutoreleaseRVCI-> |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1387 | setCalledFunction(getAutoreleaseCallee(F.getParent())); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1388 | AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1389 | Class = IC_Autorelease; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1390 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1391 | DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1392 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1393 | } |
| 1394 | |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1395 | // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain |
| 1396 | // calls. |
| 1397 | // |
| 1398 | // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and |
| 1399 | // does not escape (following the rules of block escaping), strength reduce the |
| 1400 | // objc_retainBlock to an objc_retain. |
| 1401 | // |
| 1402 | // TODO: If an objc_retainBlock call is dominated period by a previous |
| 1403 | // objc_retainBlock call, strength reduce the objc_retainBlock to an |
| 1404 | // objc_retain. |
| 1405 | bool |
| 1406 | ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst, |
| 1407 | InstructionClass &Class) { |
| 1408 | assert(GetBasicInstructionClass(Inst) == Class); |
| 1409 | assert(IC_RetainBlock == Class); |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 1410 | |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1411 | // If we can not optimize Inst, return false. |
| 1412 | if (!IsRetainBlockOptimizable(Inst)) |
| 1413 | return false; |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 1414 | |
Michael Gottesman | 3eab2e4 | 2013-04-21 00:50:27 +0000 | [diff] [blame] | 1415 | Changed = true; |
| 1416 | ++NumPeeps; |
| 1417 | |
| 1418 | DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n"); |
| 1419 | DEBUG(dbgs() << "Old: " << *Inst << "\n"); |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1420 | CallInst *RetainBlock = cast<CallInst>(Inst); |
| 1421 | RetainBlock->setCalledFunction(getRetainCallee(F.getParent())); |
| 1422 | // Remove copy_on_escape metadata. |
| 1423 | RetainBlock->setMetadata(CopyOnEscapeMDKind, 0); |
| 1424 | Class = IC_Retain; |
Michael Gottesman | 3eab2e4 | 2013-04-21 00:50:27 +0000 | [diff] [blame] | 1425 | DEBUG(dbgs() << "New: " << *Inst << "\n"); |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1426 | return true; |
| 1427 | } |
| 1428 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1429 | /// Visit each call, one at a time, and make simplifications without doing any |
| 1430 | /// additional analysis. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1431 | void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1432 | DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1433 | // Reset all the flags in preparation for recomputing them. |
| 1434 | UsedInThisFunction = 0; |
| 1435 | |
| 1436 | // Visit all objc_* calls in F. |
| 1437 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 1438 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 1439 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1440 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 1441 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1442 | DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n"); |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 1443 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1444 | switch (Class) { |
| 1445 | default: break; |
| 1446 | |
| 1447 | // Delete no-op casts. These function calls have special semantics, but |
| 1448 | // the semantics are entirely implemented via lowering in the front-end, |
| 1449 | // so by the time they reach the optimizer, they are just no-op calls |
| 1450 | // which return their argument. |
| 1451 | // |
| 1452 | // There are gray areas here, as the ability to cast reference-counted |
| 1453 | // pointers to raw void* and back allows code to break ARC assumptions, |
| 1454 | // however these are currently considered to be unimportant. |
| 1455 | case IC_NoopCast: |
| 1456 | Changed = true; |
| 1457 | ++NumNoops; |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1458 | DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1459 | EraseInstruction(Inst); |
| 1460 | continue; |
| 1461 | |
| 1462 | // If the pointer-to-weak-pointer is null, it's undefined behavior. |
| 1463 | case IC_StoreWeak: |
| 1464 | case IC_LoadWeak: |
| 1465 | case IC_LoadWeakRetained: |
| 1466 | case IC_InitWeak: |
| 1467 | case IC_DestroyWeak: { |
| 1468 | CallInst *CI = cast<CallInst>(Inst); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1469 | if (IsNullOrUndef(CI->getArgOperand(0))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1470 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1471 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1472 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1473 | Constant::getNullValue(Ty), |
| 1474 | CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1475 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1476 | DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior." |
| 1477 | "\nOld = " << *CI << "\nNew = " << *NewValue << "\n"); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1478 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1479 | CI->eraseFromParent(); |
| 1480 | continue; |
| 1481 | } |
| 1482 | break; |
| 1483 | } |
| 1484 | case IC_CopyWeak: |
| 1485 | case IC_MoveWeak: { |
| 1486 | CallInst *CI = cast<CallInst>(Inst); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1487 | if (IsNullOrUndef(CI->getArgOperand(0)) || |
| 1488 | IsNullOrUndef(CI->getArgOperand(1))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1489 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1490 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1491 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 1492 | Constant::getNullValue(Ty), |
| 1493 | CI); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1494 | |
| 1495 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1496 | DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior." |
| 1497 | "\nOld = " << *CI << "\nNew = " << *NewValue << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1498 | |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 1499 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1500 | CI->eraseFromParent(); |
| 1501 | continue; |
| 1502 | } |
| 1503 | break; |
| 1504 | } |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1505 | case IC_RetainBlock: |
Michael Gottesman | 1e43004 | 2013-04-21 00:44:46 +0000 | [diff] [blame] | 1506 | // If we strength reduce an objc_retainBlock to an objc_retain, continue |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1507 | // onto the objc_retain peephole optimizations. Otherwise break. |
Michael Gottesman | 9fc50b8 | 2013-05-13 18:29:07 +0000 | [diff] [blame] | 1508 | OptimizeRetainBlockCall(F, Inst, Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1509 | break; |
| 1510 | case IC_RetainRV: |
| 1511 | if (OptimizeRetainRVCall(F, Inst)) |
| 1512 | continue; |
| 1513 | break; |
| 1514 | case IC_AutoreleaseRV: |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1515 | OptimizeAutoreleaseRVCall(F, Inst, Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1516 | break; |
| 1517 | } |
| 1518 | |
Michael Gottesman | b8c8836 | 2013-04-03 02:57:24 +0000 | [diff] [blame] | 1519 | // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1520 | if (IsAutorelease(Class) && Inst->use_empty()) { |
| 1521 | CallInst *Call = cast<CallInst>(Inst); |
| 1522 | const Value *Arg = Call->getArgOperand(0); |
| 1523 | Arg = FindSingleUseIdentifiedObject(Arg); |
| 1524 | if (Arg) { |
| 1525 | Changed = true; |
| 1526 | ++NumAutoreleases; |
| 1527 | |
| 1528 | // Create the declaration lazily. |
| 1529 | LLVMContext &C = Inst->getContext(); |
| 1530 | CallInst *NewCall = |
| 1531 | CallInst::Create(getReleaseCallee(F.getParent()), |
| 1532 | Call->getArgOperand(0), "", Call); |
Dmitri Gribenko | 3238fb7 | 2013-05-05 00:40:33 +0000 | [diff] [blame] | 1533 | NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None)); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1534 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1535 | DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) " |
| 1536 | "since x is otherwise unused.\nOld: " << *Call << "\nNew: " |
| 1537 | << *NewCall << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1538 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1539 | EraseInstruction(Call); |
| 1540 | Inst = NewCall; |
| 1541 | Class = IC_Release; |
| 1542 | } |
| 1543 | } |
| 1544 | |
| 1545 | // For functions which can never be passed stack arguments, add |
| 1546 | // a tail keyword. |
| 1547 | if (IsAlwaysTail(Class)) { |
| 1548 | Changed = true; |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1549 | DEBUG(dbgs() << "Adding tail keyword to function since it can never be " |
| 1550 | "passed stack args: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1551 | cast<CallInst>(Inst)->setTailCall(); |
| 1552 | } |
| 1553 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1554 | // Ensure that functions that can never have a "tail" keyword due to the |
| 1555 | // semantics of ARC truly do not do so. |
| 1556 | if (IsNeverTail(Class)) { |
| 1557 | Changed = true; |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1558 | DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst << |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 1559 | "\n"); |
| 1560 | cast<CallInst>(Inst)->setTailCall(false); |
| 1561 | } |
| 1562 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1563 | // Set nounwind as needed. |
| 1564 | if (IsNoThrow(Class)) { |
| 1565 | Changed = true; |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1566 | DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst |
| 1567 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1568 | cast<CallInst>(Inst)->setDoesNotThrow(); |
| 1569 | } |
| 1570 | |
| 1571 | if (!IsNoopOnNull(Class)) { |
| 1572 | UsedInThisFunction |= 1 << Class; |
| 1573 | continue; |
| 1574 | } |
| 1575 | |
| 1576 | const Value *Arg = GetObjCArg(Inst); |
| 1577 | |
| 1578 | // ARC calls with null are no-ops. Delete them. |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1579 | if (IsNullOrUndef(Arg)) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1580 | Changed = true; |
| 1581 | ++NumNoops; |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1582 | DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst |
| 1583 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1584 | EraseInstruction(Inst); |
| 1585 | continue; |
| 1586 | } |
| 1587 | |
| 1588 | // Keep track of which of retain, release, autorelease, and retain_block |
| 1589 | // are actually present in this function. |
| 1590 | UsedInThisFunction |= 1 << Class; |
| 1591 | |
| 1592 | // If Arg is a PHI, and one or more incoming values to the |
| 1593 | // PHI are null, and the call is control-equivalent to the PHI, and there |
| 1594 | // are no relevant side effects between the PHI and the call, the call |
| 1595 | // could be pushed up to just those paths with non-null incoming values. |
| 1596 | // For now, don't bother splitting critical edges for this. |
| 1597 | SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; |
| 1598 | Worklist.push_back(std::make_pair(Inst, Arg)); |
| 1599 | do { |
| 1600 | std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); |
| 1601 | Inst = Pair.first; |
| 1602 | Arg = Pair.second; |
| 1603 | |
| 1604 | const PHINode *PN = dyn_cast<PHINode>(Arg); |
| 1605 | if (!PN) continue; |
| 1606 | |
| 1607 | // Determine if the PHI has any null operands, or any incoming |
| 1608 | // critical edges. |
| 1609 | bool HasNull = false; |
| 1610 | bool HasCriticalEdges = false; |
| 1611 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1612 | Value *Incoming = |
| 1613 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1614 | if (IsNullOrUndef(Incoming)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1615 | HasNull = true; |
| 1616 | else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back()) |
| 1617 | .getNumSuccessors() != 1) { |
| 1618 | HasCriticalEdges = true; |
| 1619 | break; |
| 1620 | } |
| 1621 | } |
| 1622 | // If we have null operands and no critical edges, optimize. |
| 1623 | if (!HasCriticalEdges && HasNull) { |
| 1624 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 1625 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 1626 | |
| 1627 | // Check that there is nothing that cares about the reference |
| 1628 | // count between the call and the phi. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1629 | switch (Class) { |
| 1630 | case IC_Retain: |
| 1631 | case IC_RetainBlock: |
| 1632 | // These can always be moved up. |
| 1633 | break; |
| 1634 | case IC_Release: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1635 | // These can't be moved across things that care about the retain |
| 1636 | // count. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 1637 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 1638 | Inst->getParent(), Inst, |
| 1639 | DependingInstructions, Visited, PA); |
| 1640 | break; |
| 1641 | case IC_Autorelease: |
| 1642 | // These can't be moved across autorelease pool scope boundaries. |
| 1643 | FindDependencies(AutoreleasePoolBoundary, Arg, |
| 1644 | Inst->getParent(), Inst, |
| 1645 | DependingInstructions, Visited, PA); |
| 1646 | break; |
| 1647 | case IC_RetainRV: |
| 1648 | case IC_AutoreleaseRV: |
| 1649 | // Don't move these; the RV optimization depends on the autoreleaseRV |
| 1650 | // being tail called, and the retainRV being immediately after a call |
| 1651 | // (which might still happen if we get lucky with codegen layout, but |
| 1652 | // it's not worth taking the chance). |
| 1653 | continue; |
| 1654 | default: |
| 1655 | llvm_unreachable("Invalid dependence flavor"); |
| 1656 | } |
| 1657 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1658 | if (DependingInstructions.size() == 1 && |
| 1659 | *DependingInstructions.begin() == PN) { |
| 1660 | Changed = true; |
| 1661 | ++NumPartialNoops; |
| 1662 | // Clone the call into each predecessor that has a non-null value. |
| 1663 | CallInst *CInst = cast<CallInst>(Inst); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1664 | Type *ParamTy = CInst->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1665 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1666 | Value *Incoming = |
| 1667 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
Michael Gottesman | 65c2481 | 2013-03-25 09:27:43 +0000 | [diff] [blame] | 1668 | if (!IsNullOrUndef(Incoming)) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1669 | CallInst *Clone = cast<CallInst>(CInst->clone()); |
| 1670 | Value *Op = PN->getIncomingValue(i); |
| 1671 | Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); |
| 1672 | if (Op->getType() != ParamTy) |
| 1673 | Op = new BitCastInst(Op, ParamTy, "", InsertPos); |
| 1674 | Clone->setArgOperand(0, Op); |
| 1675 | Clone->insertBefore(InsertPos); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1676 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1677 | DEBUG(dbgs() << "Cloning " |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1678 | << *CInst << "\n" |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1679 | "And inserting clone at " << *InsertPos << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1680 | Worklist.push_back(std::make_pair(Clone, Incoming)); |
| 1681 | } |
| 1682 | } |
| 1683 | // Erase the original call. |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 1684 | DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1685 | EraseInstruction(CInst); |
| 1686 | continue; |
| 1687 | } |
| 1688 | } |
| 1689 | } while (!Worklist.empty()); |
| 1690 | } |
| 1691 | } |
| 1692 | |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1693 | /// If we have a top down pointer in the S_Use state, make sure that there are |
| 1694 | /// no CFG hazards by checking the states of various bottom up pointers. |
| 1695 | static void CheckForUseCFGHazard(const Sequence SuccSSeq, |
| 1696 | const bool SuccSRRIKnownSafe, |
| 1697 | PtrState &S, |
| 1698 | bool &SomeSuccHasSame, |
| 1699 | bool &AllSuccsHaveSame, |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1700 | bool &NotAllSeqEqualButKnownSafe, |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1701 | bool &ShouldContinue) { |
| 1702 | switch (SuccSSeq) { |
| 1703 | case S_CanRelease: { |
| 1704 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
| 1705 | S.ClearSequenceProgress(); |
| 1706 | break; |
| 1707 | } |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1708 | S.RRI.CFGHazardAfflicted = true; |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1709 | ShouldContinue = true; |
| 1710 | break; |
| 1711 | } |
| 1712 | case S_Use: |
| 1713 | SomeSuccHasSame = true; |
| 1714 | break; |
| 1715 | case S_Stop: |
| 1716 | case S_Release: |
| 1717 | case S_MovableRelease: |
| 1718 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
| 1719 | AllSuccsHaveSame = false; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1720 | else |
| 1721 | NotAllSeqEqualButKnownSafe = true; |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1722 | break; |
| 1723 | case S_Retain: |
| 1724 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1725 | case S_None: |
| 1726 | llvm_unreachable("This should have been handled earlier."); |
| 1727 | } |
| 1728 | } |
| 1729 | |
| 1730 | /// If we have a Top Down pointer in the S_CanRelease state, make sure that |
| 1731 | /// there are no CFG hazards by checking the states of various bottom up |
| 1732 | /// pointers. |
| 1733 | static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq, |
| 1734 | const bool SuccSRRIKnownSafe, |
| 1735 | PtrState &S, |
| 1736 | bool &SomeSuccHasSame, |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1737 | bool &AllSuccsHaveSame, |
| 1738 | bool &NotAllSeqEqualButKnownSafe) { |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1739 | switch (SuccSSeq) { |
| 1740 | case S_CanRelease: |
| 1741 | SomeSuccHasSame = true; |
| 1742 | break; |
| 1743 | case S_Stop: |
| 1744 | case S_Release: |
| 1745 | case S_MovableRelease: |
| 1746 | case S_Use: |
| 1747 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
| 1748 | AllSuccsHaveSame = false; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1749 | else |
| 1750 | NotAllSeqEqualButKnownSafe = true; |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1751 | break; |
| 1752 | case S_Retain: |
| 1753 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1754 | case S_None: |
| 1755 | llvm_unreachable("This should have been handled earlier."); |
| 1756 | } |
| 1757 | } |
| 1758 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1759 | /// Check for critical edges, loop boundaries, irreducible control flow, or |
| 1760 | /// other CFG structures where moving code across the edge would result in it |
| 1761 | /// being executed more. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1762 | void |
| 1763 | ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, |
| 1764 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1765 | BBState &MyStates) const { |
| 1766 | // If any top-down local-use or possible-dec has a succ which is earlier in |
| 1767 | // the sequence, forget it. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 1768 | for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(), |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1769 | E = MyStates.top_down_ptr_end(); I != E; ++I) { |
| 1770 | PtrState &S = I->second; |
| 1771 | const Sequence Seq = I->second.GetSeq(); |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1772 | |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1773 | // We only care about S_Retain, S_CanRelease, and S_Use. |
| 1774 | if (Seq == S_None) |
| 1775 | continue; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1776 | |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1777 | // Make sure that if extra top down states are added in the future that this |
| 1778 | // code is updated to handle it. |
| 1779 | assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) && |
| 1780 | "Unknown top down sequence state."); |
| 1781 | |
| 1782 | const Value *Arg = I->first; |
| 1783 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 1784 | bool SomeSuccHasSame = false; |
| 1785 | bool AllSuccsHaveSame = true; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1786 | bool NotAllSeqEqualButKnownSafe = false; |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1787 | |
| 1788 | succ_const_iterator SI(TI), SE(TI, false); |
| 1789 | |
| 1790 | for (; SI != SE; ++SI) { |
| 1791 | // If VisitBottomUp has pointer information for this successor, take |
| 1792 | // what we know about it. |
| 1793 | const DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 1794 | BBStates.find(*SI); |
| 1795 | assert(BBI != BBStates.end()); |
| 1796 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 1797 | const Sequence SuccSSeq = SuccS.GetSeq(); |
| 1798 | |
| 1799 | // If bottom up, the pointer is in an S_None state, clear the sequence |
| 1800 | // progress since the sequence in the bottom up state finished |
| 1801 | // suggesting a mismatch in between retains/releases. This is true for |
| 1802 | // all three cases that we are handling here: S_Retain, S_Use, and |
| 1803 | // S_CanRelease. |
| 1804 | if (SuccSSeq == S_None) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1805 | S.ClearSequenceProgress(); |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1806 | continue; |
| 1807 | } |
| 1808 | |
| 1809 | // If we have S_Use or S_CanRelease, perform our check for cfg hazard |
| 1810 | // checks. |
| 1811 | const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
| 1812 | |
| 1813 | // *NOTE* We do not use Seq from above here since we are allowing for |
| 1814 | // S.GetSeq() to change while we are visiting basic blocks. |
| 1815 | switch(S.GetSeq()) { |
| 1816 | case S_Use: { |
| 1817 | bool ShouldContinue = false; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1818 | CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame, |
| 1819 | AllSuccsHaveSame, NotAllSeqEqualButKnownSafe, |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1820 | ShouldContinue); |
| 1821 | if (ShouldContinue) |
| 1822 | continue; |
| 1823 | break; |
| 1824 | } |
| 1825 | case S_CanRelease: { |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1826 | CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, |
| 1827 | SomeSuccHasSame, AllSuccsHaveSame, |
| 1828 | NotAllSeqEqualButKnownSafe); |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1829 | break; |
| 1830 | } |
| 1831 | case S_Retain: |
| 1832 | case S_None: |
| 1833 | case S_Stop: |
| 1834 | case S_Release: |
| 1835 | case S_MovableRelease: |
| 1836 | break; |
| 1837 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1838 | } |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1839 | |
| 1840 | // If the state at the other end of any of the successor edges |
| 1841 | // matches the current state, require all edges to match. This |
| 1842 | // guards against loops in the middle of a sequence. |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1843 | if (SomeSuccHasSame && !AllSuccsHaveSame) { |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1844 | S.ClearSequenceProgress(); |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 1845 | } else if (NotAllSeqEqualButKnownSafe) { |
| 1846 | // If we would have cleared the state foregoing the fact that we are known |
| 1847 | // safe, stop code motion. This is because whether or not it is safe to |
| 1848 | // remove RR pairs via KnownSafe is an orthogonal concept to whether we |
| 1849 | // are allowed to perform code motion. |
| 1850 | S.RRI.CFGHazardAfflicted = true; |
| 1851 | } |
Michael Gottesman | 323964c | 2013-04-18 05:39:45 +0000 | [diff] [blame] | 1852 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1853 | } |
| 1854 | |
| 1855 | bool |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1856 | ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1857 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1858 | MapVector<Value *, RRInfo> &Retains, |
| 1859 | BBState &MyStates) { |
| 1860 | bool NestingDetected = false; |
| 1861 | InstructionClass Class = GetInstructionClass(Inst); |
| 1862 | const Value *Arg = 0; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 1863 | |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 1864 | DEBUG(dbgs() << "Class: " << Class << "\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 1865 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1866 | switch (Class) { |
| 1867 | case IC_Release: { |
| 1868 | Arg = GetObjCArg(Inst); |
| 1869 | |
| 1870 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
| 1871 | |
| 1872 | // If we see two releases in a row on the same pointer. If so, make |
| 1873 | // a note, and we'll cicle back to revisit it after we've |
| 1874 | // hopefully eliminated the second release, which may allow us to |
| 1875 | // eliminate the first release too. |
| 1876 | // Theoretically we could implement removal of nested retain+release |
| 1877 | // pairs by making PtrState hold a stack of states, but this is |
| 1878 | // simple and avoids adding overhead for the non-nested case. |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 1879 | if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1880 | DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1881 | NestingDetected = true; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 1882 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1883 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1884 | MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1885 | Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release; |
| 1886 | ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq); |
| 1887 | S.ResetSequenceProgress(NewSeq); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1888 | S.RRI.ReleaseMetadata = ReleaseMetadata; |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 1889 | S.RRI.KnownSafe = S.HasKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1890 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 1891 | S.RRI.Calls.insert(Inst); |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1892 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1893 | break; |
| 1894 | } |
| 1895 | case IC_RetainBlock: |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 1896 | // In OptimizeIndividualCalls, we have strength reduced all optimizable |
| 1897 | // objc_retainBlocks to objc_retains. Thus at this point any |
| 1898 | // objc_retainBlocks that we see are not optimizable. |
| 1899 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1900 | case IC_Retain: |
| 1901 | case IC_RetainRV: { |
| 1902 | Arg = GetObjCArg(Inst); |
| 1903 | |
| 1904 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1905 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1906 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1907 | Sequence OldSeq = S.GetSeq(); |
| 1908 | switch (OldSeq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1909 | case S_Stop: |
| 1910 | case S_Release: |
| 1911 | case S_MovableRelease: |
| 1912 | case S_Use: |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 1913 | // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an |
| 1914 | // imprecise release, clear our reverse insertion points. |
| 1915 | if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases()) |
| 1916 | S.RRI.ReverseInsertPts.clear(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1917 | // FALL THROUGH |
| 1918 | case S_CanRelease: |
| 1919 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 1920 | // better to let it remain as the first instruction after a call. |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame] | 1921 | if (Class != IC_RetainRV) |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1922 | Retains[Inst] = S.RRI; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1923 | S.ClearSequenceProgress(); |
| 1924 | break; |
| 1925 | case S_None: |
| 1926 | break; |
| 1927 | case S_Retain: |
| 1928 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1929 | } |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 1930 | ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq()); |
Michael Gottesman | 31ba23a | 2013-04-05 22:54:32 +0000 | [diff] [blame] | 1931 | // A retain moving bottom up can be a use. |
| 1932 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1933 | } |
| 1934 | case IC_AutoreleasepoolPop: |
| 1935 | // Conservatively, clear MyStates for all known pointers. |
| 1936 | MyStates.clearBottomUpPointers(); |
| 1937 | return NestingDetected; |
| 1938 | case IC_AutoreleasepoolPush: |
| 1939 | case IC_None: |
| 1940 | // These are irrelevant. |
| 1941 | return NestingDetected; |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 1942 | case IC_User: |
| 1943 | // If we have a store into an alloca of a pointer we are tracking, the |
| 1944 | // pointer has multiple owners implying that we must be more conservative. |
| 1945 | // |
| 1946 | // This comes up in the context of a pointer being ``KnownSafe''. In the |
| 1947 | // presense of a block being initialized, the frontend will emit the |
| 1948 | // objc_retain on the original pointer and the release on the pointer loaded |
| 1949 | // from the alloca. The optimizer will through the provenance analysis |
| 1950 | // realize that the two are related, but since we only require KnownSafe in |
| 1951 | // one direction, will match the inner retain on the original pointer with |
| 1952 | // the guard release on the original pointer. This is fixed by ensuring that |
| 1953 | // in the presense of allocas we only unconditionally remove pointers if |
| 1954 | // both our retain and our release are KnownSafe. |
| 1955 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
| 1956 | if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) { |
| 1957 | BBState::ptr_iterator I = MyStates.findPtrBottomUpState( |
| 1958 | StripPointerCastsAndObjCCalls(SI->getValueOperand())); |
| 1959 | if (I != MyStates.bottom_up_ptr_end()) |
Michael Gottesman | 5a91bbf | 2013-05-24 20:44:02 +0000 | [diff] [blame] | 1960 | MultiOwnersSet.insert(I->first); |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 1961 | } |
| 1962 | } |
| 1963 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1964 | default: |
| 1965 | break; |
| 1966 | } |
| 1967 | |
| 1968 | // Consider any other possible effects of this instruction on each |
| 1969 | // pointer being tracked. |
| 1970 | for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(), |
| 1971 | ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 1972 | const Value *Ptr = MI->first; |
| 1973 | if (Ptr == Arg) |
| 1974 | continue; // Handled above. |
| 1975 | PtrState &S = MI->second; |
| 1976 | Sequence Seq = S.GetSeq(); |
| 1977 | |
| 1978 | // Check for possible releases. |
| 1979 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 1980 | DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr |
| 1981 | << "\n"); |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 1982 | S.ClearKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1983 | switch (Seq) { |
| 1984 | case S_Use: |
| 1985 | S.SetSeq(S_CanRelease); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 1986 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq()); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1987 | continue; |
| 1988 | case S_CanRelease: |
| 1989 | case S_Release: |
| 1990 | case S_MovableRelease: |
| 1991 | case S_Stop: |
| 1992 | case S_None: |
| 1993 | break; |
| 1994 | case S_Retain: |
| 1995 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 1996 | } |
| 1997 | } |
| 1998 | |
| 1999 | // Check for possible direct uses. |
| 2000 | switch (Seq) { |
| 2001 | case S_Release: |
| 2002 | case S_MovableRelease: |
| 2003 | if (CanUse(Inst, Ptr, PA, Class)) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2004 | DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr |
| 2005 | << "\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2006 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2007 | // If this is an invoke instruction, we're scanning it as part of |
| 2008 | // one of its successor blocks, since we can't insert code after it |
| 2009 | // in its own block, and we don't want to split critical edges. |
| 2010 | if (isa<InvokeInst>(Inst)) |
| 2011 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2012 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2013 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2014 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2015 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use); |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 2016 | } else if (Seq == S_Release && IsUser(Class)) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2017 | DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr |
| 2018 | << "\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2019 | // Non-movable releases depend on any possible objc pointer use. |
| 2020 | S.SetSeq(S_Stop); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2021 | ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2022 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2023 | // As above; handle invoke specially. |
| 2024 | if (isa<InvokeInst>(Inst)) |
| 2025 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2026 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2027 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2028 | } |
| 2029 | break; |
| 2030 | case S_Stop: |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2031 | if (CanUse(Inst, Ptr, PA, Class)) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2032 | DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr |
| 2033 | << "\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2034 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2035 | ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use); |
| 2036 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2037 | break; |
| 2038 | case S_CanRelease: |
| 2039 | case S_Use: |
| 2040 | case S_None: |
| 2041 | break; |
| 2042 | case S_Retain: |
| 2043 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2044 | } |
| 2045 | } |
| 2046 | |
| 2047 | return NestingDetected; |
| 2048 | } |
| 2049 | |
| 2050 | bool |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2051 | ObjCARCOpt::VisitBottomUp(BasicBlock *BB, |
| 2052 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2053 | MapVector<Value *, RRInfo> &Retains) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2054 | |
| 2055 | DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2056 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2057 | bool NestingDetected = false; |
| 2058 | BBState &MyStates = BBStates[BB]; |
| 2059 | |
| 2060 | // Merge the states from each successor to compute the initial state |
| 2061 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 2062 | BBState::edge_iterator SI(MyStates.succ_begin()), |
| 2063 | SE(MyStates.succ_end()); |
| 2064 | if (SI != SE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2065 | const BasicBlock *Succ = *SI; |
| 2066 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); |
| 2067 | assert(I != BBStates.end()); |
| 2068 | MyStates.InitFromSucc(I->second); |
| 2069 | ++SI; |
| 2070 | for (; SI != SE; ++SI) { |
| 2071 | Succ = *SI; |
| 2072 | I = BBStates.find(Succ); |
| 2073 | assert(I != BBStates.end()); |
| 2074 | MyStates.MergeSucc(I->second); |
| 2075 | } |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 2076 | } |
Michael Gottesman | cd4de0f | 2013-03-26 00:42:09 +0000 | [diff] [blame] | 2077 | |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 2078 | // If ARC Annotations are enabled, output the current state of pointers at the |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2079 | // bottom of the basic block. |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 2080 | ANNOTATE_BOTTOMUP_BBEND(MyStates, BB); |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2081 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2082 | // Visit all the instructions, bottom-up. |
| 2083 | for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { |
| 2084 | Instruction *Inst = llvm::prior(I); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2085 | |
| 2086 | // Invoke instructions are visited as part of their successors (below). |
| 2087 | if (isa<InvokeInst>(Inst)) |
| 2088 | continue; |
| 2089 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2090 | DEBUG(dbgs() << "Visiting " << *Inst << "\n"); |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2091 | |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2092 | NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); |
| 2093 | } |
| 2094 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2095 | // If there's a predecessor with an invoke, visit the invoke as if it were |
| 2096 | // part of this block, since we can't insert code after an invoke in its own |
| 2097 | // block, and we don't want to split critical edges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2098 | for (BBState::edge_iterator PI(MyStates.pred_begin()), |
| 2099 | PE(MyStates.pred_end()); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2100 | BasicBlock *Pred = *PI; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2101 | if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) |
| 2102 | NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2103 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2104 | |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 2105 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 2106 | // top of the basic block. |
| 2107 | ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB); |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2108 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2109 | return NestingDetected; |
| 2110 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2111 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2112 | bool |
| 2113 | ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, |
| 2114 | DenseMap<Value *, RRInfo> &Releases, |
| 2115 | BBState &MyStates) { |
| 2116 | bool NestingDetected = false; |
| 2117 | InstructionClass Class = GetInstructionClass(Inst); |
| 2118 | const Value *Arg = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2119 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2120 | switch (Class) { |
| 2121 | case IC_RetainBlock: |
Michael Gottesman | 158fdf6 | 2013-03-28 20:11:19 +0000 | [diff] [blame] | 2122 | // In OptimizeIndividualCalls, we have strength reduced all optimizable |
| 2123 | // objc_retainBlocks to objc_retains. Thus at this point any |
| 2124 | // objc_retainBlocks that we see are not optimizable. |
| 2125 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2126 | case IC_Retain: |
| 2127 | case IC_RetainRV: { |
| 2128 | Arg = GetObjCArg(Inst); |
| 2129 | |
| 2130 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
| 2131 | |
| 2132 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 2133 | // better to let it remain as the first instruction after a call. |
| 2134 | if (Class != IC_RetainRV) { |
| 2135 | // If we see two retains in a row on the same pointer. If so, make |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2136 | // a note, and we'll cicle back to revisit it after we've |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2137 | // hopefully eliminated the second retain, which may allow us to |
| 2138 | // eliminate the first retain too. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2139 | // Theoretically we could implement removal of nested retain+release |
| 2140 | // pairs by making PtrState hold a stack of states, but this is |
| 2141 | // simple and avoids adding overhead for the non-nested case. |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2142 | if (S.GetSeq() == S_Retain) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2143 | NestingDetected = true; |
| 2144 | |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2145 | ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2146 | S.ResetSequenceProgress(S_Retain); |
Michael Gottesman | 07beea4 | 2013-03-23 05:31:01 +0000 | [diff] [blame] | 2147 | S.RRI.KnownSafe = S.HasKnownPositiveRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2148 | S.RRI.Calls.insert(Inst); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2149 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2150 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2151 | S.SetKnownPositiveRefCount(); |
Dan Gohman | f64ff8e | 2012-07-23 19:27:31 +0000 | [diff] [blame] | 2152 | |
| 2153 | // A retain can be a potential use; procede to the generic checking |
| 2154 | // code below. |
| 2155 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2156 | } |
| 2157 | case IC_Release: { |
| 2158 | Arg = GetObjCArg(Inst); |
| 2159 | |
| 2160 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 2161 | S.ClearKnownPositiveRefCount(); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2162 | |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 2163 | Sequence OldSeq = S.GetSeq(); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2164 | |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 2165 | MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2166 | |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 2167 | switch (OldSeq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2168 | case S_Retain: |
| 2169 | case S_CanRelease: |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 2170 | if (OldSeq == S_Retain || ReleaseMetadata != 0) |
| 2171 | S.RRI.ReverseInsertPts.clear(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2172 | // FALL THROUGH |
| 2173 | case S_Use: |
Michael Gottesman | 1d8d257 | 2013-04-05 22:54:28 +0000 | [diff] [blame] | 2174 | S.RRI.ReleaseMetadata = ReleaseMetadata; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2175 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 2176 | Releases[Inst] = S.RRI; |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2177 | ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2178 | S.ClearSequenceProgress(); |
| 2179 | break; |
| 2180 | case S_None: |
| 2181 | break; |
| 2182 | case S_Stop: |
| 2183 | case S_Release: |
| 2184 | case S_MovableRelease: |
| 2185 | llvm_unreachable("top-down pointer in release state!"); |
| 2186 | } |
| 2187 | break; |
| 2188 | } |
| 2189 | case IC_AutoreleasepoolPop: |
| 2190 | // Conservatively, clear MyStates for all known pointers. |
| 2191 | MyStates.clearTopDownPointers(); |
| 2192 | return NestingDetected; |
| 2193 | case IC_AutoreleasepoolPush: |
| 2194 | case IC_None: |
| 2195 | // These are irrelevant. |
| 2196 | return NestingDetected; |
| 2197 | default: |
| 2198 | break; |
| 2199 | } |
| 2200 | |
| 2201 | // Consider any other possible effects of this instruction on each |
| 2202 | // pointer being tracked. |
| 2203 | for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(), |
| 2204 | ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) { |
| 2205 | const Value *Ptr = MI->first; |
| 2206 | if (Ptr == Arg) |
| 2207 | continue; // Handled above. |
| 2208 | PtrState &S = MI->second; |
| 2209 | Sequence Seq = S.GetSeq(); |
| 2210 | |
| 2211 | // Check for possible releases. |
| 2212 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Michael Gottesman | bab49e97 | 2013-04-05 18:26:08 +0000 | [diff] [blame] | 2213 | DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2214 | << "\n"); |
Michael Gottesman | 764b1cf | 2013-03-23 05:46:19 +0000 | [diff] [blame] | 2215 | S.ClearKnownPositiveRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2216 | switch (Seq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2217 | case S_Retain: |
| 2218 | S.SetSeq(S_CanRelease); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2219 | ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2220 | assert(S.RRI.ReverseInsertPts.empty()); |
| 2221 | S.RRI.ReverseInsertPts.insert(Inst); |
| 2222 | |
| 2223 | // One call can't cause a transition from S_Retain to S_CanRelease |
| 2224 | // and S_CanRelease to S_Use. If we've made the first transition, |
| 2225 | // we're done. |
| 2226 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2227 | case S_Use: |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2228 | case S_CanRelease: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2229 | case S_None: |
| 2230 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2231 | case S_Stop: |
| 2232 | case S_Release: |
| 2233 | case S_MovableRelease: |
| 2234 | llvm_unreachable("top-down pointer in release state!"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2235 | } |
| 2236 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2237 | |
| 2238 | // Check for possible direct uses. |
| 2239 | switch (Seq) { |
| 2240 | case S_CanRelease: |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2241 | if (CanUse(Inst, Ptr, PA, Class)) { |
Michael Gottesman | bab49e97 | 2013-04-05 18:26:08 +0000 | [diff] [blame] | 2242 | DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr |
| 2243 | << "\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2244 | S.SetSeq(S_Use); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 2245 | ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use); |
| 2246 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2247 | break; |
| 2248 | case S_Retain: |
| 2249 | case S_Use: |
| 2250 | case S_None: |
| 2251 | break; |
| 2252 | case S_Stop: |
| 2253 | case S_Release: |
| 2254 | case S_MovableRelease: |
| 2255 | llvm_unreachable("top-down pointer in release state!"); |
| 2256 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2257 | } |
| 2258 | |
| 2259 | return NestingDetected; |
| 2260 | } |
| 2261 | |
| 2262 | bool |
| 2263 | ObjCARCOpt::VisitTopDown(BasicBlock *BB, |
| 2264 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2265 | DenseMap<Value *, RRInfo> &Releases) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2266 | DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2267 | bool NestingDetected = false; |
| 2268 | BBState &MyStates = BBStates[BB]; |
| 2269 | |
| 2270 | // Merge the states from each predecessor to compute the initial state |
| 2271 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 2272 | BBState::edge_iterator PI(MyStates.pred_begin()), |
| 2273 | PE(MyStates.pred_end()); |
| 2274 | if (PI != PE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2275 | const BasicBlock *Pred = *PI; |
| 2276 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); |
| 2277 | assert(I != BBStates.end()); |
| 2278 | MyStates.InitFromPred(I->second); |
| 2279 | ++PI; |
| 2280 | for (; PI != PE; ++PI) { |
| 2281 | Pred = *PI; |
| 2282 | I = BBStates.find(Pred); |
| 2283 | assert(I != BBStates.end()); |
| 2284 | MyStates.MergePred(I->second); |
| 2285 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2286 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2287 | |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 2288 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 2289 | // top of the basic block. |
| 2290 | ANNOTATE_TOPDOWN_BBSTART(MyStates, BB); |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2291 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2292 | // Visit all the instructions, top-down. |
| 2293 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 2294 | Instruction *Inst = I; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2295 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2296 | DEBUG(dbgs() << "Visiting " << *Inst << "\n"); |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2297 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2298 | NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2299 | } |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2300 | |
Michael Gottesman | 43e7e00 | 2013-04-03 22:41:59 +0000 | [diff] [blame] | 2301 | // If ARC Annotations are enabled, output the current state of pointers at the |
| 2302 | // bottom of the basic block. |
| 2303 | ANNOTATE_TOPDOWN_BBEND(MyStates, BB); |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2304 | |
Michael Gottesman | ffef24f | 2013-04-17 20:48:01 +0000 | [diff] [blame] | 2305 | #ifdef ARC_ANNOTATIONS |
Michael Gottesman | adb921a | 2013-04-17 21:03:53 +0000 | [diff] [blame] | 2306 | if (!(EnableARCAnnotations && DisableCheckForCFGHazards)) |
Michael Gottesman | ffef24f | 2013-04-17 20:48:01 +0000 | [diff] [blame] | 2307 | #endif |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2308 | CheckForCFGHazards(BB, BBStates, MyStates); |
| 2309 | return NestingDetected; |
| 2310 | } |
| 2311 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2312 | static void |
| 2313 | ComputePostOrders(Function &F, |
| 2314 | SmallVectorImpl<BasicBlock *> &PostOrder, |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2315 | SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, |
| 2316 | unsigned NoObjCARCExceptionsMDKind, |
| 2317 | DenseMap<const BasicBlock *, BBState> &BBStates) { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2318 | /// The visited set, for doing DFS walks. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2319 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 2320 | |
| 2321 | // Do DFS, computing the PostOrder. |
| 2322 | SmallPtrSet<BasicBlock *, 16> OnStack; |
| 2323 | SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2324 | |
| 2325 | // Functions always have exactly one entry block, and we don't have |
| 2326 | // any other block that we treat like an entry block. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2327 | BasicBlock *EntryBB = &F.getEntryBlock(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2328 | BBState &MyStates = BBStates[EntryBB]; |
| 2329 | MyStates.SetAsEntry(); |
| 2330 | TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back()); |
| 2331 | SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2332 | Visited.insert(EntryBB); |
| 2333 | OnStack.insert(EntryBB); |
| 2334 | do { |
| 2335 | dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2336 | BasicBlock *CurrBB = SuccStack.back().first; |
| 2337 | TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back()); |
| 2338 | succ_iterator SE(TI, false); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2339 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2340 | while (SuccStack.back().second != SE) { |
| 2341 | BasicBlock *SuccBB = *SuccStack.back().second++; |
| 2342 | if (Visited.insert(SuccBB)) { |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2343 | TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back()); |
| 2344 | SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI))); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2345 | BBStates[CurrBB].addSucc(SuccBB); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2346 | BBState &SuccStates = BBStates[SuccBB]; |
| 2347 | SuccStates.addPred(CurrBB); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2348 | OnStack.insert(SuccBB); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2349 | goto dfs_next_succ; |
| 2350 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2351 | |
| 2352 | if (!OnStack.count(SuccBB)) { |
| 2353 | BBStates[CurrBB].addSucc(SuccBB); |
| 2354 | BBStates[SuccBB].addPred(CurrBB); |
| 2355 | } |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2356 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2357 | OnStack.erase(CurrBB); |
| 2358 | PostOrder.push_back(CurrBB); |
| 2359 | SuccStack.pop_back(); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2360 | } while (!SuccStack.empty()); |
| 2361 | |
| 2362 | Visited.clear(); |
| 2363 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2364 | // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2365 | // Functions may have many exits, and there also blocks which we treat |
| 2366 | // as exits due to ignored edges. |
| 2367 | SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; |
| 2368 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
| 2369 | BasicBlock *ExitBB = I; |
| 2370 | BBState &MyStates = BBStates[ExitBB]; |
| 2371 | if (!MyStates.isExit()) |
| 2372 | continue; |
| 2373 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2374 | MyStates.SetAsExit(); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2375 | |
| 2376 | PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2377 | Visited.insert(ExitBB); |
| 2378 | while (!PredStack.empty()) { |
| 2379 | reverse_dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2380 | BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); |
| 2381 | while (PredStack.back().second != PE) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2382 | BasicBlock *BB = *PredStack.back().second++; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2383 | if (Visited.insert(BB)) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2384 | PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2385 | goto reverse_dfs_next_succ; |
| 2386 | } |
| 2387 | } |
| 2388 | ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); |
| 2389 | } |
| 2390 | } |
| 2391 | } |
| 2392 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2393 | // Visit the function both top-down and bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2394 | bool |
| 2395 | ObjCARCOpt::Visit(Function &F, |
| 2396 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2397 | MapVector<Value *, RRInfo> &Retains, |
| 2398 | DenseMap<Value *, RRInfo> &Releases) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2399 | |
| 2400 | // Use reverse-postorder traversals, because we magically know that loops |
| 2401 | // will be well behaved, i.e. they won't repeatedly call retain on a single |
| 2402 | // pointer without doing a release. We can't use the ReversePostOrderTraversal |
| 2403 | // class here because we want the reverse-CFG postorder to consider each |
| 2404 | // function exit point, and we want to ignore selected cycle edges. |
| 2405 | SmallVector<BasicBlock *, 16> PostOrder; |
| 2406 | SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 2407 | ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, |
| 2408 | NoObjCARCExceptionsMDKind, |
| 2409 | BBStates); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2410 | |
| 2411 | // Use reverse-postorder on the reverse CFG for bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2412 | bool BottomUpNestingDetected = false; |
Dan Gohman | c57b58c | 2011-08-18 21:27:42 +0000 | [diff] [blame] | 2413 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2414 | ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend(); |
| 2415 | I != E; ++I) |
| 2416 | BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2417 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2418 | // Use reverse-postorder for top-down. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2419 | bool TopDownNestingDetected = false; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 2420 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
| 2421 | PostOrder.rbegin(), E = PostOrder.rend(); |
| 2422 | I != E; ++I) |
| 2423 | TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2424 | |
| 2425 | return TopDownNestingDetected && BottomUpNestingDetected; |
| 2426 | } |
| 2427 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2428 | /// Move the calls in RetainsToMove and ReleasesToMove. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2429 | void ObjCARCOpt::MoveCalls(Value *Arg, |
| 2430 | RRInfo &RetainsToMove, |
| 2431 | RRInfo &ReleasesToMove, |
| 2432 | MapVector<Value *, RRInfo> &Retains, |
| 2433 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2434 | SmallVectorImpl<Instruction *> &DeadInsts, |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2435 | Module *M) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2436 | Type *ArgTy = Arg->getType(); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2437 | Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2438 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2439 | DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2440 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2441 | // Insert the new retain and release calls. |
| 2442 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2443 | PI = ReleasesToMove.ReverseInsertPts.begin(), |
| 2444 | PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
| 2445 | Instruction *InsertPt = *PI; |
| 2446 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2447 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2448 | CallInst *Call = |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame] | 2449 | CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2450 | Call->setDoesNotThrow(); |
Michael Gottesman | ba64859 | 2013-03-28 23:08:44 +0000 | [diff] [blame] | 2451 | Call->setTailCall(); |
Michael Gottesman | 60f6b28 | 2013-03-29 05:13:07 +0000 | [diff] [blame] | 2452 | |
Michael Gottesman | df110ac | 2013-04-21 00:30:50 +0000 | [diff] [blame] | 2453 | DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n" |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2454 | "At insertion point: " << *InsertPt << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2455 | } |
| 2456 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2457 | PI = RetainsToMove.ReverseInsertPts.begin(), |
| 2458 | PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2459 | Instruction *InsertPt = *PI; |
| 2460 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 2461 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 2462 | CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg, |
| 2463 | "", InsertPt); |
| 2464 | // Attach a clang.imprecise_release metadata tag, if appropriate. |
| 2465 | if (MDNode *M = ReleasesToMove.ReleaseMetadata) |
| 2466 | Call->setMetadata(ImpreciseReleaseMDKind, M); |
| 2467 | Call->setDoesNotThrow(); |
| 2468 | if (ReleasesToMove.IsTailCallRelease) |
| 2469 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2470 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2471 | DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n" |
| 2472 | "At insertion point: " << *InsertPt << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2473 | } |
| 2474 | |
| 2475 | // Delete the original retain and release calls. |
| 2476 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2477 | AI = RetainsToMove.Calls.begin(), |
| 2478 | AE = RetainsToMove.Calls.end(); AI != AE; ++AI) { |
| 2479 | Instruction *OrigRetain = *AI; |
| 2480 | Retains.blot(OrigRetain); |
| 2481 | DeadInsts.push_back(OrigRetain); |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2482 | DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2483 | } |
| 2484 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2485 | AI = ReleasesToMove.Calls.begin(), |
| 2486 | AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) { |
| 2487 | Instruction *OrigRelease = *AI; |
| 2488 | Releases.erase(OrigRelease); |
| 2489 | DeadInsts.push_back(OrigRelease); |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2490 | DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2491 | } |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2492 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2493 | } |
| 2494 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2495 | bool |
| 2496 | ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> |
| 2497 | &BBStates, |
| 2498 | MapVector<Value *, RRInfo> &Retains, |
| 2499 | DenseMap<Value *, RRInfo> &Releases, |
| 2500 | Module *M, |
| 2501 | SmallVector<Instruction *, 4> &NewRetains, |
| 2502 | SmallVector<Instruction *, 4> &NewReleases, |
| 2503 | SmallVector<Instruction *, 8> &DeadInsts, |
| 2504 | RRInfo &RetainsToMove, |
| 2505 | RRInfo &ReleasesToMove, |
| 2506 | Value *Arg, |
| 2507 | bool KnownSafe, |
| 2508 | bool &AnyPairsCompletelyEliminated) { |
| 2509 | // If a pair happens in a region where it is known that the reference count |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 2510 | // is already incremented, we can similarly ignore possible decrements unless |
| 2511 | // we are dealing with a retainable object with multiple provenance sources. |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2512 | bool KnownSafeTD = true, KnownSafeBU = true; |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 2513 | bool MultipleOwners = false; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 2514 | bool CFGHazardAfflicted = false; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2515 | |
| 2516 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2517 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
| 2518 | // This is an iterative process so that we connect multiple releases |
| 2519 | // to multiple retains if needed. |
| 2520 | unsigned OldDelta = 0; |
| 2521 | unsigned NewDelta = 0; |
| 2522 | unsigned OldCount = 0; |
| 2523 | unsigned NewCount = 0; |
| 2524 | bool FirstRelease = true; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2525 | for (;;) { |
| 2526 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2527 | NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) { |
| 2528 | Instruction *NewRetain = *NI; |
| 2529 | MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain); |
| 2530 | assert(It != Retains.end()); |
| 2531 | const RRInfo &NewRetainRRI = It->second; |
| 2532 | KnownSafeTD &= NewRetainRRI.KnownSafe; |
Michael Gottesman | 5a91bbf | 2013-05-24 20:44:02 +0000 | [diff] [blame] | 2533 | MultipleOwners = |
| 2534 | MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain)); |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2535 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2536 | LI = NewRetainRRI.Calls.begin(), |
| 2537 | LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) { |
| 2538 | Instruction *NewRetainRelease = *LI; |
| 2539 | DenseMap<Value *, RRInfo>::const_iterator Jt = |
| 2540 | Releases.find(NewRetainRelease); |
| 2541 | if (Jt == Releases.end()) |
| 2542 | return false; |
| 2543 | const RRInfo &NewRetainReleaseRRI = Jt->second; |
| 2544 | assert(NewRetainReleaseRRI.Calls.count(NewRetain)); |
| 2545 | if (ReleasesToMove.Calls.insert(NewRetainRelease)) { |
| 2546 | OldDelta -= |
| 2547 | BBStates[NewRetainRelease->getParent()].GetAllPathCount(); |
| 2548 | |
| 2549 | // Merge the ReleaseMetadata and IsTailCallRelease values. |
| 2550 | if (FirstRelease) { |
| 2551 | ReleasesToMove.ReleaseMetadata = |
| 2552 | NewRetainReleaseRRI.ReleaseMetadata; |
| 2553 | ReleasesToMove.IsTailCallRelease = |
| 2554 | NewRetainReleaseRRI.IsTailCallRelease; |
| 2555 | FirstRelease = false; |
| 2556 | } else { |
| 2557 | if (ReleasesToMove.ReleaseMetadata != |
| 2558 | NewRetainReleaseRRI.ReleaseMetadata) |
| 2559 | ReleasesToMove.ReleaseMetadata = 0; |
| 2560 | if (ReleasesToMove.IsTailCallRelease != |
| 2561 | NewRetainReleaseRRI.IsTailCallRelease) |
| 2562 | ReleasesToMove.IsTailCallRelease = false; |
| 2563 | } |
| 2564 | |
| 2565 | // Collect the optimal insertion points. |
| 2566 | if (!KnownSafe) |
| 2567 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2568 | RI = NewRetainReleaseRRI.ReverseInsertPts.begin(), |
| 2569 | RE = NewRetainReleaseRRI.ReverseInsertPts.end(); |
| 2570 | RI != RE; ++RI) { |
| 2571 | Instruction *RIP = *RI; |
| 2572 | if (ReleasesToMove.ReverseInsertPts.insert(RIP)) |
| 2573 | NewDelta -= BBStates[RIP->getParent()].GetAllPathCount(); |
| 2574 | } |
| 2575 | NewReleases.push_back(NewRetainRelease); |
| 2576 | } |
| 2577 | } |
| 2578 | } |
| 2579 | NewRetains.clear(); |
| 2580 | if (NewReleases.empty()) break; |
| 2581 | |
| 2582 | // Back the other way. |
| 2583 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 2584 | NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) { |
| 2585 | Instruction *NewRelease = *NI; |
| 2586 | DenseMap<Value *, RRInfo>::const_iterator It = |
| 2587 | Releases.find(NewRelease); |
| 2588 | assert(It != Releases.end()); |
| 2589 | const RRInfo &NewReleaseRRI = It->second; |
| 2590 | KnownSafeBU &= NewReleaseRRI.KnownSafe; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 2591 | CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2592 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2593 | LI = NewReleaseRRI.Calls.begin(), |
| 2594 | LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) { |
| 2595 | Instruction *NewReleaseRetain = *LI; |
| 2596 | MapVector<Value *, RRInfo>::const_iterator Jt = |
| 2597 | Retains.find(NewReleaseRetain); |
| 2598 | if (Jt == Retains.end()) |
| 2599 | return false; |
| 2600 | const RRInfo &NewReleaseRetainRRI = Jt->second; |
| 2601 | assert(NewReleaseRetainRRI.Calls.count(NewRelease)); |
| 2602 | if (RetainsToMove.Calls.insert(NewReleaseRetain)) { |
| 2603 | unsigned PathCount = |
| 2604 | BBStates[NewReleaseRetain->getParent()].GetAllPathCount(); |
| 2605 | OldDelta += PathCount; |
| 2606 | OldCount += PathCount; |
| 2607 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2608 | // Collect the optimal insertion points. |
| 2609 | if (!KnownSafe) |
| 2610 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 2611 | RI = NewReleaseRetainRRI.ReverseInsertPts.begin(), |
| 2612 | RE = NewReleaseRetainRRI.ReverseInsertPts.end(); |
| 2613 | RI != RE; ++RI) { |
| 2614 | Instruction *RIP = *RI; |
| 2615 | if (RetainsToMove.ReverseInsertPts.insert(RIP)) { |
| 2616 | PathCount = BBStates[RIP->getParent()].GetAllPathCount(); |
| 2617 | NewDelta += PathCount; |
| 2618 | NewCount += PathCount; |
| 2619 | } |
| 2620 | } |
| 2621 | NewRetains.push_back(NewReleaseRetain); |
| 2622 | } |
| 2623 | } |
| 2624 | } |
| 2625 | NewReleases.clear(); |
| 2626 | if (NewRetains.empty()) break; |
| 2627 | } |
| 2628 | |
Michael Gottesman | a76143ee | 2013-05-13 23:49:42 +0000 | [diff] [blame] | 2629 | // If the pointer is known incremented in 1 direction and we do not have |
| 2630 | // MultipleOwners, we can safely remove the retain/releases. Otherwise we need |
| 2631 | // to be known safe in both directions. |
| 2632 | bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) || |
| 2633 | ((KnownSafeTD || KnownSafeBU) && !MultipleOwners); |
| 2634 | if (UnconditionallySafe) { |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2635 | RetainsToMove.ReverseInsertPts.clear(); |
| 2636 | ReleasesToMove.ReverseInsertPts.clear(); |
| 2637 | NewCount = 0; |
| 2638 | } else { |
| 2639 | // Determine whether the new insertion points we computed preserve the |
| 2640 | // balance of retain and release calls through the program. |
| 2641 | // TODO: If the fully aggressive solution isn't valid, try to find a |
| 2642 | // less aggressive solution which is. |
| 2643 | if (NewDelta != 0) |
| 2644 | return false; |
Michael Gottesman | e67f40c | 2013-05-24 20:44:05 +0000 | [diff] [blame^] | 2645 | |
| 2646 | // At this point, we are not going to remove any RR pairs, but we still are |
| 2647 | // able to move RR pairs. If one of our pointers is afflicted with |
| 2648 | // CFGHazards, we cannot perform such code motion so exit early. |
| 2649 | const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() || |
| 2650 | ReleasesToMove.ReverseInsertPts.size(); |
| 2651 | if (CFGHazardAfflicted && WillPerformCodeMotion) |
| 2652 | return false; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2653 | } |
| 2654 | |
| 2655 | // Determine whether the original call points are balanced in the retain and |
| 2656 | // release calls through the program. If not, conservatively don't touch |
| 2657 | // them. |
| 2658 | // TODO: It's theoretically possible to do code motion in this case, as |
| 2659 | // long as the existing imbalances are maintained. |
| 2660 | if (OldDelta != 0) |
| 2661 | return false; |
Michael Gottesman | 8005ad3 | 2013-04-29 06:16:55 +0000 | [diff] [blame] | 2662 | |
Michael Gottesman | a87bb8f | 2013-04-29 05:13:13 +0000 | [diff] [blame] | 2663 | #ifdef ARC_ANNOTATIONS |
| 2664 | // Do not move calls if ARC annotations are requested. |
Michael Gottesman | 3e3977c | 2013-04-29 05:25:39 +0000 | [diff] [blame] | 2665 | if (EnableARCAnnotations) |
| 2666 | return false; |
Michael Gottesman | a87bb8f | 2013-04-29 05:13:13 +0000 | [diff] [blame] | 2667 | #endif // ARC_ANNOTATIONS |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2668 | |
| 2669 | Changed = true; |
| 2670 | assert(OldCount != 0 && "Unreachable code?"); |
| 2671 | NumRRs += OldCount - NewCount; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2672 | // Set to true if we completely removed any RR pairs. |
Michael Gottesman | 8b5515f | 2013-01-22 21:53:43 +0000 | [diff] [blame] | 2673 | AnyPairsCompletelyEliminated = NewCount == 0; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2674 | |
| 2675 | // We can move calls! |
| 2676 | return true; |
| 2677 | } |
| 2678 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2679 | /// Identify pairings between the retains and releases, and delete and/or move |
| 2680 | /// them. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2681 | bool |
| 2682 | ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState> |
| 2683 | &BBStates, |
| 2684 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 2685 | DenseMap<Value *, RRInfo> &Releases, |
| 2686 | Module *M) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2687 | DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n"); |
| 2688 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2689 | bool AnyPairsCompletelyEliminated = false; |
| 2690 | RRInfo RetainsToMove; |
| 2691 | RRInfo ReleasesToMove; |
| 2692 | SmallVector<Instruction *, 4> NewRetains; |
| 2693 | SmallVector<Instruction *, 4> NewReleases; |
| 2694 | SmallVector<Instruction *, 8> DeadInsts; |
| 2695 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2696 | // Visit each retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2697 | for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), |
Dan Gohman | 2053a5d | 2011-09-29 22:25:23 +0000 | [diff] [blame] | 2698 | E = Retains.end(); I != E; ++I) { |
| 2699 | Value *V = I->first; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2700 | if (!V) continue; // blotted |
| 2701 | |
| 2702 | Instruction *Retain = cast<Instruction>(V); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2703 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2704 | DEBUG(dbgs() << "Visiting: " << *Retain << "\n"); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2705 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2706 | Value *Arg = GetObjCArg(Retain); |
| 2707 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2708 | // If the object being released is in static or stack storage, we know it's |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2709 | // not being managed by ObjC reference counting, so we can delete pairs |
| 2710 | // regardless of what possible decrements or uses lie between them. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 2711 | bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2712 | |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 2713 | // A constant pointer can't be pointing to an object on the heap. It may |
| 2714 | // be reference-counted, but it won't be deleted. |
| 2715 | if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) |
| 2716 | if (const GlobalVariable *GV = |
| 2717 | dyn_cast<GlobalVariable>( |
| 2718 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()))) |
| 2719 | if (GV->isConstant()) |
| 2720 | KnownSafe = true; |
| 2721 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2722 | // Connect the dots between the top-down-collected RetainsToMove and |
| 2723 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2724 | NewRetains.push_back(Retain); |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2725 | bool PerformMoveCalls = |
| 2726 | ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains, |
| 2727 | NewReleases, DeadInsts, RetainsToMove, |
| 2728 | ReleasesToMove, Arg, KnownSafe, |
| 2729 | AnyPairsCompletelyEliminated); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2730 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2731 | if (PerformMoveCalls) { |
| 2732 | // Ok, everything checks out and we're all set. Let's move/delete some |
| 2733 | // code! |
| 2734 | MoveCalls(Arg, RetainsToMove, ReleasesToMove, |
| 2735 | Retains, Releases, DeadInsts, M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2736 | } |
| 2737 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 2738 | // Clean up state for next retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2739 | NewReleases.clear(); |
| 2740 | NewRetains.clear(); |
| 2741 | RetainsToMove.clear(); |
| 2742 | ReleasesToMove.clear(); |
| 2743 | } |
| 2744 | |
| 2745 | // Now that we're done moving everything, we can delete the newly dead |
| 2746 | // instructions, as we no longer need them as insert points. |
| 2747 | while (!DeadInsts.empty()) |
| 2748 | EraseInstruction(DeadInsts.pop_back_val()); |
| 2749 | |
| 2750 | return AnyPairsCompletelyEliminated; |
| 2751 | } |
| 2752 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2753 | /// Weak pointer optimizations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2754 | void ObjCARCOpt::OptimizeWeakCalls(Function &F) { |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2755 | DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2756 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2757 | // First, do memdep-style RLE and S2L optimizations. We can't use memdep |
| 2758 | // itself because it uses AliasAnalysis and we need to do provenance |
| 2759 | // queries instead. |
| 2760 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2761 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2762 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 2763 | DEBUG(dbgs() << "Visiting: " << *Inst << "\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2764 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2765 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2766 | if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained) |
| 2767 | continue; |
| 2768 | |
| 2769 | // Delete objc_loadWeak calls with no users. |
| 2770 | if (Class == IC_LoadWeak && Inst->use_empty()) { |
| 2771 | Inst->eraseFromParent(); |
| 2772 | continue; |
| 2773 | } |
| 2774 | |
| 2775 | // TODO: For now, just look for an earlier available version of this value |
| 2776 | // within the same block. Theoretically, we could do memdep-style non-local |
| 2777 | // analysis too, but that would want caching. A better approach would be to |
| 2778 | // use the technique that EarlyCSE uses. |
| 2779 | inst_iterator Current = llvm::prior(I); |
| 2780 | BasicBlock *CurrentBB = Current.getBasicBlockIterator(); |
| 2781 | for (BasicBlock::iterator B = CurrentBB->begin(), |
| 2782 | J = Current.getInstructionIterator(); |
| 2783 | J != B; --J) { |
| 2784 | Instruction *EarlierInst = &*llvm::prior(J); |
| 2785 | InstructionClass EarlierClass = GetInstructionClass(EarlierInst); |
| 2786 | switch (EarlierClass) { |
| 2787 | case IC_LoadWeak: |
| 2788 | case IC_LoadWeakRetained: { |
| 2789 | // If this is loading from the same pointer, replace this load's value |
| 2790 | // with that one. |
| 2791 | CallInst *Call = cast<CallInst>(Inst); |
| 2792 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 2793 | Value *Arg = Call->getArgOperand(0); |
| 2794 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 2795 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 2796 | case AliasAnalysis::MustAlias: |
| 2797 | Changed = true; |
| 2798 | // If the load has a builtin retain, insert a plain retain for it. |
| 2799 | if (Class == IC_LoadWeakRetained) { |
| 2800 | CallInst *CI = |
| 2801 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 2802 | "", Call); |
| 2803 | CI->setTailCall(); |
| 2804 | } |
| 2805 | // Zap the fully redundant load. |
| 2806 | Call->replaceAllUsesWith(EarlierCall); |
| 2807 | Call->eraseFromParent(); |
| 2808 | goto clobbered; |
| 2809 | case AliasAnalysis::MayAlias: |
| 2810 | case AliasAnalysis::PartialAlias: |
| 2811 | goto clobbered; |
| 2812 | case AliasAnalysis::NoAlias: |
| 2813 | break; |
| 2814 | } |
| 2815 | break; |
| 2816 | } |
| 2817 | case IC_StoreWeak: |
| 2818 | case IC_InitWeak: { |
| 2819 | // If this is storing to the same pointer and has the same size etc. |
| 2820 | // replace this load's value with the stored value. |
| 2821 | CallInst *Call = cast<CallInst>(Inst); |
| 2822 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 2823 | Value *Arg = Call->getArgOperand(0); |
| 2824 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 2825 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 2826 | case AliasAnalysis::MustAlias: |
| 2827 | Changed = true; |
| 2828 | // If the load has a builtin retain, insert a plain retain for it. |
| 2829 | if (Class == IC_LoadWeakRetained) { |
| 2830 | CallInst *CI = |
| 2831 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 2832 | "", Call); |
| 2833 | CI->setTailCall(); |
| 2834 | } |
| 2835 | // Zap the fully redundant load. |
| 2836 | Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); |
| 2837 | Call->eraseFromParent(); |
| 2838 | goto clobbered; |
| 2839 | case AliasAnalysis::MayAlias: |
| 2840 | case AliasAnalysis::PartialAlias: |
| 2841 | goto clobbered; |
| 2842 | case AliasAnalysis::NoAlias: |
| 2843 | break; |
| 2844 | } |
| 2845 | break; |
| 2846 | } |
| 2847 | case IC_MoveWeak: |
| 2848 | case IC_CopyWeak: |
| 2849 | // TOOD: Grab the copied value. |
| 2850 | goto clobbered; |
| 2851 | case IC_AutoreleasepoolPush: |
| 2852 | case IC_None: |
John McCall | 20182ac | 2013-03-22 21:38:36 +0000 | [diff] [blame] | 2853 | case IC_IntrinsicUser: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2854 | case IC_User: |
| 2855 | // Weak pointers are only modified through the weak entry points |
| 2856 | // (and arbitrary calls, which could call the weak entry points). |
| 2857 | break; |
| 2858 | default: |
| 2859 | // Anything else could modify the weak pointer. |
| 2860 | goto clobbered; |
| 2861 | } |
| 2862 | } |
| 2863 | clobbered:; |
| 2864 | } |
| 2865 | |
| 2866 | // Then, for each destroyWeak with an alloca operand, check to see if |
| 2867 | // the alloca and all its users can be zapped. |
| 2868 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2869 | Instruction *Inst = &*I++; |
| 2870 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2871 | if (Class != IC_DestroyWeak) |
| 2872 | continue; |
| 2873 | |
| 2874 | CallInst *Call = cast<CallInst>(Inst); |
| 2875 | Value *Arg = Call->getArgOperand(0); |
| 2876 | if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { |
| 2877 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 2878 | UE = Alloca->use_end(); UI != UE; ++UI) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2879 | const Instruction *UserInst = cast<Instruction>(*UI); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2880 | switch (GetBasicInstructionClass(UserInst)) { |
| 2881 | case IC_InitWeak: |
| 2882 | case IC_StoreWeak: |
| 2883 | case IC_DestroyWeak: |
| 2884 | continue; |
| 2885 | default: |
| 2886 | goto done; |
| 2887 | } |
| 2888 | } |
| 2889 | Changed = true; |
| 2890 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 2891 | UE = Alloca->use_end(); UI != UE; ) { |
| 2892 | CallInst *UserInst = cast<CallInst>(*UI++); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 2893 | switch (GetBasicInstructionClass(UserInst)) { |
| 2894 | case IC_InitWeak: |
| 2895 | case IC_StoreWeak: |
| 2896 | // These functions return their second argument. |
| 2897 | UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); |
| 2898 | break; |
| 2899 | case IC_DestroyWeak: |
| 2900 | // No return value. |
| 2901 | break; |
| 2902 | default: |
Dan Gohman | 9c97eea0 | 2012-05-21 17:41:28 +0000 | [diff] [blame] | 2903 | llvm_unreachable("alloca really is used!"); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 2904 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2905 | UserInst->eraseFromParent(); |
| 2906 | } |
| 2907 | Alloca->eraseFromParent(); |
| 2908 | done:; |
| 2909 | } |
| 2910 | } |
| 2911 | } |
| 2912 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2913 | /// Identify program paths which execute sequences of retains and releases which |
| 2914 | /// can be eliminated. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2915 | bool ObjCARCOpt::OptimizeSequences(Function &F) { |
Michael Gottesman | 740db97 | 2013-05-23 02:35:21 +0000 | [diff] [blame] | 2916 | // Releases, Retains - These are used to store the results of the main flow |
| 2917 | // analysis. These use Value* as the key instead of Instruction* so that the |
| 2918 | // map stays valid when we get around to rewriting code and calls get |
| 2919 | // replaced by arguments. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2920 | DenseMap<Value *, RRInfo> Releases; |
| 2921 | MapVector<Value *, RRInfo> Retains; |
| 2922 | |
Michael Gottesman | 740db97 | 2013-05-23 02:35:21 +0000 | [diff] [blame] | 2923 | // This is used during the traversal of the function to track the |
| 2924 | // states for each identified object at each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2925 | DenseMap<const BasicBlock *, BBState> BBStates; |
| 2926 | |
| 2927 | // Analyze the CFG of the function, and all instructions. |
| 2928 | bool NestingDetected = Visit(F, BBStates, Retains, Releases); |
| 2929 | |
| 2930 | // Transform. |
Michael Gottesman | 5a91bbf | 2013-05-24 20:44:02 +0000 | [diff] [blame] | 2931 | bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains, |
| 2932 | Releases, |
| 2933 | F.getParent()); |
| 2934 | |
| 2935 | // Cleanup. |
| 2936 | MultiOwnersSet.clear(); |
| 2937 | |
| 2938 | return AnyPairsCompletelyEliminated && NestingDetected; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2939 | } |
| 2940 | |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2941 | /// Check if there is a dependent call earlier that does not have anything in |
| 2942 | /// between the Retain and the call that can affect the reference count of their |
| 2943 | /// shared pointer argument. Note that Retain need not be in BB. |
Michael Gottesman | 54dc7fd | 2013-04-03 23:04:28 +0000 | [diff] [blame] | 2944 | static bool |
| 2945 | HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain, |
| 2946 | SmallPtrSet<Instruction *, 4> &DepInsts, |
| 2947 | SmallPtrSet<const BasicBlock *, 4> &Visited, |
| 2948 | ProvenanceAnalysis &PA) { |
| 2949 | FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, |
| 2950 | DepInsts, Visited, PA); |
| 2951 | if (DepInsts.size() != 1) |
| 2952 | return false; |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2953 | |
Michael Gottesman | 54dc7fd | 2013-04-03 23:04:28 +0000 | [diff] [blame] | 2954 | CallInst *Call = |
| 2955 | dyn_cast_or_null<CallInst>(*DepInsts.begin()); |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2956 | |
Michael Gottesman | 54dc7fd | 2013-04-03 23:04:28 +0000 | [diff] [blame] | 2957 | // Check that the pointer is the return value of the call. |
| 2958 | if (!Call || Arg != Call) |
| 2959 | return false; |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2960 | |
Michael Gottesman | 54dc7fd | 2013-04-03 23:04:28 +0000 | [diff] [blame] | 2961 | // Check that the call is a regular call. |
| 2962 | InstructionClass Class = GetBasicInstructionClass(Call); |
| 2963 | if (Class != IC_CallOrUser && Class != IC_Call) |
| 2964 | return false; |
Michael Gottesman | c2d5bf5 | 2013-04-03 23:07:45 +0000 | [diff] [blame] | 2965 | |
Michael Gottesman | 54dc7fd | 2013-04-03 23:04:28 +0000 | [diff] [blame] | 2966 | return true; |
| 2967 | } |
| 2968 | |
Michael Gottesman | 6908db1 | 2013-04-03 23:16:05 +0000 | [diff] [blame] | 2969 | /// Find a dependent retain that precedes the given autorelease for which there |
| 2970 | /// is nothing in between the two instructions that can affect the ref count of |
| 2971 | /// Arg. |
| 2972 | static CallInst * |
| 2973 | FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB, |
| 2974 | Instruction *Autorelease, |
| 2975 | SmallPtrSet<Instruction *, 4> &DepInsts, |
| 2976 | SmallPtrSet<const BasicBlock *, 4> &Visited, |
| 2977 | ProvenanceAnalysis &PA) { |
| 2978 | FindDependencies(CanChangeRetainCount, Arg, |
| 2979 | BB, Autorelease, DepInsts, Visited, PA); |
| 2980 | if (DepInsts.size() != 1) |
| 2981 | return 0; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2982 | |
Michael Gottesman | 6908db1 | 2013-04-03 23:16:05 +0000 | [diff] [blame] | 2983 | CallInst *Retain = |
| 2984 | dyn_cast_or_null<CallInst>(*DepInsts.begin()); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2985 | |
Michael Gottesman | 6908db1 | 2013-04-03 23:16:05 +0000 | [diff] [blame] | 2986 | // Check that we found a retain with the same argument. |
| 2987 | if (!Retain || |
| 2988 | !IsRetain(GetBasicInstructionClass(Retain)) || |
| 2989 | GetObjCArg(Retain) != Arg) { |
| 2990 | return 0; |
| 2991 | } |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 2992 | |
Michael Gottesman | 6908db1 | 2013-04-03 23:16:05 +0000 | [diff] [blame] | 2993 | return Retain; |
| 2994 | } |
| 2995 | |
Michael Gottesman | 21a4ed3 | 2013-04-03 23:39:14 +0000 | [diff] [blame] | 2996 | /// Look for an ``autorelease'' instruction dependent on Arg such that there are |
| 2997 | /// no instructions dependent on Arg that need a positive ref count in between |
| 2998 | /// the autorelease and the ret. |
| 2999 | static CallInst * |
| 3000 | FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB, |
| 3001 | ReturnInst *Ret, |
| 3002 | SmallPtrSet<Instruction *, 4> &DepInsts, |
| 3003 | SmallPtrSet<const BasicBlock *, 4> &V, |
| 3004 | ProvenanceAnalysis &PA) { |
| 3005 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 3006 | BB, Ret, DepInsts, V, PA); |
| 3007 | if (DepInsts.size() != 1) |
| 3008 | return 0; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3009 | |
Michael Gottesman | 21a4ed3 | 2013-04-03 23:39:14 +0000 | [diff] [blame] | 3010 | CallInst *Autorelease = |
| 3011 | dyn_cast_or_null<CallInst>(*DepInsts.begin()); |
| 3012 | if (!Autorelease) |
| 3013 | return 0; |
| 3014 | InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease); |
| 3015 | if (!IsAutorelease(AutoreleaseClass)) |
| 3016 | return 0; |
| 3017 | if (GetObjCArg(Autorelease) != Arg) |
| 3018 | return 0; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3019 | |
Michael Gottesman | 21a4ed3 | 2013-04-03 23:39:14 +0000 | [diff] [blame] | 3020 | return Autorelease; |
| 3021 | } |
| 3022 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3023 | /// Look for this pattern: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3024 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3025 | /// %call = call i8* @something(...) |
| 3026 | /// %2 = call i8* @objc_retain(i8* %call) |
| 3027 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 3028 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3029 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3030 | /// And delete the retain and autorelease. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3031 | void ObjCARCOpt::OptimizeReturns(Function &F) { |
| 3032 | if (!F.getReturnType()->isPointerTy()) |
| 3033 | return; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3034 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 3035 | DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n"); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3036 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3037 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 3038 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 3039 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { |
| 3040 | BasicBlock *BB = FI; |
| 3041 | ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back()); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3042 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 3043 | DEBUG(dbgs() << "Visiting: " << *Ret << "\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3044 | |
Michael Gottesman | 21a4ed3 | 2013-04-03 23:39:14 +0000 | [diff] [blame] | 3045 | if (!Ret) |
| 3046 | continue; |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3047 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3048 | const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0)); |
Michael Gottesman | 7924997 | 2013-04-05 23:46:45 +0000 | [diff] [blame] | 3049 | |
Michael Gottesman | cdb7c15 | 2013-04-21 00:25:04 +0000 | [diff] [blame] | 3050 | // Look for an ``autorelease'' instruction that is a predecessor of Ret and |
Michael Gottesman | 21a4ed3 | 2013-04-03 23:39:14 +0000 | [diff] [blame] | 3051 | // dependent on Arg such that there are no instructions dependent on Arg |
| 3052 | // that need a positive ref count in between the autorelease and Ret. |
| 3053 | CallInst *Autorelease = |
| 3054 | FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret, |
| 3055 | DependingInstructions, Visited, |
| 3056 | PA); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3057 | DependingInstructions.clear(); |
| 3058 | Visited.clear(); |
Michael Gottesman | fb9ece9 | 2013-04-21 00:25:01 +0000 | [diff] [blame] | 3059 | |
| 3060 | if (!Autorelease) |
| 3061 | continue; |
| 3062 | |
| 3063 | CallInst *Retain = |
| 3064 | FindPredecessorRetainWithSafePath(Arg, BB, Autorelease, |
| 3065 | DependingInstructions, Visited, PA); |
| 3066 | DependingInstructions.clear(); |
| 3067 | Visited.clear(); |
| 3068 | |
| 3069 | if (!Retain) |
| 3070 | continue; |
| 3071 | |
| 3072 | // Check that there is nothing that can affect the reference count |
| 3073 | // between the retain and the call. Note that Retain need not be in BB. |
| 3074 | bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain, |
| 3075 | DependingInstructions, |
| 3076 | Visited, PA); |
| 3077 | DependingInstructions.clear(); |
| 3078 | Visited.clear(); |
| 3079 | |
| 3080 | if (!HasSafePathToCall) |
| 3081 | continue; |
| 3082 | |
| 3083 | // If so, we can zap the retain and autorelease. |
| 3084 | Changed = true; |
| 3085 | ++NumRets; |
| 3086 | DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " |
| 3087 | << *Autorelease << "\n"); |
| 3088 | EraseInstruction(Retain); |
| 3089 | EraseInstruction(Autorelease); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3090 | } |
| 3091 | } |
| 3092 | |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 3093 | #ifndef NDEBUG |
| 3094 | void |
| 3095 | ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) { |
| 3096 | llvm::Statistic &NumRetains = |
| 3097 | AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt; |
| 3098 | llvm::Statistic &NumReleases = |
| 3099 | AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt; |
| 3100 | |
| 3101 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 3102 | Instruction *Inst = &*I++; |
| 3103 | switch (GetBasicInstructionClass(Inst)) { |
| 3104 | default: |
| 3105 | break; |
| 3106 | case IC_Retain: |
| 3107 | ++NumRetains; |
| 3108 | break; |
| 3109 | case IC_Release: |
| 3110 | ++NumReleases; |
| 3111 | break; |
| 3112 | } |
| 3113 | } |
| 3114 | } |
| 3115 | #endif |
| 3116 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3117 | bool ObjCARCOpt::doInitialization(Module &M) { |
| 3118 | if (!EnableARCOpts) |
| 3119 | return false; |
| 3120 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3121 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3122 | Run = ModuleHasARC(M); |
| 3123 | if (!Run) |
| 3124 | return false; |
| 3125 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3126 | // Identify the imprecise release metadata kind. |
| 3127 | ImpreciseReleaseMDKind = |
| 3128 | M.getContext().getMDKindID("clang.imprecise_release"); |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 3129 | CopyOnEscapeMDKind = |
| 3130 | M.getContext().getMDKindID("clang.arc.copy_on_escape"); |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 3131 | NoObjCARCExceptionsMDKind = |
| 3132 | M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions"); |
Michael Gottesman | 81b1d43 | 2013-03-26 00:42:04 +0000 | [diff] [blame] | 3133 | #ifdef ARC_ANNOTATIONS |
| 3134 | ARCAnnotationBottomUpMDKind = |
| 3135 | M.getContext().getMDKindID("llvm.arc.annotation.bottomup"); |
| 3136 | ARCAnnotationTopDownMDKind = |
| 3137 | M.getContext().getMDKindID("llvm.arc.annotation.topdown"); |
| 3138 | ARCAnnotationProvenanceSourceMDKind = |
| 3139 | M.getContext().getMDKindID("llvm.arc.annotation.provenancesource"); |
| 3140 | #endif // ARC_ANNOTATIONS |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3141 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3142 | // Intuitively, objc_retain and others are nocapture, however in practice |
| 3143 | // they are not, because they return their argument value. And objc_release |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3144 | // calls finalizers which can have arbitrary side effects. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3145 | |
| 3146 | // These are initialized lazily. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3147 | AutoreleaseRVCallee = 0; |
| 3148 | ReleaseCallee = 0; |
| 3149 | RetainCallee = 0; |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3150 | RetainBlockCallee = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3151 | AutoreleaseCallee = 0; |
| 3152 | |
| 3153 | return false; |
| 3154 | } |
| 3155 | |
| 3156 | bool ObjCARCOpt::runOnFunction(Function &F) { |
| 3157 | if (!EnableARCOpts) |
| 3158 | return false; |
| 3159 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3160 | // If nothing in the Module uses ARC, don't do anything. |
| 3161 | if (!Run) |
| 3162 | return false; |
| 3163 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3164 | Changed = false; |
| 3165 | |
Michael Gottesman | 89279f8 | 2013-04-05 18:10:41 +0000 | [diff] [blame] | 3166 | DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>" |
| 3167 | "\n"); |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 3168 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3169 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 3170 | |
Michael Gottesman | 9fc50b8 | 2013-05-13 18:29:07 +0000 | [diff] [blame] | 3171 | #ifndef NDEBUG |
| 3172 | if (AreStatisticsEnabled()) { |
| 3173 | GatherStatistics(F, false); |
| 3174 | } |
| 3175 | #endif |
| 3176 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3177 | // This pass performs several distinct transformations. As a compile-time aid |
| 3178 | // when compiling code that isn't ObjC, skip these if the relevant ObjC |
| 3179 | // library functions aren't declared. |
| 3180 | |
Michael Gottesman | cd5b027 | 2013-04-24 22:18:15 +0000 | [diff] [blame] | 3181 | // Preliminary optimizations. This also computes UsedInThisFunction. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3182 | OptimizeIndividualCalls(F); |
| 3183 | |
| 3184 | // Optimizations for weak pointers. |
| 3185 | if (UsedInThisFunction & ((1 << IC_LoadWeak) | |
| 3186 | (1 << IC_LoadWeakRetained) | |
| 3187 | (1 << IC_StoreWeak) | |
| 3188 | (1 << IC_InitWeak) | |
| 3189 | (1 << IC_CopyWeak) | |
| 3190 | (1 << IC_MoveWeak) | |
| 3191 | (1 << IC_DestroyWeak))) |
| 3192 | OptimizeWeakCalls(F); |
| 3193 | |
| 3194 | // Optimizations for retain+release pairs. |
| 3195 | if (UsedInThisFunction & ((1 << IC_Retain) | |
| 3196 | (1 << IC_RetainRV) | |
| 3197 | (1 << IC_RetainBlock))) |
| 3198 | if (UsedInThisFunction & (1 << IC_Release)) |
| 3199 | // Run OptimizeSequences until it either stops making changes or |
| 3200 | // no retain+release pair nesting is detected. |
| 3201 | while (OptimizeSequences(F)) {} |
| 3202 | |
| 3203 | // Optimizations if objc_autorelease is used. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3204 | if (UsedInThisFunction & ((1 << IC_Autorelease) | |
| 3205 | (1 << IC_AutoreleaseRV))) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3206 | OptimizeReturns(F); |
| 3207 | |
Michael Gottesman | 9c11815 | 2013-04-29 06:16:57 +0000 | [diff] [blame] | 3208 | // Gather statistics after optimization. |
| 3209 | #ifndef NDEBUG |
| 3210 | if (AreStatisticsEnabled()) { |
| 3211 | GatherStatistics(F, true); |
| 3212 | } |
| 3213 | #endif |
| 3214 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 3215 | DEBUG(dbgs() << "\n"); |
| 3216 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3217 | return Changed; |
| 3218 | } |
| 3219 | |
| 3220 | void ObjCARCOpt::releaseMemory() { |
| 3221 | PA.clear(); |
| 3222 | } |
| 3223 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3224 | /// @} |
| 3225 | /// |