John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1 | //===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===// |
| 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 |
| 16 | /// redundant weak pointer operations, pattern-matching and replacement of |
| 17 | /// low-level operations into higher-level operations, and numerous minor |
| 18 | /// simplifications. |
| 19 | /// |
| 20 | /// This file also defines a simple ARC-aware AliasAnalysis. |
| 21 | /// |
| 22 | /// WARNING: This file knows about certain library functions. It recognizes them |
| 23 | /// by name, and hardwires knowledge of their semantics. |
| 24 | /// |
| 25 | /// WARNING: This file knows about how certain Objective-C library functions are |
| 26 | /// used. Naive LLVM IR transformations which would otherwise be |
| 27 | /// behavior-preserving may break these assumptions. |
| 28 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 29 | //===----------------------------------------------------------------------===// |
| 30 | |
| 31 | #define DEBUG_TYPE "objc-arc" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/DenseMap.h" |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 33 | #include "llvm/ADT/SmallPtrSet.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 34 | #include "llvm/Support/CommandLine.h" |
Chandler Carruth | be81023 | 2013-01-02 10:22:59 +0000 | [diff] [blame] | 35 | #include "llvm/Support/Debug.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 36 | #include "llvm/Support/raw_ostream.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 37 | using namespace llvm; |
| 38 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 39 | /// \brief A handy option to enable/disable all optimizations in this file. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 40 | static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true)); |
| 41 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 42 | /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific. |
| 43 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 44 | |
| 45 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 46 | /// \brief An associative container with fast insertion-order (deterministic) |
| 47 | /// iteration over its elements. Plus the special blot operation. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 48 | template<class KeyT, class ValueT> |
| 49 | class MapVector { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 50 | /// Map keys to indices in Vector. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 51 | typedef DenseMap<KeyT, size_t> MapTy; |
| 52 | MapTy Map; |
| 53 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 54 | typedef std::vector<std::pair<KeyT, ValueT> > VectorTy; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 55 | /// Keys and values. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 56 | VectorTy Vector; |
| 57 | |
| 58 | public: |
| 59 | typedef typename VectorTy::iterator iterator; |
| 60 | typedef typename VectorTy::const_iterator const_iterator; |
| 61 | iterator begin() { return Vector.begin(); } |
| 62 | iterator end() { return Vector.end(); } |
| 63 | const_iterator begin() const { return Vector.begin(); } |
| 64 | const_iterator end() const { return Vector.end(); } |
| 65 | |
| 66 | #ifdef XDEBUG |
| 67 | ~MapVector() { |
| 68 | assert(Vector.size() >= Map.size()); // May differ due to blotting. |
| 69 | for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); |
| 70 | I != E; ++I) { |
| 71 | assert(I->second < Vector.size()); |
| 72 | assert(Vector[I->second].first == I->first); |
| 73 | } |
| 74 | for (typename VectorTy::const_iterator I = Vector.begin(), |
| 75 | E = Vector.end(); I != E; ++I) |
| 76 | assert(!I->first || |
| 77 | (Map.count(I->first) && |
| 78 | Map[I->first] == size_t(I - Vector.begin()))); |
| 79 | } |
| 80 | #endif |
| 81 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 82 | ValueT &operator[](const KeyT &Arg) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 83 | std::pair<typename MapTy::iterator, bool> Pair = |
| 84 | Map.insert(std::make_pair(Arg, size_t(0))); |
| 85 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 86 | size_t Num = Vector.size(); |
| 87 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 88 | Vector.push_back(std::make_pair(Arg, ValueT())); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 89 | return Vector[Num].second; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 90 | } |
| 91 | return Vector[Pair.first->second].second; |
| 92 | } |
| 93 | |
| 94 | std::pair<iterator, bool> |
| 95 | insert(const std::pair<KeyT, ValueT> &InsertPair) { |
| 96 | std::pair<typename MapTy::iterator, bool> Pair = |
| 97 | Map.insert(std::make_pair(InsertPair.first, size_t(0))); |
| 98 | if (Pair.second) { |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 99 | size_t Num = Vector.size(); |
| 100 | Pair.first->second = Num; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 101 | Vector.push_back(InsertPair); |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 102 | return std::make_pair(Vector.begin() + Num, true); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 103 | } |
| 104 | return std::make_pair(Vector.begin() + Pair.first->second, false); |
| 105 | } |
| 106 | |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 107 | const_iterator find(const KeyT &Key) const { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 108 | typename MapTy::const_iterator It = Map.find(Key); |
| 109 | if (It == Map.end()) return Vector.end(); |
| 110 | return Vector.begin() + It->second; |
| 111 | } |
| 112 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 113 | /// This is similar to erase, but instead of removing the element from the |
| 114 | /// vector, it just zeros out the key in the vector. This leaves iterators |
| 115 | /// intact, but clients must be prepared for zeroed-out keys when iterating. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 116 | void blot(const KeyT &Key) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 117 | typename MapTy::iterator It = Map.find(Key); |
| 118 | if (It == Map.end()) return; |
| 119 | Vector[It->second].first = KeyT(); |
| 120 | Map.erase(It); |
| 121 | } |
| 122 | |
| 123 | void clear() { |
| 124 | Map.clear(); |
| 125 | Vector.clear(); |
| 126 | } |
| 127 | }; |
| 128 | } |
| 129 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 130 | /// @} |
| 131 | /// |
| 132 | /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. |
| 133 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 134 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 135 | #include "llvm/ADT/StringSwitch.h" |
| 136 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 137 | #include "llvm/IR/Intrinsics.h" |
| 138 | #include "llvm/IR/Module.h" |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 139 | #include "llvm/Support/CallSite.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 140 | #include "llvm/Transforms/Utils/Local.h" |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 141 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 142 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 143 | /// \enum InstructionClass |
| 144 | /// \brief A simple classification for instructions. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 145 | enum InstructionClass { |
| 146 | IC_Retain, ///< objc_retain |
| 147 | IC_RetainRV, ///< objc_retainAutoreleasedReturnValue |
| 148 | IC_RetainBlock, ///< objc_retainBlock |
| 149 | IC_Release, ///< objc_release |
| 150 | IC_Autorelease, ///< objc_autorelease |
| 151 | IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue |
| 152 | IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush |
| 153 | IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop |
| 154 | IC_NoopCast, ///< objc_retainedObject, etc. |
| 155 | IC_FusedRetainAutorelease, ///< objc_retainAutorelease |
| 156 | IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue |
| 157 | IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive) |
| 158 | IC_StoreWeak, ///< objc_storeWeak (primitive) |
| 159 | IC_InitWeak, ///< objc_initWeak (derived) |
| 160 | IC_LoadWeak, ///< objc_loadWeak (derived) |
| 161 | IC_MoveWeak, ///< objc_moveWeak (derived) |
| 162 | IC_CopyWeak, ///< objc_copyWeak (derived) |
| 163 | IC_DestroyWeak, ///< objc_destroyWeak (derived) |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 164 | IC_StoreStrong, ///< objc_storeStrong (derived) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 165 | IC_CallOrUser, ///< could call objc_release and/or "use" pointers |
| 166 | IC_Call, ///< could call objc_release |
| 167 | IC_User, ///< could "use" a pointer |
| 168 | IC_None ///< anything else |
| 169 | }; |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 170 | |
| 171 | raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) |
| 172 | LLVM_ATTRIBUTE_USED; |
Michael Gottesman | 1d77751 | 2013-01-17 18:36:17 +0000 | [diff] [blame] | 173 | raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) { |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 174 | switch (Class) { |
| 175 | case IC_Retain: |
| 176 | return OS << "IC_Retain"; |
| 177 | case IC_RetainRV: |
| 178 | return OS << "IC_RetainRV"; |
| 179 | case IC_RetainBlock: |
| 180 | return OS << "IC_RetainBlock"; |
| 181 | case IC_Release: |
| 182 | return OS << "IC_Release"; |
| 183 | case IC_Autorelease: |
| 184 | return OS << "IC_Autorelease"; |
| 185 | case IC_AutoreleaseRV: |
| 186 | return OS << "IC_AutoreleaseRV"; |
| 187 | case IC_AutoreleasepoolPush: |
| 188 | return OS << "IC_AutoreleasepoolPush"; |
| 189 | case IC_AutoreleasepoolPop: |
| 190 | return OS << "IC_AutoreleasepoolPop"; |
| 191 | case IC_NoopCast: |
| 192 | return OS << "IC_NoopCast"; |
| 193 | case IC_FusedRetainAutorelease: |
| 194 | return OS << "IC_FusedRetainAutorelease"; |
| 195 | case IC_FusedRetainAutoreleaseRV: |
| 196 | return OS << "IC_FusedRetainAutoreleaseRV"; |
| 197 | case IC_LoadWeakRetained: |
| 198 | return OS << "IC_LoadWeakRetained"; |
| 199 | case IC_StoreWeak: |
| 200 | return OS << "IC_StoreWeak"; |
| 201 | case IC_InitWeak: |
| 202 | return OS << "IC_InitWeak"; |
| 203 | case IC_LoadWeak: |
| 204 | return OS << "IC_LoadWeak"; |
| 205 | case IC_MoveWeak: |
| 206 | return OS << "IC_MoveWeak"; |
| 207 | case IC_CopyWeak: |
| 208 | return OS << "IC_CopyWeak"; |
| 209 | case IC_DestroyWeak: |
| 210 | return OS << "IC_DestroyWeak"; |
| 211 | case IC_StoreStrong: |
| 212 | return OS << "IC_StoreStrong"; |
| 213 | case IC_CallOrUser: |
| 214 | return OS << "IC_CallOrUser"; |
| 215 | case IC_Call: |
| 216 | return OS << "IC_Call"; |
| 217 | case IC_User: |
| 218 | return OS << "IC_User"; |
| 219 | case IC_None: |
| 220 | return OS << "IC_None"; |
| 221 | } |
Benjamin Kramer | 0eba577 | 2013-01-18 19:45:22 +0000 | [diff] [blame] | 222 | llvm_unreachable("Unknown instruction class!"); |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 223 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 224 | } |
| 225 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 226 | /// \brief Test whether the given value is possible a reference-counted pointer. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 227 | static bool IsPotentialUse(const Value *Op) { |
| 228 | // Pointers to static or stack storage are not reference-counted pointers. |
| 229 | if (isa<Constant>(Op) || isa<AllocaInst>(Op)) |
| 230 | return false; |
| 231 | // Special arguments are not reference-counted. |
| 232 | if (const Argument *Arg = dyn_cast<Argument>(Op)) |
| 233 | if (Arg->hasByValAttr() || |
| 234 | Arg->hasNestAttr() || |
| 235 | Arg->hasStructRetAttr()) |
| 236 | return false; |
Dan Gohman | bd944b4 | 2011-12-14 19:10:53 +0000 | [diff] [blame] | 237 | // Only consider values with pointer types. |
| 238 | // It seemes intuitive to exclude function pointer types as well, since |
| 239 | // functions are never reference-counted, however clang occasionally |
| 240 | // bitcasts reference-counted pointers to function-pointer type |
| 241 | // temporarily. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 242 | PointerType *Ty = dyn_cast<PointerType>(Op->getType()); |
Dan Gohman | bd944b4 | 2011-12-14 19:10:53 +0000 | [diff] [blame] | 243 | if (!Ty) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 244 | return false; |
| 245 | // Conservatively assume anything else is a potential use. |
| 246 | return true; |
| 247 | } |
| 248 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 249 | /// \brief Helper for GetInstructionClass. Determines what kind of construct CS |
| 250 | /// is. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 251 | static InstructionClass GetCallSiteClass(ImmutableCallSite CS) { |
| 252 | for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); |
| 253 | I != E; ++I) |
| 254 | if (IsPotentialUse(*I)) |
| 255 | return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser; |
| 256 | |
| 257 | return CS.onlyReadsMemory() ? IC_None : IC_Call; |
| 258 | } |
| 259 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 260 | /// \brief Determine if F is one of the special known Functions. If it isn't, |
| 261 | /// return IC_CallOrUser. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 262 | static InstructionClass GetFunctionClass(const Function *F) { |
| 263 | Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); |
| 264 | |
| 265 | // No arguments. |
| 266 | if (AI == AE) |
| 267 | return StringSwitch<InstructionClass>(F->getName()) |
| 268 | .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush) |
| 269 | .Default(IC_CallOrUser); |
| 270 | |
| 271 | // One argument. |
| 272 | const Argument *A0 = AI++; |
| 273 | if (AI == AE) |
| 274 | // Argument is a pointer. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 275 | if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) { |
| 276 | Type *ETy = PTy->getElementType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 277 | // Argument is i8*. |
| 278 | if (ETy->isIntegerTy(8)) |
| 279 | return StringSwitch<InstructionClass>(F->getName()) |
| 280 | .Case("objc_retain", IC_Retain) |
| 281 | .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV) |
| 282 | .Case("objc_retainBlock", IC_RetainBlock) |
| 283 | .Case("objc_release", IC_Release) |
| 284 | .Case("objc_autorelease", IC_Autorelease) |
| 285 | .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV) |
| 286 | .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop) |
| 287 | .Case("objc_retainedObject", IC_NoopCast) |
| 288 | .Case("objc_unretainedObject", IC_NoopCast) |
| 289 | .Case("objc_unretainedPointer", IC_NoopCast) |
| 290 | .Case("objc_retain_autorelease", IC_FusedRetainAutorelease) |
| 291 | .Case("objc_retainAutorelease", IC_FusedRetainAutorelease) |
| 292 | .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV) |
| 293 | .Default(IC_CallOrUser); |
| 294 | |
| 295 | // Argument is i8** |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 296 | if (PointerType *Pte = dyn_cast<PointerType>(ETy)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 297 | if (Pte->getElementType()->isIntegerTy(8)) |
| 298 | return StringSwitch<InstructionClass>(F->getName()) |
| 299 | .Case("objc_loadWeakRetained", IC_LoadWeakRetained) |
| 300 | .Case("objc_loadWeak", IC_LoadWeak) |
| 301 | .Case("objc_destroyWeak", IC_DestroyWeak) |
| 302 | .Default(IC_CallOrUser); |
| 303 | } |
| 304 | |
| 305 | // Two arguments, first is i8**. |
| 306 | const Argument *A1 = AI++; |
| 307 | if (AI == AE) |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 308 | if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) |
| 309 | if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType())) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 310 | if (Pte->getElementType()->isIntegerTy(8)) |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 311 | if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) { |
| 312 | Type *ETy1 = PTy1->getElementType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 313 | // Second argument is i8* |
| 314 | if (ETy1->isIntegerTy(8)) |
| 315 | return StringSwitch<InstructionClass>(F->getName()) |
| 316 | .Case("objc_storeWeak", IC_StoreWeak) |
| 317 | .Case("objc_initWeak", IC_InitWeak) |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 318 | .Case("objc_storeStrong", IC_StoreStrong) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 319 | .Default(IC_CallOrUser); |
| 320 | // Second argument is i8**. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 321 | if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 322 | if (Pte1->getElementType()->isIntegerTy(8)) |
| 323 | return StringSwitch<InstructionClass>(F->getName()) |
| 324 | .Case("objc_moveWeak", IC_MoveWeak) |
| 325 | .Case("objc_copyWeak", IC_CopyWeak) |
| 326 | .Default(IC_CallOrUser); |
| 327 | } |
| 328 | |
| 329 | // Anything else. |
| 330 | return IC_CallOrUser; |
| 331 | } |
| 332 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 333 | /// \brief Determine what kind of construct V is. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 334 | static InstructionClass GetInstructionClass(const Value *V) { |
| 335 | if (const Instruction *I = dyn_cast<Instruction>(V)) { |
| 336 | // Any instruction other than bitcast and gep with a pointer operand have a |
| 337 | // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer |
| 338 | // to a subsequent use, rather than using it themselves, in this sense. |
| 339 | // As a short cut, several other opcodes are known to have no pointer |
| 340 | // operands of interest. And ret is never followed by a release, so it's |
| 341 | // not interesting to examine. |
| 342 | switch (I->getOpcode()) { |
| 343 | case Instruction::Call: { |
| 344 | const CallInst *CI = cast<CallInst>(I); |
| 345 | // Check for calls to special functions. |
| 346 | if (const Function *F = CI->getCalledFunction()) { |
| 347 | InstructionClass Class = GetFunctionClass(F); |
| 348 | if (Class != IC_CallOrUser) |
| 349 | return Class; |
| 350 | |
| 351 | // None of the intrinsic functions do objc_release. For intrinsics, the |
| 352 | // only question is whether or not they may be users. |
| 353 | switch (F->getIntrinsicID()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 354 | case Intrinsic::returnaddress: case Intrinsic::frameaddress: |
| 355 | case Intrinsic::stacksave: case Intrinsic::stackrestore: |
| 356 | case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 357 | case Intrinsic::objectsize: case Intrinsic::prefetch: |
| 358 | case Intrinsic::stackprotector: |
| 359 | case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64: |
| 360 | case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa: |
| 361 | case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext: |
| 362 | case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline: |
| 363 | case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: |
| 364 | case Intrinsic::invariant_start: case Intrinsic::invariant_end: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 365 | // Don't let dbg info affect our results. |
| 366 | case Intrinsic::dbg_declare: case Intrinsic::dbg_value: |
| 367 | // Short cut: Some intrinsics obviously don't use ObjC pointers. |
| 368 | return IC_None; |
| 369 | default: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 370 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 371 | } |
| 372 | } |
| 373 | return GetCallSiteClass(CI); |
| 374 | } |
| 375 | case Instruction::Invoke: |
| 376 | return GetCallSiteClass(cast<InvokeInst>(I)); |
| 377 | case Instruction::BitCast: |
| 378 | case Instruction::GetElementPtr: |
| 379 | case Instruction::Select: case Instruction::PHI: |
| 380 | case Instruction::Ret: case Instruction::Br: |
| 381 | case Instruction::Switch: case Instruction::IndirectBr: |
| 382 | case Instruction::Alloca: case Instruction::VAArg: |
| 383 | case Instruction::Add: case Instruction::FAdd: |
| 384 | case Instruction::Sub: case Instruction::FSub: |
| 385 | case Instruction::Mul: case Instruction::FMul: |
| 386 | case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv: |
| 387 | case Instruction::SRem: case Instruction::URem: case Instruction::FRem: |
| 388 | case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: |
| 389 | case Instruction::And: case Instruction::Or: case Instruction::Xor: |
| 390 | case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc: |
| 391 | case Instruction::IntToPtr: case Instruction::FCmp: |
| 392 | case Instruction::FPTrunc: case Instruction::FPExt: |
| 393 | case Instruction::FPToUI: case Instruction::FPToSI: |
| 394 | case Instruction::UIToFP: case Instruction::SIToFP: |
| 395 | case Instruction::InsertElement: case Instruction::ExtractElement: |
| 396 | case Instruction::ShuffleVector: |
| 397 | case Instruction::ExtractValue: |
| 398 | break; |
| 399 | case Instruction::ICmp: |
| 400 | // Comparing a pointer with null, or any other constant, isn't an |
| 401 | // interesting use, because we don't care what the pointer points to, or |
| 402 | // about the values of any other dynamic reference-counted pointers. |
| 403 | if (IsPotentialUse(I->getOperand(1))) |
| 404 | return IC_User; |
| 405 | break; |
| 406 | default: |
| 407 | // For anything else, check all the operands. |
Dan Gohman | 4b8e8ce | 2011-08-22 17:29:37 +0000 | [diff] [blame] | 408 | // Note that this includes both operands of a Store: while the first |
| 409 | // operand isn't actually being dereferenced, it is being stored to |
| 410 | // memory where we can no longer track who might read it and dereference |
| 411 | // it, so we have to consider it potentially used. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 412 | for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end(); |
| 413 | OI != OE; ++OI) |
| 414 | if (IsPotentialUse(*OI)) |
| 415 | return IC_User; |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // Otherwise, it's totally inert for ARC purposes. |
| 420 | return IC_None; |
| 421 | } |
| 422 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 423 | /// \brief Determine which objc runtime call instruction class V belongs to. |
| 424 | /// |
| 425 | /// This is similar to GetInstructionClass except that it only detects objc |
| 426 | /// runtime calls. This allows it to be faster. |
| 427 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 428 | static InstructionClass GetBasicInstructionClass(const Value *V) { |
| 429 | if (const CallInst *CI = dyn_cast<CallInst>(V)) { |
| 430 | if (const Function *F = CI->getCalledFunction()) |
| 431 | return GetFunctionClass(F); |
| 432 | // Otherwise, be conservative. |
| 433 | return IC_CallOrUser; |
| 434 | } |
| 435 | |
| 436 | // Otherwise, be conservative. |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 437 | return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 438 | } |
| 439 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 440 | /// \brief Test if the given class is objc_retain or equivalent. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 441 | static bool IsRetain(InstructionClass Class) { |
| 442 | return Class == IC_Retain || |
| 443 | Class == IC_RetainRV; |
| 444 | } |
| 445 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 446 | /// \brief Test if the given class is objc_autorelease or equivalent. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 447 | static bool IsAutorelease(InstructionClass Class) { |
| 448 | return Class == IC_Autorelease || |
| 449 | Class == IC_AutoreleaseRV; |
| 450 | } |
| 451 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 452 | /// \brief Test if the given class represents instructions which return their |
| 453 | /// argument verbatim. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 454 | static bool IsForwarding(InstructionClass Class) { |
| 455 | // objc_retainBlock technically doesn't always return its argument |
| 456 | // verbatim, but it doesn't matter for our purposes here. |
| 457 | return Class == IC_Retain || |
| 458 | Class == IC_RetainRV || |
| 459 | Class == IC_Autorelease || |
| 460 | Class == IC_AutoreleaseRV || |
| 461 | Class == IC_RetainBlock || |
| 462 | Class == IC_NoopCast; |
| 463 | } |
| 464 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 465 | /// \brief Test if the given class represents instructions which do nothing if |
| 466 | /// passed a null pointer. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 467 | static bool IsNoopOnNull(InstructionClass Class) { |
| 468 | return Class == IC_Retain || |
| 469 | Class == IC_RetainRV || |
| 470 | Class == IC_Release || |
| 471 | Class == IC_Autorelease || |
| 472 | Class == IC_AutoreleaseRV || |
| 473 | Class == IC_RetainBlock; |
| 474 | } |
| 475 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 476 | /// \brief Test if the given class represents instructions which are always safe |
| 477 | /// to mark with the "tail" keyword. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 478 | static bool IsAlwaysTail(InstructionClass Class) { |
| 479 | // IC_RetainBlock may be given a stack argument. |
| 480 | return Class == IC_Retain || |
| 481 | Class == IC_RetainRV || |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 482 | Class == IC_AutoreleaseRV; |
| 483 | } |
| 484 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 485 | /// \brief Test if the given class represents instructions which are never safe |
| 486 | /// to mark with the "tail" keyword. |
| 487 | static bool IsNeverTail(InstructionClass Class) { |
| 488 | /// It is never safe to tail call objc_autorelease since by tail calling |
| 489 | /// objc_autorelease, we also tail call -[NSObject autorelease] which supports |
| 490 | /// fast autoreleasing causing our object to be potentially reclaimed from the |
| 491 | /// autorelease pool which violates the semantics of __autoreleasing types in |
| 492 | /// ARC. |
| 493 | return Class == IC_Autorelease; |
| 494 | } |
| 495 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 496 | /// \brief Test if the given class represents instructions which are always safe |
| 497 | /// to mark with the nounwind attribute. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 498 | static bool IsNoThrow(InstructionClass Class) { |
Dan Gohman | fca43c2 | 2011-09-14 18:33:34 +0000 | [diff] [blame] | 499 | // objc_retainBlock is not nounwind because it calls user copy constructors |
| 500 | // which could theoretically throw. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 501 | return Class == IC_Retain || |
| 502 | Class == IC_RetainRV || |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 503 | Class == IC_Release || |
| 504 | Class == IC_Autorelease || |
| 505 | Class == IC_AutoreleaseRV || |
| 506 | Class == IC_AutoreleasepoolPush || |
| 507 | Class == IC_AutoreleasepoolPop; |
| 508 | } |
| 509 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 510 | /// \brief Erase the given instruction. |
| 511 | /// |
| 512 | /// Many ObjC calls return their argument verbatim, |
| 513 | /// so if it's such a call and the return value has users, replace them with the |
| 514 | /// argument value. |
| 515 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 516 | static void EraseInstruction(Instruction *CI) { |
| 517 | Value *OldArg = cast<CallInst>(CI)->getArgOperand(0); |
| 518 | |
| 519 | bool Unused = CI->use_empty(); |
| 520 | |
| 521 | if (!Unused) { |
| 522 | // Replace the return value with the argument. |
| 523 | assert(IsForwarding(GetBasicInstructionClass(CI)) && |
| 524 | "Can't delete non-forwarding instruction with users!"); |
| 525 | CI->replaceAllUsesWith(OldArg); |
| 526 | } |
| 527 | |
| 528 | CI->eraseFromParent(); |
| 529 | |
| 530 | if (Unused) |
| 531 | RecursivelyDeleteTriviallyDeadInstructions(OldArg); |
| 532 | } |
| 533 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 534 | /// \brief This is a wrapper around getUnderlyingObject which also knows how to |
| 535 | /// look through objc_retain and objc_autorelease calls, which we know to return |
| 536 | /// their argument verbatim. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 537 | static const Value *GetUnderlyingObjCPtr(const Value *V) { |
| 538 | for (;;) { |
| 539 | V = GetUnderlyingObject(V); |
| 540 | if (!IsForwarding(GetBasicInstructionClass(V))) |
| 541 | break; |
| 542 | V = cast<CallInst>(V)->getArgOperand(0); |
| 543 | } |
| 544 | |
| 545 | return V; |
| 546 | } |
| 547 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 548 | /// \brief This is a wrapper around Value::stripPointerCasts which also knows |
| 549 | /// how to look through objc_retain and objc_autorelease calls, which we know to |
| 550 | /// return their argument verbatim. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 551 | static const Value *StripPointerCastsAndObjCCalls(const Value *V) { |
| 552 | for (;;) { |
| 553 | V = V->stripPointerCasts(); |
| 554 | if (!IsForwarding(GetBasicInstructionClass(V))) |
| 555 | break; |
| 556 | V = cast<CallInst>(V)->getArgOperand(0); |
| 557 | } |
| 558 | return V; |
| 559 | } |
| 560 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 561 | /// \brief This is a wrapper around Value::stripPointerCasts which also knows |
| 562 | /// how to look through objc_retain and objc_autorelease calls, which we know to |
| 563 | /// return their argument verbatim. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 564 | static Value *StripPointerCastsAndObjCCalls(Value *V) { |
| 565 | for (;;) { |
| 566 | V = V->stripPointerCasts(); |
| 567 | if (!IsForwarding(GetBasicInstructionClass(V))) |
| 568 | break; |
| 569 | V = cast<CallInst>(V)->getArgOperand(0); |
| 570 | } |
| 571 | return V; |
| 572 | } |
| 573 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 574 | /// \brief Assuming the given instruction is one of the special calls such as |
| 575 | /// objc_retain or objc_release, return the argument value, stripped of no-op |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 576 | /// casts and forwarding calls. |
| 577 | static Value *GetObjCArg(Value *Inst) { |
| 578 | return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0)); |
| 579 | } |
| 580 | |
Michael Gottesman | 87db3575 | 2013-01-18 23:02:45 +0000 | [diff] [blame] | 581 | /// \brief Return true if this value refers to a distinct and identifiable |
| 582 | /// object. |
| 583 | /// |
| 584 | /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses |
| 585 | /// special knowledge of ObjC conventions. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 586 | static bool IsObjCIdentifiedObject(const Value *V) { |
| 587 | // Assume that call results and arguments have their own "provenance". |
| 588 | // Constants (including GlobalVariables) and Allocas are never |
| 589 | // reference-counted. |
| 590 | if (isa<CallInst>(V) || isa<InvokeInst>(V) || |
| 591 | isa<Argument>(V) || isa<Constant>(V) || |
| 592 | isa<AllocaInst>(V)) |
| 593 | return true; |
| 594 | |
| 595 | if (const LoadInst *LI = dyn_cast<LoadInst>(V)) { |
| 596 | const Value *Pointer = |
| 597 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()); |
| 598 | if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) { |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 599 | // A constant pointer can't be pointing to an object on the heap. It may |
| 600 | // be reference-counted, but it won't be deleted. |
| 601 | if (GV->isConstant()) |
| 602 | return true; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 603 | StringRef Name = GV->getName(); |
| 604 | // These special variables are known to hold values which are not |
| 605 | // reference-counted pointers. |
| 606 | if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") || |
| 607 | Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") || |
| 608 | Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") || |
| 609 | Name.startswith("\01L_OBJC_METH_VAR_NAME_") || |
| 610 | Name.startswith("\01l_objc_msgSend_fixup_")) |
| 611 | return true; |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | return false; |
| 616 | } |
| 617 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 618 | /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon |
| 619 | /// as it finds a value with multiple uses. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 620 | static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { |
| 621 | if (Arg->hasOneUse()) { |
| 622 | if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) |
| 623 | return FindSingleUseIdentifiedObject(BC->getOperand(0)); |
| 624 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) |
| 625 | if (GEP->hasAllZeroIndices()) |
| 626 | return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); |
| 627 | if (IsForwarding(GetBasicInstructionClass(Arg))) |
| 628 | return FindSingleUseIdentifiedObject( |
| 629 | cast<CallInst>(Arg)->getArgOperand(0)); |
| 630 | if (!IsObjCIdentifiedObject(Arg)) |
| 631 | return 0; |
| 632 | return Arg; |
| 633 | } |
| 634 | |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 635 | // If we found an identifiable object but it has multiple uses, but they are |
| 636 | // 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] | 637 | if (IsObjCIdentifiedObject(Arg)) { |
| 638 | for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); |
| 639 | UI != UE; ++UI) { |
| 640 | const User *U = *UI; |
| 641 | if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg) |
| 642 | return 0; |
| 643 | } |
| 644 | |
| 645 | return Arg; |
| 646 | } |
| 647 | |
| 648 | return 0; |
| 649 | } |
| 650 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 651 | /// \brief Test if the given module looks interesting to run ARC optimization |
| 652 | /// on. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 653 | static bool ModuleHasARC(const Module &M) { |
| 654 | return |
| 655 | M.getNamedValue("objc_retain") || |
| 656 | M.getNamedValue("objc_release") || |
| 657 | M.getNamedValue("objc_autorelease") || |
| 658 | M.getNamedValue("objc_retainAutoreleasedReturnValue") || |
| 659 | M.getNamedValue("objc_retainBlock") || |
| 660 | M.getNamedValue("objc_autoreleaseReturnValue") || |
| 661 | M.getNamedValue("objc_autoreleasePoolPush") || |
| 662 | M.getNamedValue("objc_loadWeakRetained") || |
| 663 | M.getNamedValue("objc_loadWeak") || |
| 664 | M.getNamedValue("objc_destroyWeak") || |
| 665 | M.getNamedValue("objc_storeWeak") || |
| 666 | M.getNamedValue("objc_initWeak") || |
| 667 | M.getNamedValue("objc_moveWeak") || |
| 668 | M.getNamedValue("objc_copyWeak") || |
| 669 | M.getNamedValue("objc_retainedObject") || |
| 670 | M.getNamedValue("objc_unretainedObject") || |
| 671 | M.getNamedValue("objc_unretainedPointer"); |
| 672 | } |
| 673 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 674 | /// \brief Test whether the given pointer, which is an Objective C block |
| 675 | /// pointer, does not "escape". |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 676 | /// |
| 677 | /// This differs from regular escape analysis in that a use as an |
| 678 | /// argument to a call is not considered an escape. |
| 679 | /// |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 680 | static bool DoesObjCBlockEscape(const Value *BlockPtr) { |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 681 | |
| 682 | DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n"); |
| 683 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 684 | // Walk the def-use chains. |
| 685 | SmallVector<const Value *, 4> Worklist; |
| 686 | Worklist.push_back(BlockPtr); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 687 | |
| 688 | // Ensure we do not visit any value twice. |
| 689 | SmallPtrSet<const Value *, 4> VisitedSet; |
| 690 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 691 | do { |
| 692 | const Value *V = Worklist.pop_back_val(); |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 693 | |
| 694 | DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n"); |
| 695 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 696 | for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); |
| 697 | UI != UE; ++UI) { |
| 698 | const User *UUser = *UI; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 699 | |
| 700 | DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n"); |
| 701 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 702 | // Special - Use by a call (callee or argument) is not considered |
| 703 | // to be an escape. |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 704 | switch (GetBasicInstructionClass(UUser)) { |
| 705 | case IC_StoreWeak: |
| 706 | case IC_InitWeak: |
| 707 | case IC_StoreStrong: |
| 708 | case IC_Autorelease: |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 709 | case IC_AutoreleaseRV: { |
| 710 | DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. " |
| 711 | "Block Escapes!\n"); |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 712 | // These special functions make copies of their pointer arguments. |
| 713 | return true; |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 714 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 715 | case IC_User: |
| 716 | case IC_None: |
| 717 | // Use by an instruction which copies the value is an escape if the |
| 718 | // result is an escape. |
| 719 | if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) || |
| 720 | isa<PHINode>(UUser) || isa<SelectInst>(UUser)) { |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 721 | |
Michael Gottesman | e9145d3 | 2013-01-14 19:18:39 +0000 | [diff] [blame] | 722 | if (!VisitedSet.insert(UUser)) { |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 723 | DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes " |
| 724 | "if result escapes. Adding to list.\n"); |
Michael Gottesman | f15c0bb | 2013-01-13 22:12:06 +0000 | [diff] [blame] | 725 | Worklist.push_back(UUser); |
| 726 | } else { |
| 727 | DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n"); |
| 728 | } |
Dan Gohman | e1e352a | 2012-04-13 18:28:58 +0000 | [diff] [blame] | 729 | continue; |
| 730 | } |
| 731 | // Use by a load is not an escape. |
| 732 | if (isa<LoadInst>(UUser)) |
| 733 | continue; |
| 734 | // Use by a store is not an escape if the use is the address. |
| 735 | if (const StoreInst *SI = dyn_cast<StoreInst>(UUser)) |
| 736 | if (V != SI->getValueOperand()) |
| 737 | continue; |
| 738 | break; |
| 739 | default: |
| 740 | // Regular calls and other stuff are not considered escapes. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 741 | continue; |
| 742 | } |
Dan Gohman | eb6e015 | 2012-02-13 22:57:02 +0000 | [diff] [blame] | 743 | // Otherwise, conservatively assume an escape. |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 744 | DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 745 | return true; |
| 746 | } |
| 747 | } while (!Worklist.empty()); |
| 748 | |
| 749 | // No escapes found. |
Michael Gottesman | 1a89fe5 | 2013-01-13 07:47:32 +0000 | [diff] [blame] | 750 | DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n"); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 751 | return false; |
| 752 | } |
| 753 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 754 | /// @} |
| 755 | /// |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 756 | /// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge. |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 757 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 758 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 759 | #include "llvm/Analysis/AliasAnalysis.h" |
| 760 | #include "llvm/Analysis/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 761 | #include "llvm/Pass.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 762 | |
| 763 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 764 | /// \brief This is a simple alias analysis implementation that uses knowledge |
| 765 | /// of ARC constructs to answer queries. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 766 | /// |
| 767 | /// TODO: This class could be generalized to know about other ObjC-specific |
| 768 | /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing |
| 769 | /// even though their offsets are dynamic. |
| 770 | class ObjCARCAliasAnalysis : public ImmutablePass, |
| 771 | public AliasAnalysis { |
| 772 | public: |
| 773 | static char ID; // Class identification, replacement for typeinfo |
| 774 | ObjCARCAliasAnalysis() : ImmutablePass(ID) { |
| 775 | initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry()); |
| 776 | } |
| 777 | |
| 778 | private: |
| 779 | virtual void initializePass() { |
| 780 | InitializeAliasAnalysis(this); |
| 781 | } |
| 782 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 783 | /// This method is used when a pass implements an analysis interface through |
| 784 | /// multiple inheritance. If needed, it should override this to adjust the |
| 785 | /// this pointer as needed for the specified pass info. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 786 | virtual void *getAdjustedAnalysisPointer(const void *PI) { |
| 787 | if (PI == &AliasAnalysis::ID) |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 788 | return static_cast<AliasAnalysis *>(this); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 789 | return this; |
| 790 | } |
| 791 | |
| 792 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 793 | virtual AliasResult alias(const Location &LocA, const Location &LocB); |
| 794 | virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal); |
| 795 | virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS); |
| 796 | virtual ModRefBehavior getModRefBehavior(const Function *F); |
| 797 | virtual ModRefResult getModRefInfo(ImmutableCallSite CS, |
| 798 | const Location &Loc); |
| 799 | virtual ModRefResult getModRefInfo(ImmutableCallSite CS1, |
| 800 | ImmutableCallSite CS2); |
| 801 | }; |
| 802 | } // End of anonymous namespace |
| 803 | |
| 804 | // Register this pass... |
| 805 | char ObjCARCAliasAnalysis::ID = 0; |
| 806 | INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa", |
| 807 | "ObjC-ARC-Based Alias Analysis", false, true, false) |
| 808 | |
| 809 | ImmutablePass *llvm::createObjCARCAliasAnalysisPass() { |
| 810 | return new ObjCARCAliasAnalysis(); |
| 811 | } |
| 812 | |
| 813 | void |
| 814 | ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { |
| 815 | AU.setPreservesAll(); |
| 816 | AliasAnalysis::getAnalysisUsage(AU); |
| 817 | } |
| 818 | |
| 819 | AliasAnalysis::AliasResult |
| 820 | ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) { |
| 821 | if (!EnableARCOpts) |
| 822 | return AliasAnalysis::alias(LocA, LocB); |
| 823 | |
| 824 | // First, strip off no-ops, including ObjC-specific no-ops, and try making a |
| 825 | // precise alias query. |
| 826 | const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr); |
| 827 | const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr); |
| 828 | AliasResult Result = |
| 829 | AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag), |
| 830 | Location(SB, LocB.Size, LocB.TBAATag)); |
| 831 | if (Result != MayAlias) |
| 832 | return Result; |
| 833 | |
| 834 | // If that failed, climb to the underlying object, including climbing through |
| 835 | // ObjC-specific no-ops, and try making an imprecise alias query. |
| 836 | const Value *UA = GetUnderlyingObjCPtr(SA); |
| 837 | const Value *UB = GetUnderlyingObjCPtr(SB); |
| 838 | if (UA != SA || UB != SB) { |
| 839 | Result = AliasAnalysis::alias(Location(UA), Location(UB)); |
| 840 | // We can't use MustAlias or PartialAlias results here because |
| 841 | // GetUnderlyingObjCPtr may return an offsetted pointer value. |
| 842 | if (Result == NoAlias) |
| 843 | return NoAlias; |
| 844 | } |
| 845 | |
| 846 | // If that failed, fail. We don't need to chain here, since that's covered |
| 847 | // by the earlier precise query. |
| 848 | return MayAlias; |
| 849 | } |
| 850 | |
| 851 | bool |
| 852 | ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc, |
| 853 | bool OrLocal) { |
| 854 | if (!EnableARCOpts) |
| 855 | return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); |
| 856 | |
| 857 | // First, strip off no-ops, including ObjC-specific no-ops, and try making |
| 858 | // a precise alias query. |
| 859 | const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr); |
| 860 | if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag), |
| 861 | OrLocal)) |
| 862 | return true; |
| 863 | |
| 864 | // If that failed, climb to the underlying object, including climbing through |
| 865 | // ObjC-specific no-ops, and try making an imprecise alias query. |
| 866 | const Value *U = GetUnderlyingObjCPtr(S); |
| 867 | if (U != S) |
| 868 | return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal); |
| 869 | |
| 870 | // If that failed, fail. We don't need to chain here, since that's covered |
| 871 | // by the earlier precise query. |
| 872 | return false; |
| 873 | } |
| 874 | |
| 875 | AliasAnalysis::ModRefBehavior |
| 876 | ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) { |
| 877 | // We have nothing to do. Just chain to the next AliasAnalysis. |
| 878 | return AliasAnalysis::getModRefBehavior(CS); |
| 879 | } |
| 880 | |
| 881 | AliasAnalysis::ModRefBehavior |
| 882 | ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) { |
| 883 | if (!EnableARCOpts) |
| 884 | return AliasAnalysis::getModRefBehavior(F); |
| 885 | |
| 886 | switch (GetFunctionClass(F)) { |
| 887 | case IC_NoopCast: |
| 888 | return DoesNotAccessMemory; |
| 889 | default: |
| 890 | break; |
| 891 | } |
| 892 | |
| 893 | return AliasAnalysis::getModRefBehavior(F); |
| 894 | } |
| 895 | |
| 896 | AliasAnalysis::ModRefResult |
| 897 | ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) { |
| 898 | if (!EnableARCOpts) |
| 899 | return AliasAnalysis::getModRefInfo(CS, Loc); |
| 900 | |
| 901 | switch (GetBasicInstructionClass(CS.getInstruction())) { |
| 902 | case IC_Retain: |
| 903 | case IC_RetainRV: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 904 | case IC_Autorelease: |
| 905 | case IC_AutoreleaseRV: |
| 906 | case IC_NoopCast: |
| 907 | case IC_AutoreleasepoolPush: |
| 908 | case IC_FusedRetainAutorelease: |
| 909 | case IC_FusedRetainAutoreleaseRV: |
| 910 | // These functions don't access any memory visible to the compiler. |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 911 | // Note that this doesn't include objc_retainBlock, because it updates |
Dan Gohman | d4b5e3a | 2011-09-14 18:13:00 +0000 | [diff] [blame] | 912 | // pointers when it copies block data. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 913 | return NoModRef; |
| 914 | default: |
| 915 | break; |
| 916 | } |
| 917 | |
| 918 | return AliasAnalysis::getModRefInfo(CS, Loc); |
| 919 | } |
| 920 | |
| 921 | AliasAnalysis::ModRefResult |
| 922 | ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1, |
| 923 | ImmutableCallSite CS2) { |
| 924 | // TODO: Theoretically we could check for dependencies between objc_* calls |
| 925 | // and OnlyAccessesArgumentPointees calls or other well-behaved calls. |
| 926 | return AliasAnalysis::getModRefInfo(CS1, CS2); |
| 927 | } |
| 928 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 929 | /// @} |
| 930 | /// |
| 931 | /// \defgroup ARCExpansion Early ARC Optimizations. |
| 932 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 933 | |
| 934 | #include "llvm/Support/InstIterator.h" |
| 935 | #include "llvm/Transforms/Scalar.h" |
| 936 | |
| 937 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 938 | /// \brief Early ARC transformations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 939 | class ObjCARCExpand : public FunctionPass { |
| 940 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 941 | virtual bool doInitialization(Module &M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 942 | virtual bool runOnFunction(Function &F); |
| 943 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 944 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 945 | bool Run; |
| 946 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 947 | public: |
| 948 | static char ID; |
| 949 | ObjCARCExpand() : FunctionPass(ID) { |
| 950 | initializeObjCARCExpandPass(*PassRegistry::getPassRegistry()); |
| 951 | } |
| 952 | }; |
| 953 | } |
| 954 | |
| 955 | char ObjCARCExpand::ID = 0; |
| 956 | INITIALIZE_PASS(ObjCARCExpand, |
| 957 | "objc-arc-expand", "ObjC ARC expansion", false, false) |
| 958 | |
| 959 | Pass *llvm::createObjCARCExpandPass() { |
| 960 | return new ObjCARCExpand(); |
| 961 | } |
| 962 | |
| 963 | void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const { |
| 964 | AU.setPreservesCFG(); |
| 965 | } |
| 966 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 967 | bool ObjCARCExpand::doInitialization(Module &M) { |
| 968 | Run = ModuleHasARC(M); |
| 969 | return false; |
| 970 | } |
| 971 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 972 | bool ObjCARCExpand::runOnFunction(Function &F) { |
| 973 | if (!EnableARCOpts) |
| 974 | return false; |
| 975 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 976 | // If nothing in the Module uses ARC, don't do anything. |
| 977 | if (!Run) |
| 978 | return false; |
| 979 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 980 | bool Changed = false; |
| 981 | |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 982 | DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n"); |
| 983 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 984 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) { |
| 985 | Instruction *Inst = &*I; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 986 | |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 987 | DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 988 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 989 | switch (GetBasicInstructionClass(Inst)) { |
| 990 | case IC_Retain: |
| 991 | case IC_RetainRV: |
| 992 | case IC_Autorelease: |
| 993 | case IC_AutoreleaseRV: |
| 994 | case IC_FusedRetainAutorelease: |
Michael Gottesman | c8a11df | 2013-01-01 16:05:54 +0000 | [diff] [blame] | 995 | case IC_FusedRetainAutoreleaseRV: { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 996 | // These calls return their argument verbatim, as a low-level |
| 997 | // optimization. However, this makes high-level optimizations |
| 998 | // harder. Undo any uses of this optimization that the front-end |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 999 | // emitted here. We'll redo them in the contract pass. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1000 | Changed = true; |
Michael Gottesman | c8a11df | 2013-01-01 16:05:54 +0000 | [diff] [blame] | 1001 | Value *Value = cast<CallInst>(Inst)->getArgOperand(0); |
| 1002 | DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n" |
| 1003 | " New = " << *Value << "\n"); |
| 1004 | Inst->replaceAllUsesWith(Value); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1005 | break; |
Michael Gottesman | c8a11df | 2013-01-01 16:05:54 +0000 | [diff] [blame] | 1006 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1007 | default: |
| 1008 | break; |
| 1009 | } |
| 1010 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1011 | |
Michael Gottesman | 50ae5b2 | 2013-01-03 08:09:27 +0000 | [diff] [blame] | 1012 | DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 1013 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1014 | return Changed; |
| 1015 | } |
| 1016 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1017 | /// @} |
| 1018 | /// |
| 1019 | /// \defgroup ARCAPElim ARC Autorelease Pool Elimination. |
| 1020 | /// @{ |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1021 | |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1022 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 1023 | #include "llvm/IR/Constants.h" |
Dan Gohman | 82041c2 | 2012-01-18 21:19:38 +0000 | [diff] [blame] | 1024 | |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1025 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1026 | /// \brief Autorelease pool elimination. |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1027 | class ObjCARCAPElim : public ModulePass { |
| 1028 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1029 | virtual bool runOnModule(Module &M); |
| 1030 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1031 | static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0); |
| 1032 | static bool OptimizeBB(BasicBlock *BB); |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1033 | |
| 1034 | public: |
| 1035 | static char ID; |
| 1036 | ObjCARCAPElim() : ModulePass(ID) { |
| 1037 | initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry()); |
| 1038 | } |
| 1039 | }; |
| 1040 | } |
| 1041 | |
| 1042 | char ObjCARCAPElim::ID = 0; |
| 1043 | INITIALIZE_PASS(ObjCARCAPElim, |
| 1044 | "objc-arc-apelim", |
| 1045 | "ObjC ARC autorelease pool elimination", |
| 1046 | false, false) |
| 1047 | |
| 1048 | Pass *llvm::createObjCARCAPElimPass() { |
| 1049 | return new ObjCARCAPElim(); |
| 1050 | } |
| 1051 | |
| 1052 | void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1053 | AU.setPreservesCFG(); |
| 1054 | } |
| 1055 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1056 | /// Interprocedurally determine if calls made by the given call site can |
| 1057 | /// possibly produce autoreleases. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1058 | bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) { |
| 1059 | if (const Function *Callee = CS.getCalledFunction()) { |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1060 | if (Callee->isDeclaration() || Callee->mayBeOverridden()) |
| 1061 | return true; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1062 | for (Function::const_iterator I = Callee->begin(), E = Callee->end(); |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1063 | I != E; ++I) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1064 | const BasicBlock *BB = I; |
| 1065 | for (BasicBlock::const_iterator J = BB->begin(), F = BB->end(); |
| 1066 | J != F; ++J) |
| 1067 | if (ImmutableCallSite JCS = ImmutableCallSite(J)) |
Dan Gohman | 8f12fae | 2012-01-18 21:24:45 +0000 | [diff] [blame] | 1068 | // This recursion depth limit is arbitrary. It's just great |
| 1069 | // enough to cover known interesting testcases. |
| 1070 | if (Depth < 3 && |
| 1071 | !JCS.onlyReadsMemory() && |
| 1072 | MayAutorelease(JCS, Depth + 1)) |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1073 | return true; |
| 1074 | } |
| 1075 | return false; |
| 1076 | } |
| 1077 | |
| 1078 | return true; |
| 1079 | } |
| 1080 | |
| 1081 | bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) { |
| 1082 | bool Changed = false; |
| 1083 | |
| 1084 | Instruction *Push = 0; |
| 1085 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
| 1086 | Instruction *Inst = I++; |
| 1087 | switch (GetBasicInstructionClass(Inst)) { |
| 1088 | case IC_AutoreleasepoolPush: |
| 1089 | Push = Inst; |
| 1090 | break; |
| 1091 | case IC_AutoreleasepoolPop: |
| 1092 | // If this pop matches a push and nothing in between can autorelease, |
| 1093 | // zap the pair. |
| 1094 | if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) { |
| 1095 | Changed = true; |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1096 | DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop " |
| 1097 | "autorelease pair:\n" |
| 1098 | " Pop: " << *Inst << "\n" |
Michael Gottesman | ef682c5 | 2013-01-03 08:09:17 +0000 | [diff] [blame] | 1099 | << " Push: " << *Push << "\n"); |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1100 | Inst->eraseFromParent(); |
| 1101 | Push->eraseFromParent(); |
| 1102 | } |
| 1103 | Push = 0; |
| 1104 | break; |
| 1105 | case IC_CallOrUser: |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1106 | if (MayAutorelease(ImmutableCallSite(Inst))) |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1107 | Push = 0; |
| 1108 | break; |
| 1109 | default: |
| 1110 | break; |
| 1111 | } |
| 1112 | } |
| 1113 | |
| 1114 | return Changed; |
| 1115 | } |
| 1116 | |
| 1117 | bool ObjCARCAPElim::runOnModule(Module &M) { |
| 1118 | if (!EnableARCOpts) |
| 1119 | return false; |
| 1120 | |
| 1121 | // If nothing in the Module uses ARC, don't do anything. |
| 1122 | if (!ModuleHasARC(M)) |
| 1123 | return false; |
| 1124 | |
Dan Gohman | 82041c2 | 2012-01-18 21:19:38 +0000 | [diff] [blame] | 1125 | // Find the llvm.global_ctors variable, as the first step in |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 1126 | // identifying the global constructors. In theory, unnecessary autorelease |
| 1127 | // pools could occur anywhere, but in practice it's pretty rare. Global |
| 1128 | // ctors are a place where autorelease pools get inserted automatically, |
| 1129 | // so it's pretty common for them to be unnecessary, and it's pretty |
| 1130 | // profitable to eliminate them. |
Dan Gohman | 82041c2 | 2012-01-18 21:19:38 +0000 | [diff] [blame] | 1131 | GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors"); |
| 1132 | if (!GV) |
| 1133 | return false; |
| 1134 | |
| 1135 | assert(GV->hasDefinitiveInitializer() && |
| 1136 | "llvm.global_ctors is uncooperative!"); |
| 1137 | |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1138 | bool Changed = false; |
| 1139 | |
Dan Gohman | 82041c2 | 2012-01-18 21:19:38 +0000 | [diff] [blame] | 1140 | // Dig the constructor functions out of GV's initializer. |
| 1141 | ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); |
| 1142 | for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end(); |
| 1143 | OI != OE; ++OI) { |
| 1144 | Value *Op = *OI; |
| 1145 | // llvm.global_ctors is an array of pairs where the second members |
| 1146 | // are constructor functions. |
Dan Gohman | 22fbe8d | 2012-04-18 22:24:33 +0000 | [diff] [blame] | 1147 | Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1)); |
| 1148 | // If the user used a constructor function with the wrong signature and |
| 1149 | // it got bitcasted or whatever, look the other way. |
| 1150 | if (!F) |
| 1151 | continue; |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1152 | // Only look at function definitions. |
| 1153 | if (F->isDeclaration()) |
| 1154 | continue; |
Dan Gohman | e7a243f | 2012-01-17 20:52:24 +0000 | [diff] [blame] | 1155 | // Only look at functions with one basic block. |
| 1156 | if (llvm::next(F->begin()) != F->end()) |
| 1157 | continue; |
| 1158 | // Ok, a single-block constructor function definition. Try to optimize it. |
| 1159 | Changed |= OptimizeBB(F->begin()); |
| 1160 | } |
| 1161 | |
| 1162 | return Changed; |
| 1163 | } |
| 1164 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1165 | /// @} |
| 1166 | /// |
| 1167 | /// \defgroup ARCOpt ARC Optimization. |
| 1168 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1169 | |
| 1170 | // TODO: On code like this: |
| 1171 | // |
| 1172 | // objc_retain(%x) |
| 1173 | // stuff_that_cannot_release() |
| 1174 | // objc_autorelease(%x) |
| 1175 | // stuff_that_cannot_release() |
| 1176 | // objc_retain(%x) |
| 1177 | // stuff_that_cannot_release() |
| 1178 | // objc_autorelease(%x) |
| 1179 | // |
| 1180 | // The second retain and autorelease can be deleted. |
| 1181 | |
| 1182 | // TODO: It should be possible to delete |
| 1183 | // objc_autoreleasePoolPush and objc_autoreleasePoolPop |
| 1184 | // pairs if nothing is actually autoreleased between them. Also, autorelease |
| 1185 | // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code |
| 1186 | // after inlining) can be turned into plain release calls. |
| 1187 | |
| 1188 | // TODO: Critical-edge splitting. If the optimial insertion point is |
| 1189 | // a critical edge, the current algorithm has to fail, because it doesn't |
| 1190 | // know how to split edges. It should be possible to make the optimizer |
| 1191 | // think in terms of edges, rather than blocks, and then split critical |
| 1192 | // edges on demand. |
| 1193 | |
| 1194 | // TODO: OptimizeSequences could generalized to be Interprocedural. |
| 1195 | |
| 1196 | // TODO: Recognize that a bunch of other objc runtime calls have |
| 1197 | // non-escaping arguments and non-releasing arguments, and may be |
| 1198 | // non-autoreleasing. |
| 1199 | |
| 1200 | // TODO: Sink autorelease calls as far as possible. Unfortunately we |
| 1201 | // usually can't sink them past other calls, which would be the main |
| 1202 | // case where it would be useful. |
| 1203 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 1204 | // TODO: The pointer returned from objc_loadWeakRetained is retained. |
| 1205 | |
| 1206 | // TODO: Delete release+retain pairs (rare). |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 1207 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 1208 | #include "llvm/ADT/SmallPtrSet.h" |
| 1209 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 1210 | #include "llvm/IR/LLVMContext.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1211 | #include "llvm/Support/CFG.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1212 | |
| 1213 | STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); |
| 1214 | STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); |
| 1215 | STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); |
| 1216 | STATISTIC(NumRets, "Number of return value forwarding " |
| 1217 | "retain+autoreleaes eliminated"); |
| 1218 | STATISTIC(NumRRs, "Number of retain+release paths eliminated"); |
| 1219 | STATISTIC(NumPeeps, "Number of calls peephole-optimized"); |
| 1220 | |
| 1221 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1222 | /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same |
| 1223 | /// techniques, except it uses special ObjC-specific reasoning about pointer |
| 1224 | /// relationships. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1225 | class ProvenanceAnalysis { |
| 1226 | AliasAnalysis *AA; |
| 1227 | |
| 1228 | typedef std::pair<const Value *, const Value *> ValuePairTy; |
| 1229 | typedef DenseMap<ValuePairTy, bool> CachedResultsTy; |
| 1230 | CachedResultsTy CachedResults; |
| 1231 | |
| 1232 | bool relatedCheck(const Value *A, const Value *B); |
| 1233 | bool relatedSelect(const SelectInst *A, const Value *B); |
| 1234 | bool relatedPHI(const PHINode *A, const Value *B); |
| 1235 | |
Craig Topper | b1d83e8 | 2012-09-18 02:01:41 +0000 | [diff] [blame] | 1236 | void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION; |
| 1237 | ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1238 | |
| 1239 | public: |
| 1240 | ProvenanceAnalysis() {} |
| 1241 | |
| 1242 | void setAA(AliasAnalysis *aa) { AA = aa; } |
| 1243 | |
| 1244 | AliasAnalysis *getAA() const { return AA; } |
| 1245 | |
| 1246 | bool related(const Value *A, const Value *B); |
| 1247 | |
| 1248 | void clear() { |
| 1249 | CachedResults.clear(); |
| 1250 | } |
| 1251 | }; |
| 1252 | } |
| 1253 | |
| 1254 | bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) { |
| 1255 | // If the values are Selects with the same condition, we can do a more precise |
| 1256 | // check: just check for relations between the values on corresponding arms. |
| 1257 | if (const SelectInst *SB = dyn_cast<SelectInst>(B)) |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1258 | if (A->getCondition() == SB->getCondition()) |
| 1259 | return related(A->getTrueValue(), SB->getTrueValue()) || |
| 1260 | related(A->getFalseValue(), SB->getFalseValue()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1261 | |
| 1262 | // Check both arms of the Select node individually. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1263 | return related(A->getTrueValue(), B) || |
| 1264 | related(A->getFalseValue(), B); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1265 | } |
| 1266 | |
| 1267 | bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) { |
| 1268 | // If the values are PHIs in the same block, we can do a more precise as well |
| 1269 | // as efficient check: just check for relations between the values on |
| 1270 | // corresponding edges. |
| 1271 | if (const PHINode *PNB = dyn_cast<PHINode>(B)) |
| 1272 | if (PNB->getParent() == A->getParent()) { |
| 1273 | for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) |
| 1274 | if (related(A->getIncomingValue(i), |
| 1275 | PNB->getIncomingValueForBlock(A->getIncomingBlock(i)))) |
| 1276 | return true; |
| 1277 | return false; |
| 1278 | } |
| 1279 | |
| 1280 | // Check each unique source of the PHI node against B. |
| 1281 | SmallPtrSet<const Value *, 4> UniqueSrc; |
| 1282 | for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) { |
| 1283 | const Value *PV1 = A->getIncomingValue(i); |
| 1284 | if (UniqueSrc.insert(PV1) && related(PV1, B)) |
| 1285 | return true; |
| 1286 | } |
| 1287 | |
| 1288 | // All of the arms checked out. |
| 1289 | return false; |
| 1290 | } |
| 1291 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1292 | /// Test if the value of P, or any value covered by its provenance, is ever |
| 1293 | /// stored within the function (not counting callees). |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1294 | static bool isStoredObjCPointer(const Value *P) { |
| 1295 | SmallPtrSet<const Value *, 8> Visited; |
| 1296 | SmallVector<const Value *, 8> Worklist; |
| 1297 | Worklist.push_back(P); |
| 1298 | Visited.insert(P); |
| 1299 | do { |
| 1300 | P = Worklist.pop_back_val(); |
| 1301 | for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end(); |
| 1302 | UI != UE; ++UI) { |
| 1303 | const User *Ur = *UI; |
| 1304 | if (isa<StoreInst>(Ur)) { |
| 1305 | if (UI.getOperandNo() == 0) |
| 1306 | // The pointer is stored. |
| 1307 | return true; |
| 1308 | // The pointed is stored through. |
| 1309 | continue; |
| 1310 | } |
| 1311 | if (isa<CallInst>(Ur)) |
| 1312 | // The pointer is passed as an argument, ignore this. |
| 1313 | continue; |
| 1314 | if (isa<PtrToIntInst>(P)) |
| 1315 | // Assume the worst. |
| 1316 | return true; |
| 1317 | if (Visited.insert(Ur)) |
| 1318 | Worklist.push_back(Ur); |
| 1319 | } |
| 1320 | } while (!Worklist.empty()); |
| 1321 | |
| 1322 | // Everything checked out. |
| 1323 | return false; |
| 1324 | } |
| 1325 | |
| 1326 | bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) { |
| 1327 | // Skip past provenance pass-throughs. |
| 1328 | A = GetUnderlyingObjCPtr(A); |
| 1329 | B = GetUnderlyingObjCPtr(B); |
| 1330 | |
| 1331 | // Quick check. |
| 1332 | if (A == B) |
| 1333 | return true; |
| 1334 | |
| 1335 | // Ask regular AliasAnalysis, for a first approximation. |
| 1336 | switch (AA->alias(A, B)) { |
| 1337 | case AliasAnalysis::NoAlias: |
| 1338 | return false; |
| 1339 | case AliasAnalysis::MustAlias: |
| 1340 | case AliasAnalysis::PartialAlias: |
| 1341 | return true; |
| 1342 | case AliasAnalysis::MayAlias: |
| 1343 | break; |
| 1344 | } |
| 1345 | |
| 1346 | bool AIsIdentified = IsObjCIdentifiedObject(A); |
| 1347 | bool BIsIdentified = IsObjCIdentifiedObject(B); |
| 1348 | |
| 1349 | // An ObjC-Identified object can't alias a load if it is never locally stored. |
| 1350 | if (AIsIdentified) { |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1351 | // Check for an obvious escape. |
| 1352 | if (isa<LoadInst>(B)) |
| 1353 | return isStoredObjCPointer(A); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1354 | if (BIsIdentified) { |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1355 | // Check for an obvious escape. |
| 1356 | if (isa<LoadInst>(A)) |
| 1357 | return isStoredObjCPointer(B); |
| 1358 | // Both pointers are identified and escapes aren't an evident problem. |
| 1359 | return false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1360 | } |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1361 | } else if (BIsIdentified) { |
| 1362 | // Check for an obvious escape. |
| 1363 | if (isa<LoadInst>(A)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1364 | return isStoredObjCPointer(B); |
| 1365 | } |
| 1366 | |
| 1367 | // Special handling for PHI and Select. |
| 1368 | if (const PHINode *PN = dyn_cast<PHINode>(A)) |
| 1369 | return relatedPHI(PN, B); |
| 1370 | if (const PHINode *PN = dyn_cast<PHINode>(B)) |
| 1371 | return relatedPHI(PN, A); |
| 1372 | if (const SelectInst *S = dyn_cast<SelectInst>(A)) |
| 1373 | return relatedSelect(S, B); |
| 1374 | if (const SelectInst *S = dyn_cast<SelectInst>(B)) |
| 1375 | return relatedSelect(S, A); |
| 1376 | |
| 1377 | // Conservative. |
| 1378 | return true; |
| 1379 | } |
| 1380 | |
| 1381 | bool ProvenanceAnalysis::related(const Value *A, const Value *B) { |
| 1382 | // Begin by inserting a conservative value into the map. If the insertion |
| 1383 | // fails, we have the answer already. If it succeeds, leave it there until we |
| 1384 | // compute the real answer to guard against recursive queries. |
| 1385 | if (A > B) std::swap(A, B); |
| 1386 | std::pair<CachedResultsTy::iterator, bool> Pair = |
| 1387 | CachedResults.insert(std::make_pair(ValuePairTy(A, B), true)); |
| 1388 | if (!Pair.second) |
| 1389 | return Pair.first->second; |
| 1390 | |
| 1391 | bool Result = relatedCheck(A, B); |
| 1392 | CachedResults[ValuePairTy(A, B)] = Result; |
| 1393 | return Result; |
| 1394 | } |
| 1395 | |
| 1396 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1397 | /// \enum Sequence |
| 1398 | /// |
| 1399 | /// \brief A sequence of states that a pointer may go through in which an |
| 1400 | /// objc_retain and objc_release are actually needed. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1401 | enum Sequence { |
| 1402 | S_None, |
| 1403 | S_Retain, ///< objc_retain(x) |
| 1404 | S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement |
| 1405 | S_Use, ///< any use of x |
| 1406 | S_Stop, ///< like S_Release, but code motion is stopped |
| 1407 | S_Release, ///< objc_release(x) |
| 1408 | S_MovableRelease ///< objc_release(x), !clang.imprecise_release |
| 1409 | }; |
| 1410 | } |
| 1411 | |
| 1412 | static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) { |
| 1413 | // The easy cases. |
| 1414 | if (A == B) |
| 1415 | return A; |
| 1416 | if (A == S_None || B == S_None) |
| 1417 | return S_None; |
| 1418 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1419 | if (A > B) std::swap(A, B); |
| 1420 | if (TopDown) { |
| 1421 | // Choose the side which is further along in the sequence. |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1422 | if ((A == S_Retain || A == S_CanRelease) && |
| 1423 | (B == S_CanRelease || B == S_Use)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1424 | return B; |
| 1425 | } else { |
| 1426 | // Choose the side which is further along in the sequence. |
| 1427 | if ((A == S_Use || A == S_CanRelease) && |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1428 | (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1429 | return A; |
| 1430 | // If both sides are releases, choose the more conservative one. |
| 1431 | if (A == S_Stop && (B == S_Release || B == S_MovableRelease)) |
| 1432 | return A; |
| 1433 | if (A == S_Release && B == S_MovableRelease) |
| 1434 | return A; |
| 1435 | } |
| 1436 | |
| 1437 | return S_None; |
| 1438 | } |
| 1439 | |
| 1440 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1441 | /// \brief Unidirectional information about either a |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1442 | /// retain-decrement-use-release sequence or release-use-decrement-retain |
| 1443 | /// reverese sequence. |
| 1444 | struct RRInfo { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1445 | /// After an objc_retain, the reference count of the referenced |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 1446 | /// object is known to be positive. Similarly, before an objc_release, the |
| 1447 | /// reference count of the referenced object is known to be positive. If |
| 1448 | /// there are retain-release pairs in code regions where the retain count |
| 1449 | /// is known to be positive, they can be eliminated, regardless of any side |
| 1450 | /// effects between them. |
| 1451 | /// |
| 1452 | /// Also, a retain+release pair nested within another retain+release |
| 1453 | /// pair all on the known same pointer value can be eliminated, regardless |
| 1454 | /// of any intervening side effects. |
| 1455 | /// |
| 1456 | /// KnownSafe is true when either of these conditions is satisfied. |
| 1457 | bool KnownSafe; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1458 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1459 | /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain |
| 1460 | /// calls). |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1461 | bool IsRetainBlock; |
| 1462 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1463 | /// 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] | 1464 | bool IsTailCallRelease; |
| 1465 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1466 | /// If the Calls are objc_release calls and they all have a |
| 1467 | /// clang.imprecise_release tag, this is the metadata tag. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1468 | MDNode *ReleaseMetadata; |
| 1469 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1470 | /// For a top-down sequence, the set of objc_retains or |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1471 | /// objc_retainBlocks. For bottom-up, the set of objc_releases. |
| 1472 | SmallPtrSet<Instruction *, 2> Calls; |
| 1473 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1474 | /// The set of optimal insert positions for moving calls in the opposite |
| 1475 | /// sequence. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1476 | SmallPtrSet<Instruction *, 2> ReverseInsertPts; |
| 1477 | |
| 1478 | RRInfo() : |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1479 | KnownSafe(false), IsRetainBlock(false), |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1480 | IsTailCallRelease(false), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1481 | ReleaseMetadata(0) {} |
| 1482 | |
| 1483 | void clear(); |
| 1484 | }; |
| 1485 | } |
| 1486 | |
| 1487 | void RRInfo::clear() { |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 1488 | KnownSafe = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1489 | IsRetainBlock = false; |
| 1490 | IsTailCallRelease = false; |
| 1491 | ReleaseMetadata = 0; |
| 1492 | Calls.clear(); |
| 1493 | ReverseInsertPts.clear(); |
| 1494 | } |
| 1495 | |
| 1496 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1497 | /// \brief This class summarizes several per-pointer runtime properties which |
| 1498 | /// are propogated through the flow graph. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1499 | class PtrState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1500 | /// True if the reference count is known to be incremented. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1501 | bool KnownPositiveRefCount; |
| 1502 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1503 | /// True of we've seen an opportunity for partial RR elimination, such as |
| 1504 | /// 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] | 1505 | bool Partial; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1506 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1507 | /// The current position in the sequence. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1508 | Sequence Seq : 8; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1509 | |
| 1510 | public: |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1511 | /// Unidirectional information about the current sequence. |
| 1512 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1513 | /// TODO: Encapsulate this better. |
| 1514 | RRInfo RRI; |
| 1515 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 1516 | PtrState() : KnownPositiveRefCount(false), Partial(false), |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1517 | Seq(S_None) {} |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1518 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1519 | void SetKnownPositiveRefCount() { |
| 1520 | KnownPositiveRefCount = true; |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1521 | } |
| 1522 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1523 | void ClearRefCount() { |
| 1524 | KnownPositiveRefCount = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1525 | } |
| 1526 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1527 | bool IsKnownIncremented() const { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1528 | return KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1529 | } |
| 1530 | |
| 1531 | void SetSeq(Sequence NewSeq) { |
| 1532 | Seq = NewSeq; |
| 1533 | } |
| 1534 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1535 | Sequence GetSeq() const { |
| 1536 | return Seq; |
| 1537 | } |
| 1538 | |
| 1539 | void ClearSequenceProgress() { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1540 | ResetSequenceProgress(S_None); |
| 1541 | } |
| 1542 | |
| 1543 | void ResetSequenceProgress(Sequence NewSeq) { |
| 1544 | Seq = NewSeq; |
| 1545 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1546 | RRI.clear(); |
| 1547 | } |
| 1548 | |
| 1549 | void Merge(const PtrState &Other, bool TopDown); |
| 1550 | }; |
| 1551 | } |
| 1552 | |
| 1553 | void |
| 1554 | PtrState::Merge(const PtrState &Other, bool TopDown) { |
| 1555 | Seq = MergeSeqs(Seq, Other.Seq, TopDown); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1556 | KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1557 | |
| 1558 | // We can't merge a plain objc_retain with an objc_retainBlock. |
| 1559 | if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock) |
| 1560 | Seq = S_None; |
| 1561 | |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 1562 | // If we're not in a sequence (anymore), drop all associated state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1563 | if (Seq == S_None) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1564 | Partial = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1565 | RRI.clear(); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1566 | } else if (Partial || Other.Partial) { |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 1567 | // If we're doing a merge on a path that's previously seen a partial |
| 1568 | // merge, conservatively drop the sequence, to avoid doing partial |
| 1569 | // RR elimination. If the branch predicates for the two merge differ, |
| 1570 | // mixing them is unsafe. |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1571 | ClearSequenceProgress(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1572 | } else { |
| 1573 | // Conservatively merge the ReleaseMetadata information. |
| 1574 | if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata) |
| 1575 | RRI.ReleaseMetadata = 0; |
| 1576 | |
Dan Gohman | b389401 | 2011-08-19 00:26:36 +0000 | [diff] [blame] | 1577 | RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1578 | RRI.IsTailCallRelease = RRI.IsTailCallRelease && |
| 1579 | Other.RRI.IsTailCallRelease; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1580 | RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end()); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 1581 | |
| 1582 | // Merge the insert point sets. If there are any differences, |
| 1583 | // that makes this a partial merge. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1584 | Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size(); |
Dan Gohman | 1736c14 | 2011-10-17 18:48:25 +0000 | [diff] [blame] | 1585 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 1586 | I = Other.RRI.ReverseInsertPts.begin(), |
| 1587 | E = Other.RRI.ReverseInsertPts.end(); I != E; ++I) |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 1588 | Partial |= RRI.ReverseInsertPts.insert(*I); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1589 | } |
| 1590 | } |
| 1591 | |
| 1592 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1593 | /// \brief Per-BasicBlock state. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1594 | class BBState { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1595 | /// The number of unique control paths from the entry which can reach this |
| 1596 | /// block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1597 | unsigned TopDownPathCount; |
| 1598 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1599 | /// The number of unique control paths to exits from this block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1600 | unsigned BottomUpPathCount; |
| 1601 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1602 | /// A type for PerPtrTopDown and PerPtrBottomUp. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1603 | typedef MapVector<const Value *, PtrState> MapTy; |
| 1604 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1605 | /// The top-down traversal uses this to record information known about a |
| 1606 | /// pointer at the bottom of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1607 | MapTy PerPtrTopDown; |
| 1608 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1609 | /// The bottom-up traversal uses this to record information known about a |
| 1610 | /// pointer at the top of each block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1611 | MapTy PerPtrBottomUp; |
| 1612 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1613 | /// Effective predecessors of the current block ignoring ignorable edges and |
| 1614 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1615 | SmallVector<BasicBlock *, 2> Preds; |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1616 | /// Effective successors of the current block ignoring ignorable edges and |
| 1617 | /// ignored backedges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1618 | SmallVector<BasicBlock *, 2> Succs; |
| 1619 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1620 | public: |
| 1621 | BBState() : TopDownPathCount(0), BottomUpPathCount(0) {} |
| 1622 | |
| 1623 | typedef MapTy::iterator ptr_iterator; |
| 1624 | typedef MapTy::const_iterator ptr_const_iterator; |
| 1625 | |
| 1626 | ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } |
| 1627 | ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } |
| 1628 | ptr_const_iterator top_down_ptr_begin() const { |
| 1629 | return PerPtrTopDown.begin(); |
| 1630 | } |
| 1631 | ptr_const_iterator top_down_ptr_end() const { |
| 1632 | return PerPtrTopDown.end(); |
| 1633 | } |
| 1634 | |
| 1635 | ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); } |
| 1636 | ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } |
| 1637 | ptr_const_iterator bottom_up_ptr_begin() const { |
| 1638 | return PerPtrBottomUp.begin(); |
| 1639 | } |
| 1640 | ptr_const_iterator bottom_up_ptr_end() const { |
| 1641 | return PerPtrBottomUp.end(); |
| 1642 | } |
| 1643 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1644 | /// Mark this block as being an entry block, which has one path from the |
| 1645 | /// entry by definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1646 | void SetAsEntry() { TopDownPathCount = 1; } |
| 1647 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1648 | /// Mark this block as being an exit block, which has one path to an exit by |
| 1649 | /// definition. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1650 | void SetAsExit() { BottomUpPathCount = 1; } |
| 1651 | |
| 1652 | PtrState &getPtrTopDownState(const Value *Arg) { |
| 1653 | return PerPtrTopDown[Arg]; |
| 1654 | } |
| 1655 | |
| 1656 | PtrState &getPtrBottomUpState(const Value *Arg) { |
| 1657 | return PerPtrBottomUp[Arg]; |
| 1658 | } |
| 1659 | |
| 1660 | void clearBottomUpPointers() { |
Evan Cheng | e4df6a2 | 2011-08-04 18:40:26 +0000 | [diff] [blame] | 1661 | PerPtrBottomUp.clear(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1662 | } |
| 1663 | |
| 1664 | void clearTopDownPointers() { |
| 1665 | PerPtrTopDown.clear(); |
| 1666 | } |
| 1667 | |
| 1668 | void InitFromPred(const BBState &Other); |
| 1669 | void InitFromSucc(const BBState &Other); |
| 1670 | void MergePred(const BBState &Other); |
| 1671 | void MergeSucc(const BBState &Other); |
| 1672 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1673 | /// Return the number of possible unique paths from an entry to an exit |
| 1674 | /// which pass through this block. This is only valid after both the |
| 1675 | /// top-down and bottom-up traversals are complete. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1676 | unsigned GetAllPathCount() const { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1677 | assert(TopDownPathCount != 0); |
| 1678 | assert(BottomUpPathCount != 0); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1679 | return TopDownPathCount * BottomUpPathCount; |
| 1680 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 1681 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1682 | // Specialized CFG utilities. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 1683 | typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 1684 | edge_iterator pred_begin() { return Preds.begin(); } |
| 1685 | edge_iterator pred_end() { return Preds.end(); } |
| 1686 | edge_iterator succ_begin() { return Succs.begin(); } |
| 1687 | edge_iterator succ_end() { return Succs.end(); } |
| 1688 | |
| 1689 | void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } |
| 1690 | void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } |
| 1691 | |
| 1692 | bool isExit() const { return Succs.empty(); } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1693 | }; |
| 1694 | } |
| 1695 | |
| 1696 | void BBState::InitFromPred(const BBState &Other) { |
| 1697 | PerPtrTopDown = Other.PerPtrTopDown; |
| 1698 | TopDownPathCount = Other.TopDownPathCount; |
| 1699 | } |
| 1700 | |
| 1701 | void BBState::InitFromSucc(const BBState &Other) { |
| 1702 | PerPtrBottomUp = Other.PerPtrBottomUp; |
| 1703 | BottomUpPathCount = Other.BottomUpPathCount; |
| 1704 | } |
| 1705 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1706 | /// The top-down traversal uses this to merge information about predecessors to |
| 1707 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1708 | void BBState::MergePred(const BBState &Other) { |
| 1709 | // Other.TopDownPathCount can be 0, in which case it is either dead or a |
| 1710 | // loop backedge. Loop backedges are special. |
| 1711 | TopDownPathCount += Other.TopDownPathCount; |
| 1712 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1713 | // Check for overflow. If we have overflow, fall back to conservative |
| 1714 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 1715 | if (TopDownPathCount < Other.TopDownPathCount) { |
| 1716 | clearTopDownPointers(); |
| 1717 | return; |
| 1718 | } |
| 1719 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1720 | // For each entry in the other set, if our set has an entry with the same key, |
| 1721 | // merge the entries. Otherwise, copy the entry and merge it with an empty |
| 1722 | // entry. |
| 1723 | for (ptr_const_iterator MI = Other.top_down_ptr_begin(), |
| 1724 | ME = Other.top_down_ptr_end(); MI != ME; ++MI) { |
| 1725 | std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI); |
| 1726 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 1727 | /*TopDown=*/true); |
| 1728 | } |
| 1729 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 1730 | // 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] | 1731 | // same key, force it to merge with an empty entry. |
| 1732 | for (ptr_iterator MI = top_down_ptr_begin(), |
| 1733 | ME = top_down_ptr_end(); MI != ME; ++MI) |
| 1734 | if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) |
| 1735 | MI->second.Merge(PtrState(), /*TopDown=*/true); |
| 1736 | } |
| 1737 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1738 | /// The bottom-up traversal uses this to merge information about successors to |
| 1739 | /// form the initial state for a new block. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1740 | void BBState::MergeSucc(const BBState &Other) { |
| 1741 | // Other.BottomUpPathCount can be 0, in which case it is either dead or a |
| 1742 | // loop backedge. Loop backedges are special. |
| 1743 | BottomUpPathCount += Other.BottomUpPathCount; |
| 1744 | |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 1745 | // Check for overflow. If we have overflow, fall back to conservative |
| 1746 | // behavior. |
Dan Gohman | 7c84dad | 2012-09-12 20:45:17 +0000 | [diff] [blame] | 1747 | if (BottomUpPathCount < Other.BottomUpPathCount) { |
| 1748 | clearBottomUpPointers(); |
| 1749 | return; |
| 1750 | } |
| 1751 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1752 | // For each entry in the other set, if our set has an entry with the |
| 1753 | // same key, merge the entries. Otherwise, copy the entry and merge |
| 1754 | // it with an empty entry. |
| 1755 | for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(), |
| 1756 | ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 1757 | std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI); |
| 1758 | Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, |
| 1759 | /*TopDown=*/false); |
| 1760 | } |
| 1761 | |
Dan Gohman | 7e315fc3 | 2011-08-11 21:06:32 +0000 | [diff] [blame] | 1762 | // 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] | 1763 | // with the same key, force it to merge with an empty entry. |
| 1764 | for (ptr_iterator MI = bottom_up_ptr_begin(), |
| 1765 | ME = bottom_up_ptr_end(); MI != ME; ++MI) |
| 1766 | if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) |
| 1767 | MI->second.Merge(PtrState(), /*TopDown=*/false); |
| 1768 | } |
| 1769 | |
| 1770 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1771 | /// \brief The main ARC optimization pass. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1772 | class ObjCARCOpt : public FunctionPass { |
| 1773 | bool Changed; |
| 1774 | ProvenanceAnalysis PA; |
| 1775 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1776 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 1777 | bool Run; |
| 1778 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1779 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 1780 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 1781 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1782 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1783 | /// Declaration for ObjC runtime function |
| 1784 | /// objc_retainAutoreleasedReturnValue. |
| 1785 | Constant *RetainRVCallee; |
| 1786 | /// Declaration for ObjC runtime function objc_autoreleaseReturnValue. |
| 1787 | Constant *AutoreleaseRVCallee; |
| 1788 | /// Declaration for ObjC runtime function objc_release. |
| 1789 | Constant *ReleaseCallee; |
| 1790 | /// Declaration for ObjC runtime function objc_retain. |
| 1791 | Constant *RetainCallee; |
| 1792 | /// Declaration for ObjC runtime function objc_retainBlock. |
| 1793 | Constant *RetainBlockCallee; |
| 1794 | /// Declaration for ObjC runtime function objc_autorelease. |
| 1795 | Constant *AutoreleaseCallee; |
| 1796 | |
| 1797 | /// Flags which determine whether each of the interesting runtine functions |
| 1798 | /// is in fact used in the current function. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1799 | unsigned UsedInThisFunction; |
| 1800 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1801 | /// The Metadata Kind for clang.imprecise_release metadata. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1802 | unsigned ImpreciseReleaseMDKind; |
| 1803 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1804 | /// The Metadata Kind for clang.arc.copy_on_escape metadata. |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 1805 | unsigned CopyOnEscapeMDKind; |
| 1806 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 1807 | /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata. |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 1808 | unsigned NoObjCARCExceptionsMDKind; |
| 1809 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1810 | Constant *getRetainRVCallee(Module *M); |
| 1811 | Constant *getAutoreleaseRVCallee(Module *M); |
| 1812 | Constant *getReleaseCallee(Module *M); |
| 1813 | Constant *getRetainCallee(Module *M); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1814 | Constant *getRetainBlockCallee(Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1815 | Constant *getAutoreleaseCallee(Module *M); |
| 1816 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1817 | bool IsRetainBlockOptimizable(const Instruction *Inst); |
| 1818 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1819 | void OptimizeRetainCall(Function &F, Instruction *Retain); |
| 1820 | bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 1821 | void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 1822 | InstructionClass &Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1823 | void OptimizeIndividualCalls(Function &F); |
| 1824 | |
| 1825 | void CheckForCFGHazards(const BasicBlock *BB, |
| 1826 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1827 | BBState &MyStates) const; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1828 | bool VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 1829 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1830 | MapVector<Value *, RRInfo> &Retains, |
| 1831 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1832 | bool VisitBottomUp(BasicBlock *BB, |
| 1833 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1834 | MapVector<Value *, RRInfo> &Retains); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 1835 | bool VisitInstructionTopDown(Instruction *Inst, |
| 1836 | DenseMap<Value *, RRInfo> &Releases, |
| 1837 | BBState &MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1838 | bool VisitTopDown(BasicBlock *BB, |
| 1839 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1840 | DenseMap<Value *, RRInfo> &Releases); |
| 1841 | bool Visit(Function &F, |
| 1842 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1843 | MapVector<Value *, RRInfo> &Retains, |
| 1844 | DenseMap<Value *, RRInfo> &Releases); |
| 1845 | |
| 1846 | void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, |
| 1847 | MapVector<Value *, RRInfo> &Retains, |
| 1848 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1849 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 1850 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1851 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 1852 | bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1853 | MapVector<Value *, RRInfo> &Retains, |
| 1854 | DenseMap<Value *, RRInfo> &Releases, |
| 1855 | Module *M, |
| 1856 | SmallVector<Instruction *, 4> &NewRetains, |
| 1857 | SmallVector<Instruction *, 4> &NewReleases, |
| 1858 | SmallVector<Instruction *, 8> &DeadInsts, |
| 1859 | RRInfo &RetainsToMove, |
| 1860 | RRInfo &ReleasesToMove, |
| 1861 | Value *Arg, |
| 1862 | bool KnownSafe, |
| 1863 | bool &AnyPairsCompletelyEliminated); |
| 1864 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1865 | bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, |
| 1866 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1867 | DenseMap<Value *, RRInfo> &Releases, |
| 1868 | Module *M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1869 | |
| 1870 | void OptimizeWeakCalls(Function &F); |
| 1871 | |
| 1872 | bool OptimizeSequences(Function &F); |
| 1873 | |
| 1874 | void OptimizeReturns(Function &F); |
| 1875 | |
| 1876 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1877 | virtual bool doInitialization(Module &M); |
| 1878 | virtual bool runOnFunction(Function &F); |
| 1879 | virtual void releaseMemory(); |
| 1880 | |
| 1881 | public: |
| 1882 | static char ID; |
| 1883 | ObjCARCOpt() : FunctionPass(ID) { |
| 1884 | initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); |
| 1885 | } |
| 1886 | }; |
| 1887 | } |
| 1888 | |
| 1889 | char ObjCARCOpt::ID = 0; |
| 1890 | INITIALIZE_PASS_BEGIN(ObjCARCOpt, |
| 1891 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1892 | INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis) |
| 1893 | INITIALIZE_PASS_END(ObjCARCOpt, |
| 1894 | "objc-arc", "ObjC ARC optimization", false, false) |
| 1895 | |
| 1896 | Pass *llvm::createObjCARCOptPass() { |
| 1897 | return new ObjCARCOpt(); |
| 1898 | } |
| 1899 | |
| 1900 | void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1901 | AU.addRequired<ObjCARCAliasAnalysis>(); |
| 1902 | AU.addRequired<AliasAnalysis>(); |
| 1903 | // ARC optimization doesn't currently split critical edges. |
| 1904 | AU.setPreservesCFG(); |
| 1905 | } |
| 1906 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 1907 | bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) { |
| 1908 | // Without the magic metadata tag, we have to assume this might be an |
| 1909 | // objc_retainBlock call inserted to convert a block pointer to an id, |
| 1910 | // in which case it really is needed. |
| 1911 | if (!Inst->getMetadata(CopyOnEscapeMDKind)) |
| 1912 | return false; |
| 1913 | |
| 1914 | // If the pointer "escapes" (not including being used in a call), |
| 1915 | // the copy may be needed. |
| 1916 | if (DoesObjCBlockEscape(Inst)) |
| 1917 | return false; |
| 1918 | |
| 1919 | // Otherwise, it's not needed. |
| 1920 | return true; |
| 1921 | } |
| 1922 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1923 | Constant *ObjCARCOpt::getRetainRVCallee(Module *M) { |
| 1924 | if (!RetainRVCallee) { |
| 1925 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1926 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1927 | Type *Params[] = { I8X }; |
| 1928 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1929 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1930 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1931 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1932 | RetainRVCallee = |
| 1933 | M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1934 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1935 | } |
| 1936 | return RetainRVCallee; |
| 1937 | } |
| 1938 | |
| 1939 | Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) { |
| 1940 | if (!AutoreleaseRVCallee) { |
| 1941 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1942 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1943 | Type *Params[] = { I8X }; |
| 1944 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1945 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1946 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1947 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1948 | AutoreleaseRVCallee = |
| 1949 | M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1950 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1951 | } |
| 1952 | return AutoreleaseRVCallee; |
| 1953 | } |
| 1954 | |
| 1955 | Constant *ObjCARCOpt::getReleaseCallee(Module *M) { |
| 1956 | if (!ReleaseCallee) { |
| 1957 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1958 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1959 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1960 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1961 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1962 | ReleaseCallee = |
| 1963 | M->getOrInsertFunction( |
| 1964 | "objc_release", |
| 1965 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1966 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1967 | } |
| 1968 | return ReleaseCallee; |
| 1969 | } |
| 1970 | |
| 1971 | Constant *ObjCARCOpt::getRetainCallee(Module *M) { |
| 1972 | if (!RetainCallee) { |
| 1973 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1974 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1975 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 1976 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 1977 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1978 | RetainCallee = |
| 1979 | M->getOrInsertFunction( |
| 1980 | "objc_retain", |
| 1981 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1982 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 1983 | } |
| 1984 | return RetainCallee; |
| 1985 | } |
| 1986 | |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1987 | Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) { |
| 1988 | if (!RetainBlockCallee) { |
| 1989 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 1990 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Dan Gohman | fca43c2 | 2011-09-14 18:33:34 +0000 | [diff] [blame] | 1991 | // objc_retainBlock is not nounwind because it calls user copy constructors |
| 1992 | // which could theoretically throw. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1993 | RetainBlockCallee = |
| 1994 | M->getOrInsertFunction( |
| 1995 | "objc_retainBlock", |
| 1996 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1997 | AttributeSet()); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 1998 | } |
| 1999 | return RetainBlockCallee; |
| 2000 | } |
| 2001 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2002 | Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) { |
| 2003 | if (!AutoreleaseCallee) { |
| 2004 | LLVMContext &C = M->getContext(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2005 | Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) }; |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2006 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 2007 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 2008 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2009 | AutoreleaseCallee = |
| 2010 | M->getOrInsertFunction( |
| 2011 | "objc_autorelease", |
| 2012 | FunctionType::get(Params[0], Params, /*isVarArg=*/false), |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2013 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2014 | } |
| 2015 | return AutoreleaseCallee; |
| 2016 | } |
| 2017 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2018 | /// Test whether the given value is possible a reference-counted pointer, |
| 2019 | /// including tests which utilize AliasAnalysis. |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2020 | static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) { |
| 2021 | // First make the rudimentary check. |
| 2022 | if (!IsPotentialUse(Op)) |
| 2023 | return false; |
| 2024 | |
| 2025 | // Objects in constant memory are not reference-counted. |
| 2026 | if (AA.pointsToConstantMemory(Op)) |
| 2027 | return false; |
| 2028 | |
| 2029 | // Pointers in constant memory are not pointing to reference-counted objects. |
| 2030 | if (const LoadInst *LI = dyn_cast<LoadInst>(Op)) |
| 2031 | if (AA.pointsToConstantMemory(LI->getPointerOperand())) |
| 2032 | return false; |
| 2033 | |
| 2034 | // Otherwise assume the worst. |
| 2035 | return true; |
| 2036 | } |
| 2037 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2038 | /// Test whether the given instruction can result in a reference count |
| 2039 | /// modification (positive or negative) for the pointer's object. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2040 | static bool |
| 2041 | CanAlterRefCount(const Instruction *Inst, const Value *Ptr, |
| 2042 | ProvenanceAnalysis &PA, InstructionClass Class) { |
| 2043 | switch (Class) { |
| 2044 | case IC_Autorelease: |
| 2045 | case IC_AutoreleaseRV: |
| 2046 | case IC_User: |
| 2047 | // These operations never directly modify a reference count. |
| 2048 | return false; |
| 2049 | default: break; |
| 2050 | } |
| 2051 | |
| 2052 | ImmutableCallSite CS = static_cast<const Value *>(Inst); |
| 2053 | assert(CS && "Only calls can alter reference counts!"); |
| 2054 | |
| 2055 | // See if AliasAnalysis can help us with the call. |
| 2056 | AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS); |
| 2057 | if (AliasAnalysis::onlyReadsMemory(MRB)) |
| 2058 | return false; |
| 2059 | if (AliasAnalysis::onlyAccessesArgPointees(MRB)) { |
| 2060 | for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); |
| 2061 | I != E; ++I) { |
| 2062 | const Value *Op = *I; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2063 | if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2064 | return true; |
| 2065 | } |
| 2066 | return false; |
| 2067 | } |
| 2068 | |
| 2069 | // Assume the worst. |
| 2070 | return true; |
| 2071 | } |
| 2072 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2073 | /// Test whether the given instruction can "use" the given pointer's object in a |
| 2074 | /// way that requires the reference count to be positive. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2075 | static bool |
| 2076 | CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, |
| 2077 | InstructionClass Class) { |
| 2078 | // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers. |
| 2079 | if (Class == IC_Call) |
| 2080 | return false; |
| 2081 | |
| 2082 | // Consider various instructions which may have pointer arguments which are |
| 2083 | // not "uses". |
| 2084 | if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) { |
| 2085 | // Comparing a pointer with null, or any other constant, isn't really a use, |
| 2086 | // because we don't care what the pointer points to, or about the values |
| 2087 | // of any other dynamic reference-counted pointers. |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2088 | if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA())) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2089 | return false; |
| 2090 | } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) { |
| 2091 | // For calls, just check the arguments (and not the callee operand). |
| 2092 | for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(), |
| 2093 | OE = CS.arg_end(); OI != OE; ++OI) { |
| 2094 | const Value *Op = *OI; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2095 | if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2096 | return true; |
| 2097 | } |
| 2098 | return false; |
| 2099 | } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
| 2100 | // Special-case stores, because we don't care about the stored value, just |
| 2101 | // the store address. |
| 2102 | const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand()); |
| 2103 | // If we can't tell what the underlying object was, assume there is a |
| 2104 | // dependence. |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2105 | return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2106 | } |
| 2107 | |
| 2108 | // Check each operand for a match. |
| 2109 | for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end(); |
| 2110 | OI != OE; ++OI) { |
| 2111 | const Value *Op = *OI; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2112 | if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op)) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2113 | return true; |
| 2114 | } |
| 2115 | return false; |
| 2116 | } |
| 2117 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2118 | /// Test whether the given instruction can autorelease any pointer or cause an |
| 2119 | /// autoreleasepool pop. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2120 | static bool |
| 2121 | CanInterruptRV(InstructionClass Class) { |
| 2122 | switch (Class) { |
| 2123 | case IC_AutoreleasepoolPop: |
| 2124 | case IC_CallOrUser: |
| 2125 | case IC_Call: |
| 2126 | case IC_Autorelease: |
| 2127 | case IC_AutoreleaseRV: |
| 2128 | case IC_FusedRetainAutorelease: |
| 2129 | case IC_FusedRetainAutoreleaseRV: |
| 2130 | return true; |
| 2131 | default: |
| 2132 | return false; |
| 2133 | } |
| 2134 | } |
| 2135 | |
| 2136 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2137 | /// \enum DependenceKind |
| 2138 | /// \brief Defines different dependence kinds among various ARC constructs. |
| 2139 | /// |
| 2140 | /// There are several kinds of dependence-like concepts in use here. |
| 2141 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2142 | enum DependenceKind { |
| 2143 | NeedsPositiveRetainCount, |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 2144 | AutoreleasePoolBoundary, |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2145 | CanChangeRetainCount, |
| 2146 | RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease. |
| 2147 | RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue. |
| 2148 | RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue. |
| 2149 | }; |
| 2150 | } |
| 2151 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2152 | /// Test if there can be dependencies on Inst through Arg. This function only |
| 2153 | /// tests dependencies relevant for removing pairs of calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2154 | static bool |
| 2155 | Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg, |
| 2156 | ProvenanceAnalysis &PA) { |
| 2157 | // If we've reached the definition of Arg, stop. |
| 2158 | if (Inst == Arg) |
| 2159 | return true; |
| 2160 | |
| 2161 | switch (Flavor) { |
| 2162 | case NeedsPositiveRetainCount: { |
| 2163 | InstructionClass Class = GetInstructionClass(Inst); |
| 2164 | switch (Class) { |
| 2165 | case IC_AutoreleasepoolPop: |
| 2166 | case IC_AutoreleasepoolPush: |
| 2167 | case IC_None: |
| 2168 | return false; |
| 2169 | default: |
| 2170 | return CanUse(Inst, Arg, PA, Class); |
| 2171 | } |
| 2172 | } |
| 2173 | |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 2174 | case AutoreleasePoolBoundary: { |
| 2175 | InstructionClass Class = GetInstructionClass(Inst); |
| 2176 | switch (Class) { |
| 2177 | case IC_AutoreleasepoolPop: |
| 2178 | case IC_AutoreleasepoolPush: |
| 2179 | // These mark the end and begin of an autorelease pool scope. |
| 2180 | return true; |
| 2181 | default: |
| 2182 | // Nothing else does this. |
| 2183 | return false; |
| 2184 | } |
| 2185 | } |
| 2186 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2187 | case CanChangeRetainCount: { |
| 2188 | InstructionClass Class = GetInstructionClass(Inst); |
| 2189 | switch (Class) { |
| 2190 | case IC_AutoreleasepoolPop: |
| 2191 | // Conservatively assume this can decrement any count. |
| 2192 | return true; |
| 2193 | case IC_AutoreleasepoolPush: |
| 2194 | case IC_None: |
| 2195 | return false; |
| 2196 | default: |
| 2197 | return CanAlterRefCount(Inst, Arg, PA, Class); |
| 2198 | } |
| 2199 | } |
| 2200 | |
| 2201 | case RetainAutoreleaseDep: |
| 2202 | switch (GetBasicInstructionClass(Inst)) { |
| 2203 | case IC_AutoreleasepoolPop: |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 2204 | case IC_AutoreleasepoolPush: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2205 | // Don't merge an objc_autorelease with an objc_retain inside a different |
| 2206 | // autoreleasepool scope. |
| 2207 | return true; |
| 2208 | case IC_Retain: |
| 2209 | case IC_RetainRV: |
| 2210 | // Check for a retain of the same pointer for merging. |
| 2211 | return GetObjCArg(Inst) == Arg; |
| 2212 | default: |
| 2213 | // Nothing else matters for objc_retainAutorelease formation. |
| 2214 | return false; |
| 2215 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2216 | |
| 2217 | case RetainAutoreleaseRVDep: { |
| 2218 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2219 | switch (Class) { |
| 2220 | case IC_Retain: |
| 2221 | case IC_RetainRV: |
| 2222 | // Check for a retain of the same pointer for merging. |
| 2223 | return GetObjCArg(Inst) == Arg; |
| 2224 | default: |
| 2225 | // Anything that can autorelease interrupts |
| 2226 | // retainAutoreleaseReturnValue formation. |
| 2227 | return CanInterruptRV(Class); |
| 2228 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2229 | } |
| 2230 | |
| 2231 | case RetainRVDep: |
| 2232 | return CanInterruptRV(GetBasicInstructionClass(Inst)); |
| 2233 | } |
| 2234 | |
| 2235 | llvm_unreachable("Invalid dependence flavor"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2236 | } |
| 2237 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2238 | /// Walk up the CFG from StartPos (which is in StartBB) and find local and |
| 2239 | /// non-local dependencies on Arg. |
| 2240 | /// |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2241 | /// TODO: Cache results? |
| 2242 | static void |
| 2243 | FindDependencies(DependenceKind Flavor, |
| 2244 | const Value *Arg, |
| 2245 | BasicBlock *StartBB, Instruction *StartInst, |
| 2246 | SmallPtrSet<Instruction *, 4> &DependingInstructions, |
| 2247 | SmallPtrSet<const BasicBlock *, 4> &Visited, |
| 2248 | ProvenanceAnalysis &PA) { |
| 2249 | BasicBlock::iterator StartPos = StartInst; |
| 2250 | |
| 2251 | SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist; |
| 2252 | Worklist.push_back(std::make_pair(StartBB, StartPos)); |
| 2253 | do { |
| 2254 | std::pair<BasicBlock *, BasicBlock::iterator> Pair = |
| 2255 | Worklist.pop_back_val(); |
| 2256 | BasicBlock *LocalStartBB = Pair.first; |
| 2257 | BasicBlock::iterator LocalStartPos = Pair.second; |
| 2258 | BasicBlock::iterator StartBBBegin = LocalStartBB->begin(); |
| 2259 | for (;;) { |
| 2260 | if (LocalStartPos == StartBBBegin) { |
| 2261 | pred_iterator PI(LocalStartBB), PE(LocalStartBB, false); |
| 2262 | if (PI == PE) |
| 2263 | // If we've reached the function entry, produce a null dependence. |
| 2264 | DependingInstructions.insert(0); |
| 2265 | else |
| 2266 | // Add the predecessors to the worklist. |
| 2267 | do { |
| 2268 | BasicBlock *PredBB = *PI; |
| 2269 | if (Visited.insert(PredBB)) |
| 2270 | Worklist.push_back(std::make_pair(PredBB, PredBB->end())); |
| 2271 | } while (++PI != PE); |
| 2272 | break; |
| 2273 | } |
| 2274 | |
| 2275 | Instruction *Inst = --LocalStartPos; |
| 2276 | if (Depends(Flavor, Inst, Arg, PA)) { |
| 2277 | DependingInstructions.insert(Inst); |
| 2278 | break; |
| 2279 | } |
| 2280 | } |
| 2281 | } while (!Worklist.empty()); |
| 2282 | |
| 2283 | // Determine whether the original StartBB post-dominates all of the blocks we |
| 2284 | // visited. If not, insert a sentinal indicating that most optimizations are |
| 2285 | // not safe. |
| 2286 | for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(), |
| 2287 | E = Visited.end(); I != E; ++I) { |
| 2288 | const BasicBlock *BB = *I; |
| 2289 | if (BB == StartBB) |
| 2290 | continue; |
| 2291 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 2292 | for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) { |
| 2293 | const BasicBlock *Succ = *SI; |
| 2294 | if (Succ != StartBB && !Visited.count(Succ)) { |
| 2295 | DependingInstructions.insert(reinterpret_cast<Instruction *>(-1)); |
| 2296 | return; |
| 2297 | } |
| 2298 | } |
| 2299 | } |
| 2300 | } |
| 2301 | |
| 2302 | static bool isNullOrUndef(const Value *V) { |
| 2303 | return isa<ConstantPointerNull>(V) || isa<UndefValue>(V); |
| 2304 | } |
| 2305 | |
| 2306 | static bool isNoopInstruction(const Instruction *I) { |
| 2307 | return isa<BitCastInst>(I) || |
| 2308 | (isa<GetElementPtrInst>(I) && |
| 2309 | cast<GetElementPtrInst>(I)->hasAllZeroIndices()); |
| 2310 | } |
| 2311 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2312 | /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a |
| 2313 | /// return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2314 | void |
| 2315 | ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2316 | ImmutableCallSite CS(GetObjCArg(Retain)); |
| 2317 | const Instruction *Call = CS.getInstruction(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2318 | if (!Call) return; |
| 2319 | if (Call->getParent() != Retain->getParent()) return; |
| 2320 | |
| 2321 | // Check that the call is next to the retain. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2322 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2323 | ++I; |
| 2324 | while (isNoopInstruction(I)) ++I; |
| 2325 | if (&*I != Retain) |
| 2326 | return; |
| 2327 | |
| 2328 | // Turn it to an objc_retainAutoreleasedReturnValue.. |
| 2329 | Changed = true; |
| 2330 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2331 | |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 2332 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming " |
Michael Gottesman | 9f1be68 | 2013-01-12 03:45:49 +0000 | [diff] [blame] | 2333 | "objc_retain => objc_retainAutoreleasedReturnValue" |
| 2334 | " since the operand is a return value.\n" |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 2335 | " Old: " |
| 2336 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2337 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2338 | cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent())); |
Michael Gottesman | 1e00ac6 | 2013-01-04 21:30:38 +0000 | [diff] [blame] | 2339 | |
| 2340 | DEBUG(dbgs() << " New: " |
| 2341 | << *Retain << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2342 | } |
| 2343 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2344 | /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is |
| 2345 | /// not a return value. Or, if it can be paired with an |
| 2346 | /// objc_autoreleaseReturnValue, delete the pair and return true. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2347 | bool |
| 2348 | ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 2349 | // Check for the argument being from an immediately preceding call or invoke. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2350 | const Value *Arg = GetObjCArg(RetainRV); |
| 2351 | ImmutableCallSite CS(Arg); |
| 2352 | if (const Instruction *Call = CS.getInstruction()) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2353 | if (Call->getParent() == RetainRV->getParent()) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2354 | BasicBlock::const_iterator I = Call; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2355 | ++I; |
| 2356 | while (isNoopInstruction(I)) ++I; |
| 2357 | if (&*I == RetainRV) |
| 2358 | return false; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2359 | } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 2360 | BasicBlock *RetainRVParent = RetainRV->getParent(); |
| 2361 | if (II->getNormalDest() == RetainRVParent) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2362 | BasicBlock::const_iterator I = RetainRVParent->begin(); |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 2363 | while (isNoopInstruction(I)) ++I; |
| 2364 | if (&*I == RetainRV) |
| 2365 | return false; |
| 2366 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2367 | } |
Dan Gohman | e3ed2b0 | 2012-03-23 18:09:00 +0000 | [diff] [blame] | 2368 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2369 | |
| 2370 | // Check for being preceded by an objc_autoreleaseReturnValue on the same |
| 2371 | // pointer. In this case, we can delete the pair. |
| 2372 | BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin(); |
| 2373 | if (I != Begin) { |
| 2374 | do --I; while (I != Begin && isNoopInstruction(I)); |
| 2375 | if (GetBasicInstructionClass(I) == IC_AutoreleaseRV && |
| 2376 | GetObjCArg(I) == Arg) { |
| 2377 | Changed = true; |
| 2378 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2379 | |
Michael Gottesman | 5c32ce9 | 2013-01-05 17:55:35 +0000 | [diff] [blame] | 2380 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n" |
| 2381 | << " Erasing " << *RetainRV |
| 2382 | << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2383 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2384 | EraseInstruction(I); |
| 2385 | EraseInstruction(RetainRV); |
| 2386 | return true; |
| 2387 | } |
| 2388 | } |
| 2389 | |
| 2390 | // Turn it to a plain objc_retain. |
| 2391 | Changed = true; |
| 2392 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2393 | |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 2394 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming " |
| 2395 | "objc_retainAutoreleasedReturnValue => " |
| 2396 | "objc_retain since the operand is not a return value.\n" |
| 2397 | " Old: " |
| 2398 | << *RetainRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2399 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2400 | cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent())); |
Michael Gottesman | def07bb | 2013-01-05 17:55:42 +0000 | [diff] [blame] | 2401 | |
| 2402 | DEBUG(dbgs() << " New: " |
| 2403 | << *RetainRV << "\n"); |
| 2404 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2405 | return false; |
| 2406 | } |
| 2407 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2408 | /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not |
| 2409 | /// used as a return value. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2410 | void |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 2411 | ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, |
| 2412 | InstructionClass &Class) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2413 | // Check for a return of the pointer value. |
| 2414 | const Value *Ptr = GetObjCArg(AutoreleaseRV); |
Dan Gohman | 10a18d5 | 2011-08-12 00:36:31 +0000 | [diff] [blame] | 2415 | SmallVector<const Value *, 2> Users; |
| 2416 | Users.push_back(Ptr); |
| 2417 | do { |
| 2418 | Ptr = Users.pop_back_val(); |
| 2419 | for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); |
| 2420 | UI != UE; ++UI) { |
| 2421 | const User *I = *UI; |
| 2422 | if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV) |
| 2423 | return; |
| 2424 | if (isa<BitCastInst>(I)) |
| 2425 | Users.push_back(I); |
| 2426 | } |
| 2427 | } while (!Users.empty()); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2428 | |
| 2429 | Changed = true; |
| 2430 | ++NumPeeps; |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 2431 | |
| 2432 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming " |
| 2433 | "objc_autoreleaseReturnValue => " |
| 2434 | "objc_autorelease since its operand is not used as a return " |
| 2435 | "value.\n" |
| 2436 | " Old: " |
| 2437 | << *AutoreleaseRV << "\n"); |
| 2438 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 2439 | CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); |
| 2440 | AutoreleaseRVCI-> |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2441 | setCalledFunction(getAutoreleaseCallee(F.getParent())); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 2442 | AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 2443 | Class = IC_Autorelease; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2444 | |
Michael Gottesman | 1bf6908 | 2013-01-06 21:07:11 +0000 | [diff] [blame] | 2445 | DEBUG(dbgs() << " New: " |
| 2446 | << *AutoreleaseRV << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2447 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2448 | } |
| 2449 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2450 | /// Visit each call, one at a time, and make simplifications without doing any |
| 2451 | /// additional analysis. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2452 | void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { |
| 2453 | // Reset all the flags in preparation for recomputing them. |
| 2454 | UsedInThisFunction = 0; |
| 2455 | |
| 2456 | // Visit all objc_* calls in F. |
| 2457 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 2458 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 2459 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2460 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 2461 | |
Michael Gottesman | d359e06 | 2013-01-18 03:08:39 +0000 | [diff] [blame] | 2462 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: " |
| 2463 | << Class << "; " << *Inst << "\n"); |
Michael Gottesman | 782e344 | 2013-01-17 18:32:34 +0000 | [diff] [blame] | 2464 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2465 | switch (Class) { |
| 2466 | default: break; |
| 2467 | |
| 2468 | // Delete no-op casts. These function calls have special semantics, but |
| 2469 | // the semantics are entirely implemented via lowering in the front-end, |
| 2470 | // so by the time they reach the optimizer, they are just no-op calls |
| 2471 | // which return their argument. |
| 2472 | // |
| 2473 | // There are gray areas here, as the ability to cast reference-counted |
| 2474 | // pointers to raw void* and back allows code to break ARC assumptions, |
| 2475 | // however these are currently considered to be unimportant. |
| 2476 | case IC_NoopCast: |
| 2477 | Changed = true; |
| 2478 | ++NumNoops; |
Michael Gottesman | dc042f0 | 2013-01-06 21:07:15 +0000 | [diff] [blame] | 2479 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:" |
| 2480 | " " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2481 | EraseInstruction(Inst); |
| 2482 | continue; |
| 2483 | |
| 2484 | // If the pointer-to-weak-pointer is null, it's undefined behavior. |
| 2485 | case IC_StoreWeak: |
| 2486 | case IC_LoadWeak: |
| 2487 | case IC_LoadWeakRetained: |
| 2488 | case IC_InitWeak: |
| 2489 | case IC_DestroyWeak: { |
| 2490 | CallInst *CI = cast<CallInst>(Inst); |
| 2491 | if (isNullOrUndef(CI->getArgOperand(0))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2492 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2493 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2494 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 2495 | Constant::getNullValue(Ty), |
| 2496 | CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2497 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 2498 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 2499 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 2500 | " Old = " << *CI << |
| 2501 | "\n New = " << |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2502 | *NewValue << "\n"); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 2503 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2504 | CI->eraseFromParent(); |
| 2505 | continue; |
| 2506 | } |
| 2507 | break; |
| 2508 | } |
| 2509 | case IC_CopyWeak: |
| 2510 | case IC_MoveWeak: { |
| 2511 | CallInst *CI = cast<CallInst>(Inst); |
| 2512 | if (isNullOrUndef(CI->getArgOperand(0)) || |
| 2513 | isNullOrUndef(CI->getArgOperand(1))) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 2514 | Changed = true; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2515 | Type *Ty = CI->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2516 | new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), |
| 2517 | Constant::getNullValue(Ty), |
| 2518 | CI); |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 2519 | |
| 2520 | llvm::Value *NewValue = UndefValue::get(CI->getType()); |
| 2521 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null " |
| 2522 | "pointer-to-weak-pointer is undefined behavior.\n" |
| 2523 | " Old = " << *CI << |
| 2524 | "\n New = " << |
| 2525 | *NewValue << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2526 | |
Michael Gottesman | fec61c0 | 2013-01-06 21:54:30 +0000 | [diff] [blame] | 2527 | CI->replaceAllUsesWith(NewValue); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2528 | CI->eraseFromParent(); |
| 2529 | continue; |
| 2530 | } |
| 2531 | break; |
| 2532 | } |
| 2533 | case IC_Retain: |
| 2534 | OptimizeRetainCall(F, Inst); |
| 2535 | break; |
| 2536 | case IC_RetainRV: |
| 2537 | if (OptimizeRetainRVCall(F, Inst)) |
| 2538 | continue; |
| 2539 | break; |
| 2540 | case IC_AutoreleaseRV: |
Michael Gottesman | 556ff61 | 2013-01-12 01:25:19 +0000 | [diff] [blame] | 2541 | OptimizeAutoreleaseRVCall(F, Inst, Class); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2542 | break; |
| 2543 | } |
| 2544 | |
| 2545 | // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. |
| 2546 | if (IsAutorelease(Class) && Inst->use_empty()) { |
| 2547 | CallInst *Call = cast<CallInst>(Inst); |
| 2548 | const Value *Arg = Call->getArgOperand(0); |
| 2549 | Arg = FindSingleUseIdentifiedObject(Arg); |
| 2550 | if (Arg) { |
| 2551 | Changed = true; |
| 2552 | ++NumAutoreleases; |
| 2553 | |
| 2554 | // Create the declaration lazily. |
| 2555 | LLVMContext &C = Inst->getContext(); |
| 2556 | CallInst *NewCall = |
| 2557 | CallInst::Create(getReleaseCallee(F.getParent()), |
| 2558 | Call->getArgOperand(0), "", Call); |
| 2559 | NewCall->setMetadata(ImpreciseReleaseMDKind, |
| 2560 | MDNode::get(C, ArrayRef<Value *>())); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2561 | |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 2562 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing " |
| 2563 | "objc_autorelease(x) with objc_release(x) since x is " |
| 2564 | "otherwise unused.\n" |
Michael Gottesman | 4bf6e75 | 2013-01-06 22:56:54 +0000 | [diff] [blame] | 2565 | " Old: " << *Call << |
Michael Gottesman | a6a1dad | 2013-01-06 22:56:50 +0000 | [diff] [blame] | 2566 | "\n New: " << |
| 2567 | *NewCall << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 2568 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2569 | EraseInstruction(Call); |
| 2570 | Inst = NewCall; |
| 2571 | Class = IC_Release; |
| 2572 | } |
| 2573 | } |
| 2574 | |
| 2575 | // For functions which can never be passed stack arguments, add |
| 2576 | // a tail keyword. |
| 2577 | if (IsAlwaysTail(Class)) { |
| 2578 | Changed = true; |
Michael Gottesman | 2d76331 | 2013-01-06 23:39:09 +0000 | [diff] [blame] | 2579 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword" |
| 2580 | " to function since it can never be passed stack args: " << *Inst << |
| 2581 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2582 | cast<CallInst>(Inst)->setTailCall(); |
| 2583 | } |
| 2584 | |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 2585 | // Ensure that functions that can never have a "tail" keyword due to the |
| 2586 | // semantics of ARC truly do not do so. |
| 2587 | if (IsNeverTail(Class)) { |
| 2588 | Changed = true; |
Michael Gottesman | 4385edf | 2013-01-14 01:47:53 +0000 | [diff] [blame] | 2589 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail " |
| 2590 | "keyword from function: " << *Inst << |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 2591 | "\n"); |
| 2592 | cast<CallInst>(Inst)->setTailCall(false); |
| 2593 | } |
| 2594 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2595 | // Set nounwind as needed. |
| 2596 | if (IsNoThrow(Class)) { |
| 2597 | Changed = true; |
Michael Gottesman | 8800a51 | 2013-01-06 23:39:13 +0000 | [diff] [blame] | 2598 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw" |
| 2599 | " class. Setting nounwind on: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2600 | cast<CallInst>(Inst)->setDoesNotThrow(); |
| 2601 | } |
| 2602 | |
| 2603 | if (!IsNoopOnNull(Class)) { |
| 2604 | UsedInThisFunction |= 1 << Class; |
| 2605 | continue; |
| 2606 | } |
| 2607 | |
| 2608 | const Value *Arg = GetObjCArg(Inst); |
| 2609 | |
| 2610 | // ARC calls with null are no-ops. Delete them. |
| 2611 | if (isNullOrUndef(Arg)) { |
| 2612 | Changed = true; |
| 2613 | ++NumNoops; |
Michael Gottesman | 5b970e1 | 2013-01-07 00:04:52 +0000 | [diff] [blame] | 2614 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with " |
| 2615 | " null are no-ops. Erasing: " << *Inst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2616 | EraseInstruction(Inst); |
| 2617 | continue; |
| 2618 | } |
| 2619 | |
| 2620 | // Keep track of which of retain, release, autorelease, and retain_block |
| 2621 | // are actually present in this function. |
| 2622 | UsedInThisFunction |= 1 << Class; |
| 2623 | |
| 2624 | // If Arg is a PHI, and one or more incoming values to the |
| 2625 | // PHI are null, and the call is control-equivalent to the PHI, and there |
| 2626 | // are no relevant side effects between the PHI and the call, the call |
| 2627 | // could be pushed up to just those paths with non-null incoming values. |
| 2628 | // For now, don't bother splitting critical edges for this. |
| 2629 | SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; |
| 2630 | Worklist.push_back(std::make_pair(Inst, Arg)); |
| 2631 | do { |
| 2632 | std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); |
| 2633 | Inst = Pair.first; |
| 2634 | Arg = Pair.second; |
| 2635 | |
| 2636 | const PHINode *PN = dyn_cast<PHINode>(Arg); |
| 2637 | if (!PN) continue; |
| 2638 | |
| 2639 | // Determine if the PHI has any null operands, or any incoming |
| 2640 | // critical edges. |
| 2641 | bool HasNull = false; |
| 2642 | bool HasCriticalEdges = false; |
| 2643 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 2644 | Value *Incoming = |
| 2645 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
| 2646 | if (isNullOrUndef(Incoming)) |
| 2647 | HasNull = true; |
| 2648 | else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back()) |
| 2649 | .getNumSuccessors() != 1) { |
| 2650 | HasCriticalEdges = true; |
| 2651 | break; |
| 2652 | } |
| 2653 | } |
| 2654 | // If we have null operands and no critical edges, optimize. |
| 2655 | if (!HasCriticalEdges && HasNull) { |
| 2656 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 2657 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 2658 | |
| 2659 | // Check that there is nothing that cares about the reference |
| 2660 | // count between the call and the phi. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 2661 | switch (Class) { |
| 2662 | case IC_Retain: |
| 2663 | case IC_RetainBlock: |
| 2664 | // These can always be moved up. |
| 2665 | break; |
| 2666 | case IC_Release: |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2667 | // These can't be moved across things that care about the retain |
| 2668 | // count. |
Dan Gohman | 8478d76 | 2012-04-13 00:59:57 +0000 | [diff] [blame] | 2669 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 2670 | Inst->getParent(), Inst, |
| 2671 | DependingInstructions, Visited, PA); |
| 2672 | break; |
| 2673 | case IC_Autorelease: |
| 2674 | // These can't be moved across autorelease pool scope boundaries. |
| 2675 | FindDependencies(AutoreleasePoolBoundary, Arg, |
| 2676 | Inst->getParent(), Inst, |
| 2677 | DependingInstructions, Visited, PA); |
| 2678 | break; |
| 2679 | case IC_RetainRV: |
| 2680 | case IC_AutoreleaseRV: |
| 2681 | // Don't move these; the RV optimization depends on the autoreleaseRV |
| 2682 | // being tail called, and the retainRV being immediately after a call |
| 2683 | // (which might still happen if we get lucky with codegen layout, but |
| 2684 | // it's not worth taking the chance). |
| 2685 | continue; |
| 2686 | default: |
| 2687 | llvm_unreachable("Invalid dependence flavor"); |
| 2688 | } |
| 2689 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2690 | if (DependingInstructions.size() == 1 && |
| 2691 | *DependingInstructions.begin() == PN) { |
| 2692 | Changed = true; |
| 2693 | ++NumPartialNoops; |
| 2694 | // Clone the call into each predecessor that has a non-null value. |
| 2695 | CallInst *CInst = cast<CallInst>(Inst); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2696 | Type *ParamTy = CInst->getArgOperand(0)->getType(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2697 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 2698 | Value *Incoming = |
| 2699 | StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); |
| 2700 | if (!isNullOrUndef(Incoming)) { |
| 2701 | CallInst *Clone = cast<CallInst>(CInst->clone()); |
| 2702 | Value *Op = PN->getIncomingValue(i); |
| 2703 | Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); |
| 2704 | if (Op->getType() != ParamTy) |
| 2705 | Op = new BitCastInst(Op, ParamTy, "", InsertPos); |
| 2706 | Clone->setArgOperand(0, Op); |
| 2707 | Clone->insertBefore(InsertPos); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2708 | |
| 2709 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning " |
| 2710 | << *CInst << "\n" |
| 2711 | " And inserting " |
| 2712 | "clone at " << *InsertPos << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2713 | Worklist.push_back(std::make_pair(Clone, Incoming)); |
| 2714 | } |
| 2715 | } |
| 2716 | // Erase the original call. |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 2717 | DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2718 | EraseInstruction(CInst); |
| 2719 | continue; |
| 2720 | } |
| 2721 | } |
| 2722 | } while (!Worklist.empty()); |
| 2723 | } |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 2724 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2725 | } |
| 2726 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 2727 | /// Check for critical edges, loop boundaries, irreducible control flow, or |
| 2728 | /// other CFG structures where moving code across the edge would result in it |
| 2729 | /// being executed more. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2730 | void |
| 2731 | ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, |
| 2732 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2733 | BBState &MyStates) const { |
| 2734 | // If any top-down local-use or possible-dec has a succ which is earlier in |
| 2735 | // the sequence, forget it. |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2736 | for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2737 | E = MyStates.top_down_ptr_end(); I != E; ++I) |
| 2738 | switch (I->second.GetSeq()) { |
| 2739 | default: break; |
| 2740 | case S_Use: { |
| 2741 | const Value *Arg = I->first; |
| 2742 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 2743 | bool SomeSuccHasSame = false; |
| 2744 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2745 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2746 | succ_const_iterator SI(TI), SE(TI, false); |
| 2747 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2748 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2749 | Sequence SuccSSeq = S_None; |
| 2750 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2751 | // If VisitBottomUp has pointer information for this successor, take |
| 2752 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2753 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 2754 | BBStates.find(*SI); |
| 2755 | assert(BBI != BBStates.end()); |
| 2756 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 2757 | SuccSSeq = SuccS.GetSeq(); |
| 2758 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2759 | switch (SuccSSeq) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2760 | case S_None: |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2761 | case S_CanRelease: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2762 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2763 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2764 | break; |
| 2765 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2766 | continue; |
| 2767 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2768 | case S_Use: |
| 2769 | SomeSuccHasSame = true; |
| 2770 | break; |
| 2771 | case S_Stop: |
| 2772 | case S_Release: |
| 2773 | case S_MovableRelease: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2774 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2775 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2776 | break; |
| 2777 | case S_Retain: |
| 2778 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2779 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2780 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2781 | // If the state at the other end of any of the successor edges |
| 2782 | // matches the current state, require all edges to match. This |
| 2783 | // guards against loops in the middle of a sequence. |
| 2784 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2785 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 2786 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2787 | } |
| 2788 | case S_CanRelease: { |
| 2789 | const Value *Arg = I->first; |
| 2790 | const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); |
| 2791 | bool SomeSuccHasSame = false; |
| 2792 | bool AllSuccsHaveSame = true; |
Dan Gohman | 55b0674 | 2012-03-02 01:13:53 +0000 | [diff] [blame] | 2793 | PtrState &S = I->second; |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2794 | succ_const_iterator SI(TI), SE(TI, false); |
| 2795 | |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 2796 | for (; SI != SE; ++SI) { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2797 | Sequence SuccSSeq = S_None; |
| 2798 | bool SuccSRRIKnownSafe = false; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 2799 | // If VisitBottomUp has pointer information for this successor, take |
| 2800 | // what we know about it. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 2801 | DenseMap<const BasicBlock *, BBState>::iterator BBI = |
| 2802 | BBStates.find(*SI); |
| 2803 | assert(BBI != BBStates.end()); |
| 2804 | const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); |
| 2805 | SuccSSeq = SuccS.GetSeq(); |
| 2806 | SuccSRRIKnownSafe = SuccS.RRI.KnownSafe; |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2807 | switch (SuccSSeq) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2808 | case S_None: { |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2809 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) { |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2810 | S.ClearSequenceProgress(); |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2811 | break; |
| 2812 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2813 | continue; |
| 2814 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2815 | case S_CanRelease: |
| 2816 | SomeSuccHasSame = true; |
| 2817 | break; |
| 2818 | case S_Stop: |
| 2819 | case S_Release: |
| 2820 | case S_MovableRelease: |
| 2821 | case S_Use: |
Dan Gohman | 362eb69 | 2012-03-02 01:26:46 +0000 | [diff] [blame] | 2822 | if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2823 | AllSuccsHaveSame = false; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2824 | break; |
| 2825 | case S_Retain: |
| 2826 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2827 | } |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2828 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2829 | // If the state at the other end of any of the successor edges |
| 2830 | // matches the current state, require all edges to match. This |
| 2831 | // guards against loops in the middle of a sequence. |
| 2832 | if (SomeSuccHasSame && !AllSuccsHaveSame) |
Dan Gohman | 1213027 | 2011-08-12 00:26:31 +0000 | [diff] [blame] | 2833 | S.ClearSequenceProgress(); |
Dan Gohman | 04443706 | 2011-12-12 18:13:53 +0000 | [diff] [blame] | 2834 | break; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2835 | } |
| 2836 | } |
| 2837 | } |
| 2838 | |
| 2839 | bool |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2840 | ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst, |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2841 | BasicBlock *BB, |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2842 | MapVector<Value *, RRInfo> &Retains, |
| 2843 | BBState &MyStates) { |
| 2844 | bool NestingDetected = false; |
| 2845 | InstructionClass Class = GetInstructionClass(Inst); |
| 2846 | const Value *Arg = 0; |
| 2847 | |
| 2848 | switch (Class) { |
| 2849 | case IC_Release: { |
| 2850 | Arg = GetObjCArg(Inst); |
| 2851 | |
| 2852 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
| 2853 | |
| 2854 | // If we see two releases in a row on the same pointer. If so, make |
| 2855 | // a note, and we'll cicle back to revisit it after we've |
| 2856 | // hopefully eliminated the second release, which may allow us to |
| 2857 | // eliminate the first release too. |
| 2858 | // Theoretically we could implement removal of nested retain+release |
| 2859 | // pairs by making PtrState hold a stack of states, but this is |
| 2860 | // simple and avoids adding overhead for the non-nested case. |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2861 | if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) { |
| 2862 | DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested " |
| 2863 | "releases (i.e. a release pair)\n"); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2864 | NestingDetected = true; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 2865 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2866 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2867 | MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2868 | S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2869 | S.RRI.ReleaseMetadata = ReleaseMetadata; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2870 | S.RRI.KnownSafe = S.IsKnownIncremented(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2871 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 2872 | S.RRI.Calls.insert(Inst); |
| 2873 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 2874 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2875 | break; |
| 2876 | } |
| 2877 | case IC_RetainBlock: |
| 2878 | // An objc_retainBlock call with just a use may need to be kept, |
| 2879 | // because it may be copying a block from the stack to the heap. |
| 2880 | if (!IsRetainBlockOptimizable(Inst)) |
| 2881 | break; |
| 2882 | // FALLTHROUGH |
| 2883 | case IC_Retain: |
| 2884 | case IC_RetainRV: { |
| 2885 | Arg = GetObjCArg(Inst); |
| 2886 | |
| 2887 | PtrState &S = MyStates.getPtrBottomUpState(Arg); |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2888 | S.SetKnownPositiveRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2889 | |
| 2890 | switch (S.GetSeq()) { |
| 2891 | case S_Stop: |
| 2892 | case S_Release: |
| 2893 | case S_MovableRelease: |
| 2894 | case S_Use: |
| 2895 | S.RRI.ReverseInsertPts.clear(); |
| 2896 | // FALL THROUGH |
| 2897 | case S_CanRelease: |
| 2898 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 2899 | // better to let it remain as the first instruction after a call. |
| 2900 | if (Class != IC_RetainRV) { |
| 2901 | S.RRI.IsRetainBlock = Class == IC_RetainBlock; |
| 2902 | Retains[Inst] = S.RRI; |
| 2903 | } |
| 2904 | S.ClearSequenceProgress(); |
| 2905 | break; |
| 2906 | case S_None: |
| 2907 | break; |
| 2908 | case S_Retain: |
| 2909 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2910 | } |
| 2911 | return NestingDetected; |
| 2912 | } |
| 2913 | case IC_AutoreleasepoolPop: |
| 2914 | // Conservatively, clear MyStates for all known pointers. |
| 2915 | MyStates.clearBottomUpPointers(); |
| 2916 | return NestingDetected; |
| 2917 | case IC_AutoreleasepoolPush: |
| 2918 | case IC_None: |
| 2919 | // These are irrelevant. |
| 2920 | return NestingDetected; |
| 2921 | default: |
| 2922 | break; |
| 2923 | } |
| 2924 | |
| 2925 | // Consider any other possible effects of this instruction on each |
| 2926 | // pointer being tracked. |
| 2927 | for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(), |
| 2928 | ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) { |
| 2929 | const Value *Ptr = MI->first; |
| 2930 | if (Ptr == Arg) |
| 2931 | continue; // Handled above. |
| 2932 | PtrState &S = MI->second; |
| 2933 | Sequence Seq = S.GetSeq(); |
| 2934 | |
| 2935 | // Check for possible releases. |
| 2936 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 2937 | S.ClearRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2938 | switch (Seq) { |
| 2939 | case S_Use: |
| 2940 | S.SetSeq(S_CanRelease); |
| 2941 | continue; |
| 2942 | case S_CanRelease: |
| 2943 | case S_Release: |
| 2944 | case S_MovableRelease: |
| 2945 | case S_Stop: |
| 2946 | case S_None: |
| 2947 | break; |
| 2948 | case S_Retain: |
| 2949 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2950 | } |
| 2951 | } |
| 2952 | |
| 2953 | // Check for possible direct uses. |
| 2954 | switch (Seq) { |
| 2955 | case S_Release: |
| 2956 | case S_MovableRelease: |
| 2957 | if (CanUse(Inst, Ptr, PA, Class)) { |
| 2958 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2959 | // If this is an invoke instruction, we're scanning it as part of |
| 2960 | // one of its successor blocks, since we can't insert code after it |
| 2961 | // in its own block, and we don't want to split critical edges. |
| 2962 | if (isa<InvokeInst>(Inst)) |
| 2963 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2964 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2965 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2966 | S.SetSeq(S_Use); |
| 2967 | } else if (Seq == S_Release && |
| 2968 | (Class == IC_User || Class == IC_CallOrUser)) { |
| 2969 | // Non-movable releases depend on any possible objc pointer use. |
| 2970 | S.SetSeq(S_Stop); |
| 2971 | assert(S.RRI.ReverseInsertPts.empty()); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 2972 | // As above; handle invoke specially. |
| 2973 | if (isa<InvokeInst>(Inst)) |
| 2974 | S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt()); |
| 2975 | else |
Francois Pichet | 4b9ab74 | 2012-03-24 01:36:37 +0000 | [diff] [blame] | 2976 | S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst))); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 2977 | } |
| 2978 | break; |
| 2979 | case S_Stop: |
| 2980 | if (CanUse(Inst, Ptr, PA, Class)) |
| 2981 | S.SetSeq(S_Use); |
| 2982 | break; |
| 2983 | case S_CanRelease: |
| 2984 | case S_Use: |
| 2985 | case S_None: |
| 2986 | break; |
| 2987 | case S_Retain: |
| 2988 | llvm_unreachable("bottom-up pointer in retain state!"); |
| 2989 | } |
| 2990 | } |
| 2991 | |
| 2992 | return NestingDetected; |
| 2993 | } |
| 2994 | |
| 2995 | bool |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 2996 | ObjCARCOpt::VisitBottomUp(BasicBlock *BB, |
| 2997 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 2998 | MapVector<Value *, RRInfo> &Retains) { |
| 2999 | bool NestingDetected = false; |
| 3000 | BBState &MyStates = BBStates[BB]; |
| 3001 | |
| 3002 | // Merge the states from each successor to compute the initial state |
| 3003 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 3004 | BBState::edge_iterator SI(MyStates.succ_begin()), |
| 3005 | SE(MyStates.succ_end()); |
| 3006 | if (SI != SE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3007 | const BasicBlock *Succ = *SI; |
| 3008 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); |
| 3009 | assert(I != BBStates.end()); |
| 3010 | MyStates.InitFromSucc(I->second); |
| 3011 | ++SI; |
| 3012 | for (; SI != SE; ++SI) { |
| 3013 | Succ = *SI; |
| 3014 | I = BBStates.find(Succ); |
| 3015 | assert(I != BBStates.end()); |
| 3016 | MyStates.MergeSucc(I->second); |
| 3017 | } |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 3018 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3019 | |
| 3020 | // Visit all the instructions, bottom-up. |
| 3021 | for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { |
| 3022 | Instruction *Inst = llvm::prior(I); |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 3023 | |
| 3024 | // Invoke instructions are visited as part of their successors (below). |
| 3025 | if (isa<InvokeInst>(Inst)) |
| 3026 | continue; |
| 3027 | |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 3028 | DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n"); |
| 3029 | |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 3030 | NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); |
| 3031 | } |
| 3032 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3033 | // If there's a predecessor with an invoke, visit the invoke as if it were |
| 3034 | // part of this block, since we can't insert code after an invoke in its own |
| 3035 | // block, and we don't want to split critical edges. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3036 | for (BBState::edge_iterator PI(MyStates.pred_begin()), |
| 3037 | PE(MyStates.pred_end()); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 3038 | BasicBlock *Pred = *PI; |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3039 | if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) |
| 3040 | NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3041 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3042 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3043 | return NestingDetected; |
| 3044 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3045 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3046 | bool |
| 3047 | ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, |
| 3048 | DenseMap<Value *, RRInfo> &Releases, |
| 3049 | BBState &MyStates) { |
| 3050 | bool NestingDetected = false; |
| 3051 | InstructionClass Class = GetInstructionClass(Inst); |
| 3052 | const Value *Arg = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3053 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3054 | switch (Class) { |
| 3055 | case IC_RetainBlock: |
| 3056 | // An objc_retainBlock call with just a use may need to be kept, |
| 3057 | // because it may be copying a block from the stack to the heap. |
| 3058 | if (!IsRetainBlockOptimizable(Inst)) |
| 3059 | break; |
| 3060 | // FALLTHROUGH |
| 3061 | case IC_Retain: |
| 3062 | case IC_RetainRV: { |
| 3063 | Arg = GetObjCArg(Inst); |
| 3064 | |
| 3065 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
| 3066 | |
| 3067 | // Don't do retain+release tracking for IC_RetainRV, because it's |
| 3068 | // better to let it remain as the first instruction after a call. |
| 3069 | if (Class != IC_RetainRV) { |
| 3070 | // 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] | 3071 | // 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] | 3072 | // hopefully eliminated the second retain, which may allow us to |
| 3073 | // eliminate the first retain too. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3074 | // Theoretically we could implement removal of nested retain+release |
| 3075 | // pairs by making PtrState hold a stack of states, but this is |
| 3076 | // simple and avoids adding overhead for the non-nested case. |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3077 | if (S.GetSeq() == S_Retain) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3078 | NestingDetected = true; |
| 3079 | |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 3080 | S.ResetSequenceProgress(S_Retain); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3081 | S.RRI.IsRetainBlock = Class == IC_RetainBlock; |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 3082 | S.RRI.KnownSafe = S.IsKnownIncremented(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3083 | S.RRI.Calls.insert(Inst); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3084 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3085 | |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 3086 | S.SetKnownPositiveRefCount(); |
Dan Gohman | f64ff8e | 2012-07-23 19:27:31 +0000 | [diff] [blame] | 3087 | |
| 3088 | // A retain can be a potential use; procede to the generic checking |
| 3089 | // code below. |
| 3090 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3091 | } |
| 3092 | case IC_Release: { |
| 3093 | Arg = GetObjCArg(Inst); |
| 3094 | |
| 3095 | PtrState &S = MyStates.getPtrTopDownState(Arg); |
Dan Gohman | df476e5 | 2012-09-04 23:16:20 +0000 | [diff] [blame] | 3096 | S.ClearRefCount(); |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3097 | |
| 3098 | switch (S.GetSeq()) { |
| 3099 | case S_Retain: |
| 3100 | case S_CanRelease: |
| 3101 | S.RRI.ReverseInsertPts.clear(); |
| 3102 | // FALL THROUGH |
| 3103 | case S_Use: |
| 3104 | S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); |
| 3105 | S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); |
| 3106 | Releases[Inst] = S.RRI; |
| 3107 | S.ClearSequenceProgress(); |
| 3108 | break; |
| 3109 | case S_None: |
| 3110 | break; |
| 3111 | case S_Stop: |
| 3112 | case S_Release: |
| 3113 | case S_MovableRelease: |
| 3114 | llvm_unreachable("top-down pointer in release state!"); |
| 3115 | } |
| 3116 | break; |
| 3117 | } |
| 3118 | case IC_AutoreleasepoolPop: |
| 3119 | // Conservatively, clear MyStates for all known pointers. |
| 3120 | MyStates.clearTopDownPointers(); |
| 3121 | return NestingDetected; |
| 3122 | case IC_AutoreleasepoolPush: |
| 3123 | case IC_None: |
| 3124 | // These are irrelevant. |
| 3125 | return NestingDetected; |
| 3126 | default: |
| 3127 | break; |
| 3128 | } |
| 3129 | |
| 3130 | // Consider any other possible effects of this instruction on each |
| 3131 | // pointer being tracked. |
| 3132 | for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(), |
| 3133 | ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) { |
| 3134 | const Value *Ptr = MI->first; |
| 3135 | if (Ptr == Arg) |
| 3136 | continue; // Handled above. |
| 3137 | PtrState &S = MI->second; |
| 3138 | Sequence Seq = S.GetSeq(); |
| 3139 | |
| 3140 | // Check for possible releases. |
| 3141 | if (CanAlterRefCount(Inst, Ptr, PA, Class)) { |
Dan Gohman | 62079b4 | 2012-04-25 00:50:46 +0000 | [diff] [blame] | 3142 | S.ClearRefCount(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3143 | switch (Seq) { |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3144 | case S_Retain: |
| 3145 | S.SetSeq(S_CanRelease); |
| 3146 | assert(S.RRI.ReverseInsertPts.empty()); |
| 3147 | S.RRI.ReverseInsertPts.insert(Inst); |
| 3148 | |
| 3149 | // One call can't cause a transition from S_Retain to S_CanRelease |
| 3150 | // and S_CanRelease to S_Use. If we've made the first transition, |
| 3151 | // we're done. |
| 3152 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3153 | case S_Use: |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3154 | case S_CanRelease: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3155 | case S_None: |
| 3156 | break; |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3157 | case S_Stop: |
| 3158 | case S_Release: |
| 3159 | case S_MovableRelease: |
| 3160 | llvm_unreachable("top-down pointer in release state!"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3161 | } |
| 3162 | } |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3163 | |
| 3164 | // Check for possible direct uses. |
| 3165 | switch (Seq) { |
| 3166 | case S_CanRelease: |
| 3167 | if (CanUse(Inst, Ptr, PA, Class)) |
| 3168 | S.SetSeq(S_Use); |
| 3169 | break; |
| 3170 | case S_Retain: |
| 3171 | case S_Use: |
| 3172 | case S_None: |
| 3173 | break; |
| 3174 | case S_Stop: |
| 3175 | case S_Release: |
| 3176 | case S_MovableRelease: |
| 3177 | llvm_unreachable("top-down pointer in release state!"); |
| 3178 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3179 | } |
| 3180 | |
| 3181 | return NestingDetected; |
| 3182 | } |
| 3183 | |
| 3184 | bool |
| 3185 | ObjCARCOpt::VisitTopDown(BasicBlock *BB, |
| 3186 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 3187 | DenseMap<Value *, RRInfo> &Releases) { |
| 3188 | bool NestingDetected = false; |
| 3189 | BBState &MyStates = BBStates[BB]; |
| 3190 | |
| 3191 | // Merge the states from each predecessor to compute the initial state |
| 3192 | // for the current block. |
Dan Gohman | 10c82ce | 2012-08-27 18:31:36 +0000 | [diff] [blame] | 3193 | BBState::edge_iterator PI(MyStates.pred_begin()), |
| 3194 | PE(MyStates.pred_end()); |
| 3195 | if (PI != PE) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3196 | const BasicBlock *Pred = *PI; |
| 3197 | DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); |
| 3198 | assert(I != BBStates.end()); |
| 3199 | MyStates.InitFromPred(I->second); |
| 3200 | ++PI; |
| 3201 | for (; PI != PE; ++PI) { |
| 3202 | Pred = *PI; |
| 3203 | I = BBStates.find(Pred); |
| 3204 | assert(I != BBStates.end()); |
| 3205 | MyStates.MergePred(I->second); |
| 3206 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3207 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3208 | |
| 3209 | // Visit all the instructions, top-down. |
| 3210 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 3211 | Instruction *Inst = I; |
Michael Gottesman | af2113f | 2013-01-13 07:00:51 +0000 | [diff] [blame] | 3212 | |
| 3213 | DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n"); |
| 3214 | |
Dan Gohman | 817a7c6 | 2012-03-22 18:24:56 +0000 | [diff] [blame] | 3215 | NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3216 | } |
| 3217 | |
| 3218 | CheckForCFGHazards(BB, BBStates, MyStates); |
| 3219 | return NestingDetected; |
| 3220 | } |
| 3221 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3222 | static void |
| 3223 | ComputePostOrders(Function &F, |
| 3224 | SmallVectorImpl<BasicBlock *> &PostOrder, |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3225 | SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, |
| 3226 | unsigned NoObjCARCExceptionsMDKind, |
| 3227 | DenseMap<const BasicBlock *, BBState> &BBStates) { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3228 | /// The visited set, for doing DFS walks. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3229 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 3230 | |
| 3231 | // Do DFS, computing the PostOrder. |
| 3232 | SmallPtrSet<BasicBlock *, 16> OnStack; |
| 3233 | SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3234 | |
| 3235 | // Functions always have exactly one entry block, and we don't have |
| 3236 | // any other block that we treat like an entry block. |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3237 | BasicBlock *EntryBB = &F.getEntryBlock(); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3238 | BBState &MyStates = BBStates[EntryBB]; |
| 3239 | MyStates.SetAsEntry(); |
| 3240 | TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back()); |
| 3241 | SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3242 | Visited.insert(EntryBB); |
| 3243 | OnStack.insert(EntryBB); |
| 3244 | do { |
| 3245 | dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3246 | BasicBlock *CurrBB = SuccStack.back().first; |
| 3247 | TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back()); |
| 3248 | succ_iterator SE(TI, false); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3249 | |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3250 | while (SuccStack.back().second != SE) { |
| 3251 | BasicBlock *SuccBB = *SuccStack.back().second++; |
| 3252 | if (Visited.insert(SuccBB)) { |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3253 | TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back()); |
| 3254 | SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI))); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3255 | BBStates[CurrBB].addSucc(SuccBB); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3256 | BBState &SuccStates = BBStates[SuccBB]; |
| 3257 | SuccStates.addPred(CurrBB); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3258 | OnStack.insert(SuccBB); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3259 | goto dfs_next_succ; |
| 3260 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3261 | |
| 3262 | if (!OnStack.count(SuccBB)) { |
| 3263 | BBStates[CurrBB].addSucc(SuccBB); |
| 3264 | BBStates[SuccBB].addPred(CurrBB); |
| 3265 | } |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3266 | } |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3267 | OnStack.erase(CurrBB); |
| 3268 | PostOrder.push_back(CurrBB); |
| 3269 | SuccStack.pop_back(); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3270 | } while (!SuccStack.empty()); |
| 3271 | |
| 3272 | Visited.clear(); |
| 3273 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3274 | // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3275 | // Functions may have many exits, and there also blocks which we treat |
| 3276 | // as exits due to ignored edges. |
| 3277 | SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; |
| 3278 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
| 3279 | BasicBlock *ExitBB = I; |
| 3280 | BBState &MyStates = BBStates[ExitBB]; |
| 3281 | if (!MyStates.isExit()) |
| 3282 | continue; |
| 3283 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3284 | MyStates.SetAsExit(); |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3285 | |
| 3286 | PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3287 | Visited.insert(ExitBB); |
| 3288 | while (!PredStack.empty()) { |
| 3289 | reverse_dfs_next_succ: |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3290 | BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); |
| 3291 | while (PredStack.back().second != PE) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3292 | BasicBlock *BB = *PredStack.back().second++; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3293 | if (Visited.insert(BB)) { |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3294 | PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3295 | goto reverse_dfs_next_succ; |
| 3296 | } |
| 3297 | } |
| 3298 | ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); |
| 3299 | } |
| 3300 | } |
| 3301 | } |
| 3302 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3303 | // Visit the function both top-down and bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3304 | bool |
| 3305 | ObjCARCOpt::Visit(Function &F, |
| 3306 | DenseMap<const BasicBlock *, BBState> &BBStates, |
| 3307 | MapVector<Value *, RRInfo> &Retains, |
| 3308 | DenseMap<Value *, RRInfo> &Releases) { |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3309 | |
| 3310 | // Use reverse-postorder traversals, because we magically know that loops |
| 3311 | // will be well behaved, i.e. they won't repeatedly call retain on a single |
| 3312 | // pointer without doing a release. We can't use the ReversePostOrderTraversal |
| 3313 | // class here because we want the reverse-CFG postorder to consider each |
| 3314 | // function exit point, and we want to ignore selected cycle edges. |
| 3315 | SmallVector<BasicBlock *, 16> PostOrder; |
| 3316 | SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; |
Dan Gohman | c24c66f | 2012-04-24 22:53:18 +0000 | [diff] [blame] | 3317 | ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, |
| 3318 | NoObjCARCExceptionsMDKind, |
| 3319 | BBStates); |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3320 | |
| 3321 | // Use reverse-postorder on the reverse CFG for bottom-up. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3322 | bool BottomUpNestingDetected = false; |
Dan Gohman | c57b58c | 2011-08-18 21:27:42 +0000 | [diff] [blame] | 3323 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3324 | ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend(); |
| 3325 | I != E; ++I) |
| 3326 | BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3327 | |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3328 | // Use reverse-postorder for top-down. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3329 | bool TopDownNestingDetected = false; |
Dan Gohman | a53a12c | 2011-12-12 19:42:25 +0000 | [diff] [blame] | 3330 | for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = |
| 3331 | PostOrder.rbegin(), E = PostOrder.rend(); |
| 3332 | I != E; ++I) |
| 3333 | TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3334 | |
| 3335 | return TopDownNestingDetected && BottomUpNestingDetected; |
| 3336 | } |
| 3337 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3338 | /// Move the calls in RetainsToMove and ReleasesToMove. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3339 | void ObjCARCOpt::MoveCalls(Value *Arg, |
| 3340 | RRInfo &RetainsToMove, |
| 3341 | RRInfo &ReleasesToMove, |
| 3342 | MapVector<Value *, RRInfo> &Retains, |
| 3343 | DenseMap<Value *, RRInfo> &Releases, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3344 | SmallVectorImpl<Instruction *> &DeadInsts, |
| 3345 | Module *M) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3346 | Type *ArgTy = Arg->getType(); |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3347 | Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3348 | |
| 3349 | // Insert the new retain and release calls. |
| 3350 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3351 | PI = ReleasesToMove.ReverseInsertPts.begin(), |
| 3352 | PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
| 3353 | Instruction *InsertPt = *PI; |
| 3354 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 3355 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 3356 | CallInst *Call = |
| 3357 | CallInst::Create(RetainsToMove.IsRetainBlock ? |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3358 | getRetainBlockCallee(M) : getRetainCallee(M), |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3359 | MyArg, "", InsertPt); |
| 3360 | Call->setDoesNotThrow(); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 3361 | if (RetainsToMove.IsRetainBlock) |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 3362 | Call->setMetadata(CopyOnEscapeMDKind, |
| 3363 | MDNode::get(M->getContext(), ArrayRef<Value *>())); |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 3364 | else |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3365 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 3366 | |
| 3367 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call |
| 3368 | << "\n" |
| 3369 | " At insertion point: " << *InsertPt |
| 3370 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3371 | } |
| 3372 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3373 | PI = RetainsToMove.ReverseInsertPts.begin(), |
| 3374 | PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) { |
Dan Gohman | 5c70fad | 2012-03-23 17:47:54 +0000 | [diff] [blame] | 3375 | Instruction *InsertPt = *PI; |
| 3376 | Value *MyArg = ArgTy == ParamTy ? Arg : |
| 3377 | new BitCastInst(Arg, ParamTy, "", InsertPt); |
| 3378 | CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg, |
| 3379 | "", InsertPt); |
| 3380 | // Attach a clang.imprecise_release metadata tag, if appropriate. |
| 3381 | if (MDNode *M = ReleasesToMove.ReleaseMetadata) |
| 3382 | Call->setMetadata(ImpreciseReleaseMDKind, M); |
| 3383 | Call->setDoesNotThrow(); |
| 3384 | if (ReleasesToMove.IsTailCallRelease) |
| 3385 | Call->setTailCall(); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 3386 | |
| 3387 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call |
| 3388 | << "\n" |
| 3389 | " At insertion point: " << *InsertPt |
| 3390 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3391 | } |
| 3392 | |
| 3393 | // Delete the original retain and release calls. |
| 3394 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3395 | AI = RetainsToMove.Calls.begin(), |
| 3396 | AE = RetainsToMove.Calls.end(); AI != AE; ++AI) { |
| 3397 | Instruction *OrigRetain = *AI; |
| 3398 | Retains.blot(OrigRetain); |
| 3399 | DeadInsts.push_back(OrigRetain); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 3400 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain << |
| 3401 | "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3402 | } |
| 3403 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3404 | AI = ReleasesToMove.Calls.begin(), |
| 3405 | AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) { |
| 3406 | Instruction *OrigRelease = *AI; |
| 3407 | Releases.erase(OrigRelease); |
| 3408 | DeadInsts.push_back(OrigRelease); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 3409 | DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease |
| 3410 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3411 | } |
| 3412 | } |
| 3413 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3414 | bool |
| 3415 | ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> |
| 3416 | &BBStates, |
| 3417 | MapVector<Value *, RRInfo> &Retains, |
| 3418 | DenseMap<Value *, RRInfo> &Releases, |
| 3419 | Module *M, |
| 3420 | SmallVector<Instruction *, 4> &NewRetains, |
| 3421 | SmallVector<Instruction *, 4> &NewReleases, |
| 3422 | SmallVector<Instruction *, 8> &DeadInsts, |
| 3423 | RRInfo &RetainsToMove, |
| 3424 | RRInfo &ReleasesToMove, |
| 3425 | Value *Arg, |
| 3426 | bool KnownSafe, |
| 3427 | bool &AnyPairsCompletelyEliminated) { |
| 3428 | // If a pair happens in a region where it is known that the reference count |
| 3429 | // is already incremented, we can similarly ignore possible decrements. |
| 3430 | bool KnownSafeTD = true, KnownSafeBU = true; |
| 3431 | |
| 3432 | // Connect the dots between the top-down-collected RetainsToMove and |
| 3433 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
| 3434 | // This is an iterative process so that we connect multiple releases |
| 3435 | // to multiple retains if needed. |
| 3436 | unsigned OldDelta = 0; |
| 3437 | unsigned NewDelta = 0; |
| 3438 | unsigned OldCount = 0; |
| 3439 | unsigned NewCount = 0; |
| 3440 | bool FirstRelease = true; |
| 3441 | bool FirstRetain = true; |
| 3442 | for (;;) { |
| 3443 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 3444 | NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) { |
| 3445 | Instruction *NewRetain = *NI; |
| 3446 | MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain); |
| 3447 | assert(It != Retains.end()); |
| 3448 | const RRInfo &NewRetainRRI = It->second; |
| 3449 | KnownSafeTD &= NewRetainRRI.KnownSafe; |
| 3450 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3451 | LI = NewRetainRRI.Calls.begin(), |
| 3452 | LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) { |
| 3453 | Instruction *NewRetainRelease = *LI; |
| 3454 | DenseMap<Value *, RRInfo>::const_iterator Jt = |
| 3455 | Releases.find(NewRetainRelease); |
| 3456 | if (Jt == Releases.end()) |
| 3457 | return false; |
| 3458 | const RRInfo &NewRetainReleaseRRI = Jt->second; |
| 3459 | assert(NewRetainReleaseRRI.Calls.count(NewRetain)); |
| 3460 | if (ReleasesToMove.Calls.insert(NewRetainRelease)) { |
| 3461 | OldDelta -= |
| 3462 | BBStates[NewRetainRelease->getParent()].GetAllPathCount(); |
| 3463 | |
| 3464 | // Merge the ReleaseMetadata and IsTailCallRelease values. |
| 3465 | if (FirstRelease) { |
| 3466 | ReleasesToMove.ReleaseMetadata = |
| 3467 | NewRetainReleaseRRI.ReleaseMetadata; |
| 3468 | ReleasesToMove.IsTailCallRelease = |
| 3469 | NewRetainReleaseRRI.IsTailCallRelease; |
| 3470 | FirstRelease = false; |
| 3471 | } else { |
| 3472 | if (ReleasesToMove.ReleaseMetadata != |
| 3473 | NewRetainReleaseRRI.ReleaseMetadata) |
| 3474 | ReleasesToMove.ReleaseMetadata = 0; |
| 3475 | if (ReleasesToMove.IsTailCallRelease != |
| 3476 | NewRetainReleaseRRI.IsTailCallRelease) |
| 3477 | ReleasesToMove.IsTailCallRelease = false; |
| 3478 | } |
| 3479 | |
| 3480 | // Collect the optimal insertion points. |
| 3481 | if (!KnownSafe) |
| 3482 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3483 | RI = NewRetainReleaseRRI.ReverseInsertPts.begin(), |
| 3484 | RE = NewRetainReleaseRRI.ReverseInsertPts.end(); |
| 3485 | RI != RE; ++RI) { |
| 3486 | Instruction *RIP = *RI; |
| 3487 | if (ReleasesToMove.ReverseInsertPts.insert(RIP)) |
| 3488 | NewDelta -= BBStates[RIP->getParent()].GetAllPathCount(); |
| 3489 | } |
| 3490 | NewReleases.push_back(NewRetainRelease); |
| 3491 | } |
| 3492 | } |
| 3493 | } |
| 3494 | NewRetains.clear(); |
| 3495 | if (NewReleases.empty()) break; |
| 3496 | |
| 3497 | // Back the other way. |
| 3498 | for (SmallVectorImpl<Instruction *>::const_iterator |
| 3499 | NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) { |
| 3500 | Instruction *NewRelease = *NI; |
| 3501 | DenseMap<Value *, RRInfo>::const_iterator It = |
| 3502 | Releases.find(NewRelease); |
| 3503 | assert(It != Releases.end()); |
| 3504 | const RRInfo &NewReleaseRRI = It->second; |
| 3505 | KnownSafeBU &= NewReleaseRRI.KnownSafe; |
| 3506 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3507 | LI = NewReleaseRRI.Calls.begin(), |
| 3508 | LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) { |
| 3509 | Instruction *NewReleaseRetain = *LI; |
| 3510 | MapVector<Value *, RRInfo>::const_iterator Jt = |
| 3511 | Retains.find(NewReleaseRetain); |
| 3512 | if (Jt == Retains.end()) |
| 3513 | return false; |
| 3514 | const RRInfo &NewReleaseRetainRRI = Jt->second; |
| 3515 | assert(NewReleaseRetainRRI.Calls.count(NewRelease)); |
| 3516 | if (RetainsToMove.Calls.insert(NewReleaseRetain)) { |
| 3517 | unsigned PathCount = |
| 3518 | BBStates[NewReleaseRetain->getParent()].GetAllPathCount(); |
| 3519 | OldDelta += PathCount; |
| 3520 | OldCount += PathCount; |
| 3521 | |
| 3522 | // Merge the IsRetainBlock values. |
| 3523 | if (FirstRetain) { |
| 3524 | RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock; |
| 3525 | FirstRetain = false; |
| 3526 | } else if (ReleasesToMove.IsRetainBlock != |
| 3527 | NewReleaseRetainRRI.IsRetainBlock) |
| 3528 | // It's not possible to merge the sequences if one uses |
| 3529 | // objc_retain and the other uses objc_retainBlock. |
| 3530 | return false; |
| 3531 | |
| 3532 | // Collect the optimal insertion points. |
| 3533 | if (!KnownSafe) |
| 3534 | for (SmallPtrSet<Instruction *, 2>::const_iterator |
| 3535 | RI = NewReleaseRetainRRI.ReverseInsertPts.begin(), |
| 3536 | RE = NewReleaseRetainRRI.ReverseInsertPts.end(); |
| 3537 | RI != RE; ++RI) { |
| 3538 | Instruction *RIP = *RI; |
| 3539 | if (RetainsToMove.ReverseInsertPts.insert(RIP)) { |
| 3540 | PathCount = BBStates[RIP->getParent()].GetAllPathCount(); |
| 3541 | NewDelta += PathCount; |
| 3542 | NewCount += PathCount; |
| 3543 | } |
| 3544 | } |
| 3545 | NewRetains.push_back(NewReleaseRetain); |
| 3546 | } |
| 3547 | } |
| 3548 | } |
| 3549 | NewReleases.clear(); |
| 3550 | if (NewRetains.empty()) break; |
| 3551 | } |
| 3552 | |
| 3553 | // If the pointer is known incremented or nested, we can safely delete the |
| 3554 | // pair regardless of what's between them. |
| 3555 | if (KnownSafeTD || KnownSafeBU) { |
| 3556 | RetainsToMove.ReverseInsertPts.clear(); |
| 3557 | ReleasesToMove.ReverseInsertPts.clear(); |
| 3558 | NewCount = 0; |
| 3559 | } else { |
| 3560 | // Determine whether the new insertion points we computed preserve the |
| 3561 | // balance of retain and release calls through the program. |
| 3562 | // TODO: If the fully aggressive solution isn't valid, try to find a |
| 3563 | // less aggressive solution which is. |
| 3564 | if (NewDelta != 0) |
| 3565 | return false; |
| 3566 | } |
| 3567 | |
| 3568 | // Determine whether the original call points are balanced in the retain and |
| 3569 | // release calls through the program. If not, conservatively don't touch |
| 3570 | // them. |
| 3571 | // TODO: It's theoretically possible to do code motion in this case, as |
| 3572 | // long as the existing imbalances are maintained. |
| 3573 | if (OldDelta != 0) |
| 3574 | return false; |
| 3575 | |
| 3576 | Changed = true; |
| 3577 | assert(OldCount != 0 && "Unreachable code?"); |
| 3578 | NumRRs += OldCount - NewCount; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3579 | // Set to true if we completely removed any RR pairs. |
Michael Gottesman | 8b5515f | 2013-01-22 21:53:43 +0000 | [diff] [blame^] | 3580 | AnyPairsCompletelyEliminated = NewCount == 0; |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3581 | |
| 3582 | // We can move calls! |
| 3583 | return true; |
| 3584 | } |
| 3585 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3586 | /// Identify pairings between the retains and releases, and delete and/or move |
| 3587 | /// them. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3588 | bool |
| 3589 | ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState> |
| 3590 | &BBStates, |
| 3591 | MapVector<Value *, RRInfo> &Retains, |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3592 | DenseMap<Value *, RRInfo> &Releases, |
| 3593 | Module *M) { |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3594 | bool AnyPairsCompletelyEliminated = false; |
| 3595 | RRInfo RetainsToMove; |
| 3596 | RRInfo ReleasesToMove; |
| 3597 | SmallVector<Instruction *, 4> NewRetains; |
| 3598 | SmallVector<Instruction *, 4> NewReleases; |
| 3599 | SmallVector<Instruction *, 8> DeadInsts; |
| 3600 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3601 | // Visit each retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3602 | for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), |
Dan Gohman | 2053a5d | 2011-09-29 22:25:23 +0000 | [diff] [blame] | 3603 | E = Retains.end(); I != E; ++I) { |
| 3604 | Value *V = I->first; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3605 | if (!V) continue; // blotted |
| 3606 | |
| 3607 | Instruction *Retain = cast<Instruction>(V); |
Michael Gottesman | c189a39 | 2013-01-09 19:23:24 +0000 | [diff] [blame] | 3608 | |
| 3609 | DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain |
| 3610 | << "\n"); |
| 3611 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3612 | Value *Arg = GetObjCArg(Retain); |
| 3613 | |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 3614 | // 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] | 3615 | // not being managed by ObjC reference counting, so we can delete pairs |
| 3616 | // regardless of what possible decrements or uses lie between them. |
Dan Gohman | 728db49 | 2012-01-13 00:39:07 +0000 | [diff] [blame] | 3617 | bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3618 | |
Dan Gohman | 56e1cef | 2011-08-22 17:29:11 +0000 | [diff] [blame] | 3619 | // A constant pointer can't be pointing to an object on the heap. It may |
| 3620 | // be reference-counted, but it won't be deleted. |
| 3621 | if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) |
| 3622 | if (const GlobalVariable *GV = |
| 3623 | dyn_cast<GlobalVariable>( |
| 3624 | StripPointerCastsAndObjCCalls(LI->getPointerOperand()))) |
| 3625 | if (GV->isConstant()) |
| 3626 | KnownSafe = true; |
| 3627 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3628 | // Connect the dots between the top-down-collected RetainsToMove and |
| 3629 | // bottom-up-collected ReleasesToMove to form sets of related calls. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3630 | NewRetains.push_back(Retain); |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3631 | bool PerformMoveCalls = |
| 3632 | ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains, |
| 3633 | NewReleases, DeadInsts, RetainsToMove, |
| 3634 | ReleasesToMove, Arg, KnownSafe, |
| 3635 | AnyPairsCompletelyEliminated); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3636 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3637 | if (PerformMoveCalls) { |
| 3638 | // Ok, everything checks out and we're all set. Let's move/delete some |
| 3639 | // code! |
| 3640 | MoveCalls(Arg, RetainsToMove, ReleasesToMove, |
| 3641 | Retains, Releases, DeadInsts, M); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3642 | } |
| 3643 | |
Michael Gottesman | 9de6f96 | 2013-01-22 21:49:00 +0000 | [diff] [blame] | 3644 | // Clean up state for next retain. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3645 | NewReleases.clear(); |
| 3646 | NewRetains.clear(); |
| 3647 | RetainsToMove.clear(); |
| 3648 | ReleasesToMove.clear(); |
| 3649 | } |
| 3650 | |
| 3651 | // Now that we're done moving everything, we can delete the newly dead |
| 3652 | // instructions, as we no longer need them as insert points. |
| 3653 | while (!DeadInsts.empty()) |
| 3654 | EraseInstruction(DeadInsts.pop_back_val()); |
| 3655 | |
| 3656 | return AnyPairsCompletelyEliminated; |
| 3657 | } |
| 3658 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3659 | /// Weak pointer optimizations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3660 | void ObjCARCOpt::OptimizeWeakCalls(Function &F) { |
| 3661 | // First, do memdep-style RLE and S2L optimizations. We can't use memdep |
| 3662 | // itself because it uses AliasAnalysis and we need to do provenance |
| 3663 | // queries instead. |
| 3664 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 3665 | Instruction *Inst = &*I++; |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3666 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3667 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst << |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3668 | "\n"); |
| 3669 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3670 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 3671 | if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained) |
| 3672 | continue; |
| 3673 | |
| 3674 | // Delete objc_loadWeak calls with no users. |
| 3675 | if (Class == IC_LoadWeak && Inst->use_empty()) { |
| 3676 | Inst->eraseFromParent(); |
| 3677 | continue; |
| 3678 | } |
| 3679 | |
| 3680 | // TODO: For now, just look for an earlier available version of this value |
| 3681 | // within the same block. Theoretically, we could do memdep-style non-local |
| 3682 | // analysis too, but that would want caching. A better approach would be to |
| 3683 | // use the technique that EarlyCSE uses. |
| 3684 | inst_iterator Current = llvm::prior(I); |
| 3685 | BasicBlock *CurrentBB = Current.getBasicBlockIterator(); |
| 3686 | for (BasicBlock::iterator B = CurrentBB->begin(), |
| 3687 | J = Current.getInstructionIterator(); |
| 3688 | J != B; --J) { |
| 3689 | Instruction *EarlierInst = &*llvm::prior(J); |
| 3690 | InstructionClass EarlierClass = GetInstructionClass(EarlierInst); |
| 3691 | switch (EarlierClass) { |
| 3692 | case IC_LoadWeak: |
| 3693 | case IC_LoadWeakRetained: { |
| 3694 | // If this is loading from the same pointer, replace this load's value |
| 3695 | // with that one. |
| 3696 | CallInst *Call = cast<CallInst>(Inst); |
| 3697 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 3698 | Value *Arg = Call->getArgOperand(0); |
| 3699 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 3700 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 3701 | case AliasAnalysis::MustAlias: |
| 3702 | Changed = true; |
| 3703 | // If the load has a builtin retain, insert a plain retain for it. |
| 3704 | if (Class == IC_LoadWeakRetained) { |
| 3705 | CallInst *CI = |
| 3706 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 3707 | "", Call); |
| 3708 | CI->setTailCall(); |
| 3709 | } |
| 3710 | // Zap the fully redundant load. |
| 3711 | Call->replaceAllUsesWith(EarlierCall); |
| 3712 | Call->eraseFromParent(); |
| 3713 | goto clobbered; |
| 3714 | case AliasAnalysis::MayAlias: |
| 3715 | case AliasAnalysis::PartialAlias: |
| 3716 | goto clobbered; |
| 3717 | case AliasAnalysis::NoAlias: |
| 3718 | break; |
| 3719 | } |
| 3720 | break; |
| 3721 | } |
| 3722 | case IC_StoreWeak: |
| 3723 | case IC_InitWeak: { |
| 3724 | // If this is storing to the same pointer and has the same size etc. |
| 3725 | // replace this load's value with the stored value. |
| 3726 | CallInst *Call = cast<CallInst>(Inst); |
| 3727 | CallInst *EarlierCall = cast<CallInst>(EarlierInst); |
| 3728 | Value *Arg = Call->getArgOperand(0); |
| 3729 | Value *EarlierArg = EarlierCall->getArgOperand(0); |
| 3730 | switch (PA.getAA()->alias(Arg, EarlierArg)) { |
| 3731 | case AliasAnalysis::MustAlias: |
| 3732 | Changed = true; |
| 3733 | // If the load has a builtin retain, insert a plain retain for it. |
| 3734 | if (Class == IC_LoadWeakRetained) { |
| 3735 | CallInst *CI = |
| 3736 | CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, |
| 3737 | "", Call); |
| 3738 | CI->setTailCall(); |
| 3739 | } |
| 3740 | // Zap the fully redundant load. |
| 3741 | Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); |
| 3742 | Call->eraseFromParent(); |
| 3743 | goto clobbered; |
| 3744 | case AliasAnalysis::MayAlias: |
| 3745 | case AliasAnalysis::PartialAlias: |
| 3746 | goto clobbered; |
| 3747 | case AliasAnalysis::NoAlias: |
| 3748 | break; |
| 3749 | } |
| 3750 | break; |
| 3751 | } |
| 3752 | case IC_MoveWeak: |
| 3753 | case IC_CopyWeak: |
| 3754 | // TOOD: Grab the copied value. |
| 3755 | goto clobbered; |
| 3756 | case IC_AutoreleasepoolPush: |
| 3757 | case IC_None: |
| 3758 | case IC_User: |
| 3759 | // Weak pointers are only modified through the weak entry points |
| 3760 | // (and arbitrary calls, which could call the weak entry points). |
| 3761 | break; |
| 3762 | default: |
| 3763 | // Anything else could modify the weak pointer. |
| 3764 | goto clobbered; |
| 3765 | } |
| 3766 | } |
| 3767 | clobbered:; |
| 3768 | } |
| 3769 | |
| 3770 | // Then, for each destroyWeak with an alloca operand, check to see if |
| 3771 | // the alloca and all its users can be zapped. |
| 3772 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 3773 | Instruction *Inst = &*I++; |
| 3774 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 3775 | if (Class != IC_DestroyWeak) |
| 3776 | continue; |
| 3777 | |
| 3778 | CallInst *Call = cast<CallInst>(Inst); |
| 3779 | Value *Arg = Call->getArgOperand(0); |
| 3780 | if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { |
| 3781 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 3782 | UE = Alloca->use_end(); UI != UE; ++UI) { |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3783 | const Instruction *UserInst = cast<Instruction>(*UI); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3784 | switch (GetBasicInstructionClass(UserInst)) { |
| 3785 | case IC_InitWeak: |
| 3786 | case IC_StoreWeak: |
| 3787 | case IC_DestroyWeak: |
| 3788 | continue; |
| 3789 | default: |
| 3790 | goto done; |
| 3791 | } |
| 3792 | } |
| 3793 | Changed = true; |
| 3794 | for (Value::use_iterator UI = Alloca->use_begin(), |
| 3795 | UE = Alloca->use_end(); UI != UE; ) { |
| 3796 | CallInst *UserInst = cast<CallInst>(*UI++); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 3797 | switch (GetBasicInstructionClass(UserInst)) { |
| 3798 | case IC_InitWeak: |
| 3799 | case IC_StoreWeak: |
| 3800 | // These functions return their second argument. |
| 3801 | UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); |
| 3802 | break; |
| 3803 | case IC_DestroyWeak: |
| 3804 | // No return value. |
| 3805 | break; |
| 3806 | default: |
Dan Gohman | 9c97eea0 | 2012-05-21 17:41:28 +0000 | [diff] [blame] | 3807 | llvm_unreachable("alloca really is used!"); |
Dan Gohman | 14862c3 | 2012-05-18 22:17:29 +0000 | [diff] [blame] | 3808 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3809 | UserInst->eraseFromParent(); |
| 3810 | } |
| 3811 | Alloca->eraseFromParent(); |
| 3812 | done:; |
| 3813 | } |
| 3814 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3815 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3816 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3817 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3818 | } |
| 3819 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3820 | /// Identify program paths which execute sequences of retains and releases which |
| 3821 | /// can be eliminated. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3822 | bool ObjCARCOpt::OptimizeSequences(Function &F) { |
| 3823 | /// Releases, Retains - These are used to store the results of the main flow |
| 3824 | /// analysis. These use Value* as the key instead of Instruction* so that the |
| 3825 | /// map stays valid when we get around to rewriting code and calls get |
| 3826 | /// replaced by arguments. |
| 3827 | DenseMap<Value *, RRInfo> Releases; |
| 3828 | MapVector<Value *, RRInfo> Retains; |
| 3829 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3830 | /// This is used during the traversal of the function to track the |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3831 | /// states for each identified object at each block. |
| 3832 | DenseMap<const BasicBlock *, BBState> BBStates; |
| 3833 | |
| 3834 | // Analyze the CFG of the function, and all instructions. |
| 3835 | bool NestingDetected = Visit(F, BBStates, Retains, Releases); |
| 3836 | |
| 3837 | // Transform. |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3838 | return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) && |
| 3839 | NestingDetected; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3840 | } |
| 3841 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 3842 | /// Look for this pattern: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3843 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3844 | /// %call = call i8* @something(...) |
| 3845 | /// %2 = call i8* @objc_retain(i8* %call) |
| 3846 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 3847 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3848 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3849 | /// And delete the retain and autorelease. |
| 3850 | /// |
| 3851 | /// Otherwise if it's just this: |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3852 | /// \code |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3853 | /// %3 = call i8* @objc_autorelease(i8* %2) |
| 3854 | /// ret i8* %3 |
Dmitri Gribenko | 5485acd | 2012-09-14 14:57:36 +0000 | [diff] [blame] | 3855 | /// \endcode |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3856 | /// convert the autorelease to autoreleaseRV. |
| 3857 | void ObjCARCOpt::OptimizeReturns(Function &F) { |
| 3858 | if (!F.getReturnType()->isPointerTy()) |
| 3859 | return; |
| 3860 | |
| 3861 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 3862 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 3863 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { |
| 3864 | BasicBlock *BB = FI; |
| 3865 | ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back()); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3866 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3867 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 3868 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3869 | if (!Ret) continue; |
| 3870 | |
| 3871 | const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0)); |
| 3872 | FindDependencies(NeedsPositiveRetainCount, Arg, |
| 3873 | BB, Ret, DependingInstructions, Visited, PA); |
| 3874 | if (DependingInstructions.size() != 1) |
| 3875 | goto next_block; |
| 3876 | |
| 3877 | { |
| 3878 | CallInst *Autorelease = |
| 3879 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3880 | if (!Autorelease) |
| 3881 | goto next_block; |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 3882 | InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3883 | if (!IsAutorelease(AutoreleaseClass)) |
| 3884 | goto next_block; |
| 3885 | if (GetObjCArg(Autorelease) != Arg) |
| 3886 | goto next_block; |
| 3887 | |
| 3888 | DependingInstructions.clear(); |
| 3889 | Visited.clear(); |
| 3890 | |
| 3891 | // Check that there is nothing that can affect the reference |
| 3892 | // count between the autorelease and the retain. |
| 3893 | FindDependencies(CanChangeRetainCount, Arg, |
| 3894 | BB, Autorelease, DependingInstructions, Visited, PA); |
| 3895 | if (DependingInstructions.size() != 1) |
| 3896 | goto next_block; |
| 3897 | |
| 3898 | { |
| 3899 | CallInst *Retain = |
| 3900 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3901 | |
| 3902 | // Check that we found a retain with the same argument. |
| 3903 | if (!Retain || |
| 3904 | !IsRetain(GetBasicInstructionClass(Retain)) || |
| 3905 | GetObjCArg(Retain) != Arg) |
| 3906 | goto next_block; |
| 3907 | |
| 3908 | DependingInstructions.clear(); |
| 3909 | Visited.clear(); |
| 3910 | |
| 3911 | // Convert the autorelease to an autoreleaseRV, since it's |
| 3912 | // returning the value. |
| 3913 | if (AutoreleaseClass == IC_Autorelease) { |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 3914 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease " |
| 3915 | "=> autoreleaseRV since it's returning a value.\n" |
| 3916 | " In: " << *Autorelease |
| 3917 | << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3918 | Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent())); |
Michael Gottesman | a6cb018 | 2013-01-10 02:03:50 +0000 | [diff] [blame] | 3919 | DEBUG(dbgs() << " Out: " << *Autorelease |
| 3920 | << "\n"); |
Michael Gottesman | c9656fa | 2013-01-12 01:25:15 +0000 | [diff] [blame] | 3921 | Autorelease->setTailCall(); // Always tail call autoreleaseRV. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3922 | AutoreleaseClass = IC_AutoreleaseRV; |
| 3923 | } |
| 3924 | |
| 3925 | // Check that there is nothing that can affect the reference |
| 3926 | // count between the retain and the call. |
Dan Gohman | 4ac148d | 2011-09-29 22:27:34 +0000 | [diff] [blame] | 3927 | // Note that Retain need not be in BB. |
| 3928 | FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3929 | DependingInstructions, Visited, PA); |
| 3930 | if (DependingInstructions.size() != 1) |
| 3931 | goto next_block; |
| 3932 | |
| 3933 | { |
| 3934 | CallInst *Call = |
| 3935 | dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 3936 | |
| 3937 | // Check that the pointer is the return value of the call. |
| 3938 | if (!Call || Arg != Call) |
| 3939 | goto next_block; |
| 3940 | |
| 3941 | // Check that the call is a regular call. |
| 3942 | InstructionClass Class = GetBasicInstructionClass(Call); |
| 3943 | if (Class != IC_CallOrUser && Class != IC_Call) |
| 3944 | goto next_block; |
| 3945 | |
| 3946 | // If so, we can zap the retain and autorelease. |
| 3947 | Changed = true; |
| 3948 | ++NumRets; |
Michael Gottesman | d61a3b2 | 2013-01-07 00:04:56 +0000 | [diff] [blame] | 3949 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain |
| 3950 | << "\n Erasing: " |
| 3951 | << *Autorelease << "\n"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3952 | EraseInstruction(Retain); |
| 3953 | EraseInstruction(Autorelease); |
| 3954 | } |
| 3955 | } |
| 3956 | } |
| 3957 | |
| 3958 | next_block: |
| 3959 | DependingInstructions.clear(); |
| 3960 | Visited.clear(); |
| 3961 | } |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3962 | |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 3963 | DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 3964 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3965 | } |
| 3966 | |
| 3967 | bool ObjCARCOpt::doInitialization(Module &M) { |
| 3968 | if (!EnableARCOpts) |
| 3969 | return false; |
| 3970 | |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 3971 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 3972 | Run = ModuleHasARC(M); |
| 3973 | if (!Run) |
| 3974 | return false; |
| 3975 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3976 | // Identify the imprecise release metadata kind. |
| 3977 | ImpreciseReleaseMDKind = |
| 3978 | M.getContext().getMDKindID("clang.imprecise_release"); |
Dan Gohman | a7107f9 | 2011-10-17 22:53:25 +0000 | [diff] [blame] | 3979 | CopyOnEscapeMDKind = |
| 3980 | M.getContext().getMDKindID("clang.arc.copy_on_escape"); |
Dan Gohman | 0155f30 | 2012-02-17 18:59:53 +0000 | [diff] [blame] | 3981 | NoObjCARCExceptionsMDKind = |
| 3982 | M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions"); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3983 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3984 | // Intuitively, objc_retain and others are nocapture, however in practice |
| 3985 | // they are not, because they return their argument value. And objc_release |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 3986 | // calls finalizers which can have arbitrary side effects. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3987 | |
| 3988 | // These are initialized lazily. |
| 3989 | RetainRVCallee = 0; |
| 3990 | AutoreleaseRVCallee = 0; |
| 3991 | ReleaseCallee = 0; |
| 3992 | RetainCallee = 0; |
Dan Gohman | 6320f52 | 2011-07-22 22:29:21 +0000 | [diff] [blame] | 3993 | RetainBlockCallee = 0; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 3994 | AutoreleaseCallee = 0; |
| 3995 | |
| 3996 | return false; |
| 3997 | } |
| 3998 | |
| 3999 | bool ObjCARCOpt::runOnFunction(Function &F) { |
| 4000 | if (!EnableARCOpts) |
| 4001 | return false; |
| 4002 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 4003 | // If nothing in the Module uses ARC, don't do anything. |
| 4004 | if (!Run) |
| 4005 | return false; |
| 4006 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4007 | Changed = false; |
| 4008 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 4009 | DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n"); |
| 4010 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4011 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 4012 | |
| 4013 | // This pass performs several distinct transformations. As a compile-time aid |
| 4014 | // when compiling code that isn't ObjC, skip these if the relevant ObjC |
| 4015 | // library functions aren't declared. |
| 4016 | |
| 4017 | // Preliminary optimizations. This also computs UsedInThisFunction. |
| 4018 | OptimizeIndividualCalls(F); |
| 4019 | |
| 4020 | // Optimizations for weak pointers. |
| 4021 | if (UsedInThisFunction & ((1 << IC_LoadWeak) | |
| 4022 | (1 << IC_LoadWeakRetained) | |
| 4023 | (1 << IC_StoreWeak) | |
| 4024 | (1 << IC_InitWeak) | |
| 4025 | (1 << IC_CopyWeak) | |
| 4026 | (1 << IC_MoveWeak) | |
| 4027 | (1 << IC_DestroyWeak))) |
| 4028 | OptimizeWeakCalls(F); |
| 4029 | |
| 4030 | // Optimizations for retain+release pairs. |
| 4031 | if (UsedInThisFunction & ((1 << IC_Retain) | |
| 4032 | (1 << IC_RetainRV) | |
| 4033 | (1 << IC_RetainBlock))) |
| 4034 | if (UsedInThisFunction & (1 << IC_Release)) |
| 4035 | // Run OptimizeSequences until it either stops making changes or |
| 4036 | // no retain+release pair nesting is detected. |
| 4037 | while (OptimizeSequences(F)) {} |
| 4038 | |
| 4039 | // Optimizations if objc_autorelease is used. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4040 | if (UsedInThisFunction & ((1 << IC_Autorelease) | |
| 4041 | (1 << IC_AutoreleaseRV))) |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4042 | OptimizeReturns(F); |
| 4043 | |
Michael Gottesman | b24bdef | 2013-01-12 02:57:16 +0000 | [diff] [blame] | 4044 | DEBUG(dbgs() << "\n"); |
| 4045 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4046 | return Changed; |
| 4047 | } |
| 4048 | |
| 4049 | void ObjCARCOpt::releaseMemory() { |
| 4050 | PA.clear(); |
| 4051 | } |
| 4052 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4053 | /// @} |
| 4054 | /// |
| 4055 | /// \defgroup ARCContract ARC Contraction. |
| 4056 | /// @{ |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4057 | |
| 4058 | // TODO: ObjCARCContract could insert PHI nodes when uses aren't |
| 4059 | // dominated by single calls. |
| 4060 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4061 | #include "llvm/Analysis/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 4062 | #include "llvm/IR/InlineAsm.h" |
| 4063 | #include "llvm/IR/Operator.h" |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4064 | |
| 4065 | STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed"); |
| 4066 | |
| 4067 | namespace { |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4068 | /// \brief Late ARC optimizations |
| 4069 | /// |
| 4070 | /// These change the IR in a way that makes it difficult to be analyzed by |
| 4071 | /// ObjCARCOpt, so it's run late. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4072 | class ObjCARCContract : public FunctionPass { |
| 4073 | bool Changed; |
| 4074 | AliasAnalysis *AA; |
| 4075 | DominatorTree *DT; |
| 4076 | ProvenanceAnalysis PA; |
| 4077 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4078 | /// A flag indicating whether this optimization pass should run. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 4079 | bool Run; |
| 4080 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4081 | /// Declarations for ObjC runtime functions, for use in creating calls to |
| 4082 | /// them. These are initialized lazily to avoid cluttering up the Module |
| 4083 | /// with unused declarations. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4084 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4085 | /// Declaration for objc_storeStrong(). |
| 4086 | Constant *StoreStrongCallee; |
| 4087 | /// Declaration for objc_retainAutorelease(). |
| 4088 | Constant *RetainAutoreleaseCallee; |
| 4089 | /// Declaration for objc_retainAutoreleaseReturnValue(). |
| 4090 | Constant *RetainAutoreleaseRVCallee; |
| 4091 | |
| 4092 | /// The inline asm string to insert between calls and RetainRV calls to make |
| 4093 | /// the optimization work on targets which need it. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4094 | const MDString *RetainRVMarker; |
| 4095 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4096 | /// The set of inserted objc_storeStrong calls. If at the end of walking the |
| 4097 | /// function we have found no alloca instructions, these calls can be marked |
| 4098 | /// "tail". |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4099 | SmallPtrSet<CallInst *, 8> StoreStrongCalls; |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4100 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4101 | Constant *getStoreStrongCallee(Module *M); |
| 4102 | Constant *getRetainAutoreleaseCallee(Module *M); |
| 4103 | Constant *getRetainAutoreleaseRVCallee(Module *M); |
| 4104 | |
| 4105 | bool ContractAutorelease(Function &F, Instruction *Autorelease, |
| 4106 | InstructionClass Class, |
| 4107 | SmallPtrSet<Instruction *, 4> |
| 4108 | &DependingInstructions, |
| 4109 | SmallPtrSet<const BasicBlock *, 4> |
| 4110 | &Visited); |
| 4111 | |
| 4112 | void ContractRelease(Instruction *Release, |
| 4113 | inst_iterator &Iter); |
| 4114 | |
| 4115 | virtual void getAnalysisUsage(AnalysisUsage &AU) const; |
| 4116 | virtual bool doInitialization(Module &M); |
| 4117 | virtual bool runOnFunction(Function &F); |
| 4118 | |
| 4119 | public: |
| 4120 | static char ID; |
| 4121 | ObjCARCContract() : FunctionPass(ID) { |
| 4122 | initializeObjCARCContractPass(*PassRegistry::getPassRegistry()); |
| 4123 | } |
| 4124 | }; |
| 4125 | } |
| 4126 | |
| 4127 | char ObjCARCContract::ID = 0; |
| 4128 | INITIALIZE_PASS_BEGIN(ObjCARCContract, |
| 4129 | "objc-arc-contract", "ObjC ARC contraction", false, false) |
| 4130 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 4131 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
| 4132 | INITIALIZE_PASS_END(ObjCARCContract, |
| 4133 | "objc-arc-contract", "ObjC ARC contraction", false, false) |
| 4134 | |
| 4135 | Pass *llvm::createObjCARCContractPass() { |
| 4136 | return new ObjCARCContract(); |
| 4137 | } |
| 4138 | |
| 4139 | void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const { |
| 4140 | AU.addRequired<AliasAnalysis>(); |
| 4141 | AU.addRequired<DominatorTree>(); |
| 4142 | AU.setPreservesCFG(); |
| 4143 | } |
| 4144 | |
| 4145 | Constant *ObjCARCContract::getStoreStrongCallee(Module *M) { |
| 4146 | if (!StoreStrongCallee) { |
| 4147 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 4148 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 4149 | Type *I8XX = PointerType::getUnqual(I8X); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4150 | Type *Params[] = { I8XX, I8X }; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4151 | |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 4152 | AttributeSet Attr = AttributeSet() |
| 4153 | .addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 4154 | Attribute::NoUnwind) |
| 4155 | .addAttribute(M->getContext(), 1, Attribute::NoCapture); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4156 | |
| 4157 | StoreStrongCallee = |
| 4158 | M->getOrInsertFunction( |
| 4159 | "objc_storeStrong", |
| 4160 | FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 4161 | Attr); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4162 | } |
| 4163 | return StoreStrongCallee; |
| 4164 | } |
| 4165 | |
| 4166 | Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) { |
| 4167 | if (!RetainAutoreleaseCallee) { |
| 4168 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 4169 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4170 | Type *Params[] = { I8X }; |
| 4171 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 4172 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 4173 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 4174 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4175 | RetainAutoreleaseCallee = |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 4176 | M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4177 | } |
| 4178 | return RetainAutoreleaseCallee; |
| 4179 | } |
| 4180 | |
| 4181 | Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) { |
| 4182 | if (!RetainAutoreleaseRVCallee) { |
| 4183 | LLVMContext &C = M->getContext(); |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 4184 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4185 | Type *Params[] = { I8X }; |
| 4186 | FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false); |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 4187 | AttributeSet Attribute = |
Bill Wendling | 09175b3 | 2013-01-22 21:15:51 +0000 | [diff] [blame] | 4188 | AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex, |
| 4189 | Attribute::NoUnwind); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4190 | RetainAutoreleaseRVCallee = |
| 4191 | M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy, |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 4192 | Attribute); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4193 | } |
| 4194 | return RetainAutoreleaseRVCallee; |
| 4195 | } |
| 4196 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4197 | /// Merge an autorelease with a retain into a fused call. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4198 | bool |
| 4199 | ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease, |
| 4200 | InstructionClass Class, |
| 4201 | SmallPtrSet<Instruction *, 4> |
| 4202 | &DependingInstructions, |
| 4203 | SmallPtrSet<const BasicBlock *, 4> |
| 4204 | &Visited) { |
| 4205 | const Value *Arg = GetObjCArg(Autorelease); |
| 4206 | |
| 4207 | // Check that there are no instructions between the retain and the autorelease |
| 4208 | // (such as an autorelease_pop) which may change the count. |
| 4209 | CallInst *Retain = 0; |
| 4210 | if (Class == IC_AutoreleaseRV) |
| 4211 | FindDependencies(RetainAutoreleaseRVDep, Arg, |
| 4212 | Autorelease->getParent(), Autorelease, |
| 4213 | DependingInstructions, Visited, PA); |
| 4214 | else |
| 4215 | FindDependencies(RetainAutoreleaseDep, Arg, |
| 4216 | Autorelease->getParent(), Autorelease, |
| 4217 | DependingInstructions, Visited, PA); |
| 4218 | |
| 4219 | Visited.clear(); |
| 4220 | if (DependingInstructions.size() != 1) { |
| 4221 | DependingInstructions.clear(); |
| 4222 | return false; |
| 4223 | } |
| 4224 | |
| 4225 | Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); |
| 4226 | DependingInstructions.clear(); |
| 4227 | |
| 4228 | if (!Retain || |
| 4229 | GetBasicInstructionClass(Retain) != IC_Retain || |
| 4230 | GetObjCArg(Retain) != Arg) |
| 4231 | return false; |
| 4232 | |
| 4233 | Changed = true; |
| 4234 | ++NumPeeps; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4235 | |
Michael Gottesman | add0847 | 2013-01-07 00:31:26 +0000 | [diff] [blame] | 4236 | DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing " |
| 4237 | "retain/autorelease. Erasing: " << *Autorelease << "\n" |
| 4238 | " Old Retain: " |
| 4239 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4240 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4241 | if (Class == IC_AutoreleaseRV) |
| 4242 | Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent())); |
| 4243 | else |
| 4244 | Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent())); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4245 | |
Michael Gottesman | add0847 | 2013-01-07 00:31:26 +0000 | [diff] [blame] | 4246 | DEBUG(dbgs() << " New Retain: " |
| 4247 | << *Retain << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4248 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4249 | EraseInstruction(Autorelease); |
| 4250 | return true; |
| 4251 | } |
| 4252 | |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4253 | /// Attempt to merge an objc_release with a store, load, and objc_retain to form |
| 4254 | /// an objc_storeStrong. This can be a little tricky because the instructions |
| 4255 | /// don't always appear in order, and there may be unrelated intervening |
| 4256 | /// instructions. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4257 | void ObjCARCContract::ContractRelease(Instruction *Release, |
| 4258 | inst_iterator &Iter) { |
| 4259 | LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release)); |
Eli Friedman | 7c5dc12 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 4260 | if (!Load || !Load->isSimple()) return; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4261 | |
| 4262 | // For now, require everything to be in one basic block. |
| 4263 | BasicBlock *BB = Release->getParent(); |
| 4264 | if (Load->getParent() != BB) return; |
| 4265 | |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 4266 | // Walk down to find the store and the release, which may be in either order. |
Dan Gohman | f8b19d0 | 2012-05-09 23:08:33 +0000 | [diff] [blame] | 4267 | BasicBlock::iterator I = Load, End = BB->end(); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4268 | ++I; |
| 4269 | AliasAnalysis::Location Loc = AA->getLocation(Load); |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 4270 | StoreInst *Store = 0; |
| 4271 | bool SawRelease = false; |
| 4272 | for (; !Store || !SawRelease; ++I) { |
Dan Gohman | f8b19d0 | 2012-05-09 23:08:33 +0000 | [diff] [blame] | 4273 | if (I == End) |
| 4274 | return; |
| 4275 | |
Dan Gohman | 61708d3 | 2012-05-08 23:34:08 +0000 | [diff] [blame] | 4276 | Instruction *Inst = I; |
| 4277 | if (Inst == Release) { |
| 4278 | SawRelease = true; |
| 4279 | continue; |
| 4280 | } |
| 4281 | |
| 4282 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 4283 | |
| 4284 | // Unrelated retains are harmless. |
| 4285 | if (IsRetain(Class)) |
| 4286 | continue; |
| 4287 | |
| 4288 | if (Store) { |
| 4289 | // The store is the point where we're going to put the objc_storeStrong, |
| 4290 | // so make sure there are no uses after it. |
| 4291 | if (CanUse(Inst, Load, PA, Class)) |
| 4292 | return; |
| 4293 | } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) { |
| 4294 | // We are moving the load down to the store, so check for anything |
| 4295 | // else which writes to the memory between the load and the store. |
| 4296 | Store = dyn_cast<StoreInst>(Inst); |
| 4297 | if (!Store || !Store->isSimple()) return; |
| 4298 | if (Store->getPointerOperand() != Loc.Ptr) return; |
| 4299 | } |
| 4300 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4301 | |
| 4302 | Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand()); |
| 4303 | |
| 4304 | // Walk up to find the retain. |
| 4305 | I = Store; |
| 4306 | BasicBlock::iterator Begin = BB->begin(); |
| 4307 | while (I != Begin && GetBasicInstructionClass(I) != IC_Retain) |
| 4308 | --I; |
| 4309 | Instruction *Retain = I; |
| 4310 | if (GetBasicInstructionClass(Retain) != IC_Retain) return; |
| 4311 | if (GetObjCArg(Retain) != New) return; |
| 4312 | |
| 4313 | Changed = true; |
| 4314 | ++NumStoreStrongs; |
| 4315 | |
| 4316 | LLVMContext &C = Release->getContext(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4317 | Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); |
| 4318 | Type *I8XX = PointerType::getUnqual(I8X); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4319 | |
| 4320 | Value *Args[] = { Load->getPointerOperand(), New }; |
| 4321 | if (Args[0]->getType() != I8XX) |
| 4322 | Args[0] = new BitCastInst(Args[0], I8XX, "", Store); |
| 4323 | if (Args[1]->getType() != I8X) |
| 4324 | Args[1] = new BitCastInst(Args[1], I8X, "", Store); |
| 4325 | CallInst *StoreStrong = |
| 4326 | CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()), |
Jay Foad | 5bd375a | 2011-07-15 08:37:34 +0000 | [diff] [blame] | 4327 | Args, "", Store); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4328 | StoreStrong->setDoesNotThrow(); |
| 4329 | StoreStrong->setDebugLoc(Store->getDebugLoc()); |
| 4330 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4331 | // We can't set the tail flag yet, because we haven't yet determined |
| 4332 | // whether there are any escaping allocas. Remember this call, so that |
| 4333 | // we can set the tail flag once we know it's safe. |
| 4334 | StoreStrongCalls.insert(StoreStrong); |
| 4335 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4336 | if (&*Iter == Store) ++Iter; |
| 4337 | Store->eraseFromParent(); |
| 4338 | Release->eraseFromParent(); |
| 4339 | EraseInstruction(Retain); |
| 4340 | if (Load->use_empty()) |
| 4341 | Load->eraseFromParent(); |
| 4342 | } |
| 4343 | |
| 4344 | bool ObjCARCContract::doInitialization(Module &M) { |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 4345 | // If nothing in the Module uses ARC, don't do anything. |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 4346 | Run = ModuleHasARC(M); |
| 4347 | if (!Run) |
| 4348 | return false; |
| 4349 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4350 | // These are initialized lazily. |
| 4351 | StoreStrongCallee = 0; |
| 4352 | RetainAutoreleaseCallee = 0; |
| 4353 | RetainAutoreleaseRVCallee = 0; |
| 4354 | |
| 4355 | // Initialize RetainRVMarker. |
| 4356 | RetainRVMarker = 0; |
| 4357 | if (NamedMDNode *NMD = |
| 4358 | M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker")) |
| 4359 | if (NMD->getNumOperands() == 1) { |
| 4360 | const MDNode *N = NMD->getOperand(0); |
| 4361 | if (N->getNumOperands() == 1) |
| 4362 | if (const MDString *S = dyn_cast<MDString>(N->getOperand(0))) |
| 4363 | RetainRVMarker = S; |
| 4364 | } |
| 4365 | |
| 4366 | return false; |
| 4367 | } |
| 4368 | |
| 4369 | bool ObjCARCContract::runOnFunction(Function &F) { |
| 4370 | if (!EnableARCOpts) |
| 4371 | return false; |
| 4372 | |
Dan Gohman | ceaac7c | 2011-06-20 23:20:43 +0000 | [diff] [blame] | 4373 | // If nothing in the Module uses ARC, don't do anything. |
| 4374 | if (!Run) |
| 4375 | return false; |
| 4376 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4377 | Changed = false; |
| 4378 | AA = &getAnalysis<AliasAnalysis>(); |
| 4379 | DT = &getAnalysis<DominatorTree>(); |
| 4380 | |
| 4381 | PA.setAA(&getAnalysis<AliasAnalysis>()); |
| 4382 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4383 | // Track whether it's ok to mark objc_storeStrong calls with the "tail" |
| 4384 | // keyword. Be conservative if the function has variadic arguments. |
| 4385 | // It seems that functions which "return twice" are also unsafe for the |
| 4386 | // "tail" argument, because they are setjmp, which could need to |
| 4387 | // return to an earlier stack state. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4388 | bool TailOkForStoreStrongs = !F.isVarArg() && |
| 4389 | !F.callsFunctionThatReturnsTwice(); |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4390 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4391 | // For ObjC library calls which return their argument, replace uses of the |
| 4392 | // argument with uses of the call return value, if it dominates the use. This |
| 4393 | // reduces register pressure. |
| 4394 | SmallPtrSet<Instruction *, 4> DependingInstructions; |
| 4395 | SmallPtrSet<const BasicBlock *, 4> Visited; |
| 4396 | for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { |
| 4397 | Instruction *Inst = &*I++; |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4398 | |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 4399 | DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4400 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4401 | // Only these library routines return their argument. In particular, |
| 4402 | // objc_retainBlock does not necessarily return its argument. |
| 4403 | InstructionClass Class = GetBasicInstructionClass(Inst); |
| 4404 | switch (Class) { |
| 4405 | case IC_Retain: |
| 4406 | case IC_FusedRetainAutorelease: |
| 4407 | case IC_FusedRetainAutoreleaseRV: |
| 4408 | break; |
| 4409 | case IC_Autorelease: |
| 4410 | case IC_AutoreleaseRV: |
| 4411 | if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited)) |
| 4412 | continue; |
| 4413 | break; |
| 4414 | case IC_RetainRV: { |
| 4415 | // If we're compiling for a target which needs a special inline-asm |
| 4416 | // marker to do the retainAutoreleasedReturnValue optimization, |
| 4417 | // insert it now. |
| 4418 | if (!RetainRVMarker) |
| 4419 | break; |
| 4420 | BasicBlock::iterator BBI = Inst; |
Dan Gohman | 5f725cd | 2012-06-25 19:47:37 +0000 | [diff] [blame] | 4421 | BasicBlock *InstParent = Inst->getParent(); |
| 4422 | |
| 4423 | // Step up to see if the call immediately precedes the RetainRV call. |
| 4424 | // If it's an invoke, we have to cross a block boundary. And we have |
| 4425 | // to carefully dodge no-op instructions. |
| 4426 | do { |
| 4427 | if (&*BBI == InstParent->begin()) { |
| 4428 | BasicBlock *Pred = InstParent->getSinglePredecessor(); |
| 4429 | if (!Pred) |
| 4430 | goto decline_rv_optimization; |
| 4431 | BBI = Pred->getTerminator(); |
| 4432 | break; |
| 4433 | } |
| 4434 | --BBI; |
| 4435 | } while (isNoopInstruction(BBI)); |
| 4436 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4437 | if (&*BBI == GetObjCArg(Inst)) { |
Michael Gottesman | 00d1f96 | 2013-01-03 07:32:41 +0000 | [diff] [blame] | 4438 | DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for " |
Michael Gottesman | 9f848ae | 2013-01-04 21:29:57 +0000 | [diff] [blame] | 4439 | "retainAutoreleasedReturnValue optimization.\n"); |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 4440 | Changed = true; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4441 | InlineAsm *IA = |
| 4442 | InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()), |
| 4443 | /*isVarArg=*/false), |
| 4444 | RetainRVMarker->getString(), |
| 4445 | /*Constraints=*/"", /*hasSideEffects=*/true); |
| 4446 | CallInst::Create(IA, "", Inst); |
| 4447 | } |
Dan Gohman | 5f725cd | 2012-06-25 19:47:37 +0000 | [diff] [blame] | 4448 | decline_rv_optimization: |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4449 | break; |
| 4450 | } |
| 4451 | case IC_InitWeak: { |
| 4452 | // objc_initWeak(p, null) => *p = null |
| 4453 | CallInst *CI = cast<CallInst>(Inst); |
| 4454 | if (isNullOrUndef(CI->getArgOperand(1))) { |
| 4455 | Value *Null = |
| 4456 | ConstantPointerNull::get(cast<PointerType>(CI->getType())); |
| 4457 | Changed = true; |
| 4458 | new StoreInst(Null, CI->getArgOperand(0), CI); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4459 | |
Michael Gottesman | 416dc00 | 2013-01-03 07:32:53 +0000 | [diff] [blame] | 4460 | DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n" |
| 4461 | << " New = " << *Null << "\n"); |
Michael Gottesman | 10426b5 | 2013-01-07 21:26:07 +0000 | [diff] [blame] | 4462 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4463 | CI->replaceAllUsesWith(Null); |
| 4464 | CI->eraseFromParent(); |
| 4465 | } |
| 4466 | continue; |
| 4467 | } |
| 4468 | case IC_Release: |
| 4469 | ContractRelease(Inst, I); |
| 4470 | continue; |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4471 | case IC_User: |
| 4472 | // Be conservative if the function has any alloca instructions. |
| 4473 | // Technically we only care about escaping alloca instructions, |
| 4474 | // but this is sufficient to handle some interesting cases. |
| 4475 | if (isa<AllocaInst>(Inst)) |
| 4476 | TailOkForStoreStrongs = false; |
| 4477 | continue; |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4478 | default: |
| 4479 | continue; |
| 4480 | } |
| 4481 | |
Michael Gottesman | 50ae5b2 | 2013-01-03 08:09:27 +0000 | [diff] [blame] | 4482 | DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n"); |
Michael Gottesman | 3f146e2 | 2013-01-01 16:05:48 +0000 | [diff] [blame] | 4483 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4484 | // Don't use GetObjCArg because we don't want to look through bitcasts |
| 4485 | // and such; to do the replacement, the argument must have type i8*. |
| 4486 | const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0); |
| 4487 | for (;;) { |
| 4488 | // If we're compiling bugpointed code, don't get in trouble. |
| 4489 | if (!isa<Instruction>(Arg) && !isa<Argument>(Arg)) |
| 4490 | break; |
| 4491 | // Look through the uses of the pointer. |
| 4492 | for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); |
| 4493 | UI != UE; ) { |
| 4494 | Use &U = UI.getUse(); |
| 4495 | unsigned OperandNo = UI.getOperandNo(); |
| 4496 | ++UI; // Increment UI now, because we may unlink its element. |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 4497 | |
| 4498 | // If the call's return value dominates a use of the call's argument |
| 4499 | // value, rewrite the use to use the return value. We check for |
| 4500 | // reachability here because an unreachable call is considered to |
| 4501 | // trivially dominate itself, which would lead us to rewriting its |
| 4502 | // argument in terms of its return value, which would lead to |
| 4503 | // infinite loops in GetObjCArg. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4504 | if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) { |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4505 | Changed = true; |
| 4506 | Instruction *Replacement = Inst; |
| 4507 | Type *UseTy = U.get()->getType(); |
Dan Gohman | de8d2c4 | 2012-04-13 01:08:28 +0000 | [diff] [blame] | 4508 | if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) { |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4509 | // For PHI nodes, insert the bitcast in the predecessor block. |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4510 | unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo); |
| 4511 | BasicBlock *BB = PHI->getIncomingBlock(ValNo); |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4512 | if (Replacement->getType() != UseTy) |
| 4513 | Replacement = new BitCastInst(Replacement, UseTy, "", |
| 4514 | &BB->back()); |
Dan Gohman | 670f937 | 2012-04-13 18:57:48 +0000 | [diff] [blame] | 4515 | // While we're here, rewrite all edges for this PHI, rather |
| 4516 | // than just one use at a time, to minimize the number of |
| 4517 | // bitcasts we emit. |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 4518 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4519 | if (PHI->getIncomingBlock(i) == BB) { |
| 4520 | // Keep the UI iterator valid. |
| 4521 | if (&PHI->getOperandUse( |
| 4522 | PHINode::getOperandNumForIncomingValue(i)) == |
| 4523 | &UI.getUse()) |
| 4524 | ++UI; |
| 4525 | PHI->setIncomingValue(i, Replacement); |
| 4526 | } |
| 4527 | } else { |
| 4528 | if (Replacement->getType() != UseTy) |
Dan Gohman | de8d2c4 | 2012-04-13 01:08:28 +0000 | [diff] [blame] | 4529 | Replacement = new BitCastInst(Replacement, UseTy, "", |
| 4530 | cast<Instruction>(U.getUser())); |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4531 | U.set(Replacement); |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4532 | } |
Rafael Espindola | f589278 | 2012-03-15 15:52:59 +0000 | [diff] [blame] | 4533 | } |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4534 | } |
| 4535 | |
Dan Gohman | dae3349 | 2012-04-27 18:56:31 +0000 | [diff] [blame] | 4536 | // If Arg is a no-op casted pointer, strip one level of casts and iterate. |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4537 | if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg)) |
| 4538 | Arg = BI->getOperand(0); |
| 4539 | else if (isa<GEPOperator>(Arg) && |
| 4540 | cast<GEPOperator>(Arg)->hasAllZeroIndices()) |
| 4541 | Arg = cast<GEPOperator>(Arg)->getPointerOperand(); |
| 4542 | else if (isa<GlobalAlias>(Arg) && |
| 4543 | !cast<GlobalAlias>(Arg)->mayBeOverridden()) |
| 4544 | Arg = cast<GlobalAlias>(Arg)->getAliasee(); |
| 4545 | else |
| 4546 | break; |
| 4547 | } |
| 4548 | } |
| 4549 | |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4550 | // If this function has no escaping allocas or suspicious vararg usage, |
| 4551 | // objc_storeStrong calls can be marked with the "tail" keyword. |
| 4552 | if (TailOkForStoreStrongs) |
Dan Gohman | 41375a3 | 2012-05-08 23:39:44 +0000 | [diff] [blame] | 4553 | for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(), |
Dan Gohman | 8ee108b | 2012-01-19 19:14:36 +0000 | [diff] [blame] | 4554 | E = StoreStrongCalls.end(); I != E; ++I) |
| 4555 | (*I)->setTailCall(); |
| 4556 | StoreStrongCalls.clear(); |
| 4557 | |
John McCall | d935e9c | 2011-06-15 23:37:01 +0000 | [diff] [blame] | 4558 | return Changed; |
| 4559 | } |
Michael Gottesman | 97e3df0 | 2013-01-14 00:35:14 +0000 | [diff] [blame] | 4560 | |
| 4561 | /// @} |
| 4562 | /// |