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