Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1 | //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements the MemorySSAUpdater class. |
| 10 | // |
| 11 | //===----------------------------------------------------------------===// |
Daniel Berlin | 554dcd8 | 2017-04-11 20:06:36 +0000 | [diff] [blame] | 12 | #include "llvm/Analysis/MemorySSAUpdater.h" |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 13 | #include "llvm/ADT/STLExtras.h" |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/SetVector.h" |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/SmallPtrSet.h" |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 16 | #include "llvm/Analysis/IteratedDominanceFrontier.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/MemorySSA.h" |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 18 | #include "llvm/IR/DataLayout.h" |
| 19 | #include "llvm/IR/Dominators.h" |
| 20 | #include "llvm/IR/GlobalVariable.h" |
| 21 | #include "llvm/IR/IRBuilder.h" |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 22 | #include "llvm/IR/LLVMContext.h" |
| 23 | #include "llvm/IR/Metadata.h" |
| 24 | #include "llvm/IR/Module.h" |
| 25 | #include "llvm/Support/Debug.h" |
| 26 | #include "llvm/Support/FormattedStream.h" |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 27 | #include <algorithm> |
| 28 | |
| 29 | #define DEBUG_TYPE "memoryssa" |
| 30 | using namespace llvm; |
George Burgess IV | 56169ed | 2017-04-21 04:54:52 +0000 | [diff] [blame] | 31 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 32 | // This is the marker algorithm from "Simple and Efficient Construction of |
| 33 | // Static Single Assignment Form" |
| 34 | // The simple, non-marker algorithm places phi nodes at any join |
| 35 | // Here, we place markers, and only place phi nodes if they end up necessary. |
| 36 | // They are only necessary if they break a cycle (IE we recursively visit |
| 37 | // ourselves again), or we discover, while getting the value of the operands, |
| 38 | // that there are two or more definitions needing to be merged. |
| 39 | // This still will leave non-minimal form in the case of irreducible control |
| 40 | // flow, where phi nodes may be in cycles with themselves, but unnecessary. |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 41 | MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive( |
| 42 | BasicBlock *BB, |
| 43 | DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { |
| 44 | // First, do a cache lookup. Without this cache, certain CFG structures |
| 45 | // (like a series of if statements) take exponential time to visit. |
| 46 | auto Cached = CachedPreviousDef.find(BB); |
| 47 | if (Cached != CachedPreviousDef.end()) { |
| 48 | return Cached->second; |
George Burgess IV | 45f263d | 2018-05-26 02:28:55 +0000 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | if (BasicBlock *Pred = BB->getSinglePredecessor()) { |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 52 | // Single predecessor case, just recurse, we can only have one definition. |
| 53 | MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef); |
| 54 | CachedPreviousDef.insert({BB, Result}); |
| 55 | return Result; |
George Burgess IV | 45f263d | 2018-05-26 02:28:55 +0000 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | if (VisitedBlocks.count(BB)) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 59 | // We hit our node again, meaning we had a cycle, we must insert a phi |
| 60 | // node to break it so we have an operand. The only case this will |
| 61 | // insert useless phis is if we have irreducible control flow. |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 62 | MemoryAccess *Result = MSSA->createMemoryPhi(BB); |
| 63 | CachedPreviousDef.insert({BB, Result}); |
| 64 | return Result; |
George Burgess IV | 45f263d | 2018-05-26 02:28:55 +0000 | [diff] [blame] | 65 | } |
| 66 | |
| 67 | if (VisitedBlocks.insert(BB).second) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 68 | // Mark us visited so we can detect a cycle |
Alexandros Lamprineas | bf6009c | 2018-07-23 10:56:30 +0000 | [diff] [blame] | 69 | SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps; |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 70 | |
| 71 | // Recurse to get the values in our predecessors for placement of a |
| 72 | // potential phi node. This will insert phi nodes if we cycle in order to |
| 73 | // break the cycle and have an operand. |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 74 | bool UniqueIncomingAccess = true; |
| 75 | MemoryAccess *SingleAccess = nullptr; |
| 76 | for (auto *Pred : predecessors(BB)) { |
| 77 | if (MSSA->DT->isReachableFromEntry(Pred)) { |
| 78 | auto *IncomingAccess = getPreviousDefFromEnd(Pred, CachedPreviousDef); |
| 79 | if (!SingleAccess) |
| 80 | SingleAccess = IncomingAccess; |
| 81 | else if (IncomingAccess != SingleAccess) |
| 82 | UniqueIncomingAccess = false; |
| 83 | PhiOps.push_back(IncomingAccess); |
| 84 | } else |
Alina Sbirlea | 0363c3b | 2019-05-02 23:41:58 +0000 | [diff] [blame] | 85 | PhiOps.push_back(MSSA->getLiveOnEntryDef()); |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 86 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 87 | |
| 88 | // Now try to simplify the ops to avoid placing a phi. |
| 89 | // This may return null if we never created a phi yet, that's okay |
| 90 | MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB)); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 91 | |
| 92 | // See if we can avoid the phi by simplifying it. |
| 93 | auto *Result = tryRemoveTrivialPhi(Phi, PhiOps); |
| 94 | // If we couldn't simplify, we may have to create a phi |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 95 | if (Result == Phi && UniqueIncomingAccess && SingleAccess) |
| 96 | Result = SingleAccess; |
| 97 | else if (Result == Phi && !(UniqueIncomingAccess && SingleAccess)) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 98 | if (!Phi) |
| 99 | Phi = MSSA->createMemoryPhi(BB); |
| 100 | |
Alexandros Lamprineas | bf6009c | 2018-07-23 10:56:30 +0000 | [diff] [blame] | 101 | // See if the existing phi operands match what we need. |
| 102 | // Unlike normal SSA, we only allow one phi node per block, so we can't just |
| 103 | // create a new one. |
| 104 | if (Phi->getNumOperands() != 0) { |
| 105 | // FIXME: Figure out whether this is dead code and if so remove it. |
| 106 | if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) { |
| 107 | // These will have been filled in by the recursive read we did above. |
Fangrui Song | 7570932 | 2018-11-17 01:44:25 +0000 | [diff] [blame] | 108 | llvm::copy(PhiOps, Phi->op_begin()); |
Alexandros Lamprineas | bf6009c | 2018-07-23 10:56:30 +0000 | [diff] [blame] | 109 | std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin()); |
| 110 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 111 | } else { |
| 112 | unsigned i = 0; |
| 113 | for (auto *Pred : predecessors(BB)) |
Alexandros Lamprineas | bf6009c | 2018-07-23 10:56:30 +0000 | [diff] [blame] | 114 | Phi->addIncoming(&*PhiOps[i++], Pred); |
Daniel Berlin | 97f34e8 | 2017-09-27 05:35:19 +0000 | [diff] [blame] | 115 | InsertedPHIs.push_back(Phi); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 116 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 117 | Result = Phi; |
| 118 | } |
Daniel Berlin | 97f34e8 | 2017-09-27 05:35:19 +0000 | [diff] [blame] | 119 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 120 | // Set ourselves up for the next variable by resetting visited state. |
| 121 | VisitedBlocks.erase(BB); |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 122 | CachedPreviousDef.insert({BB, Result}); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 123 | return Result; |
| 124 | } |
| 125 | llvm_unreachable("Should have hit one of the three cases above"); |
| 126 | } |
| 127 | |
| 128 | // This starts at the memory access, and goes backwards in the block to find the |
| 129 | // previous definition. If a definition is not found the block of the access, |
| 130 | // it continues globally, creating phi nodes to ensure we have a single |
| 131 | // definition. |
| 132 | MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) { |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 133 | if (auto *LocalResult = getPreviousDefInBlock(MA)) |
| 134 | return LocalResult; |
| 135 | DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef; |
| 136 | return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 137 | } |
| 138 | |
| 139 | // This starts at the memory access, and goes backwards in the block to the find |
| 140 | // the previous definition. If the definition is not found in the block of the |
| 141 | // access, it returns nullptr. |
| 142 | MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) { |
| 143 | auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock()); |
| 144 | |
| 145 | // It's possible there are no defs, or we got handed the first def to start. |
| 146 | if (Defs) { |
| 147 | // If this is a def, we can just use the def iterators. |
| 148 | if (!isa<MemoryUse>(MA)) { |
| 149 | auto Iter = MA->getReverseDefsIterator(); |
| 150 | ++Iter; |
| 151 | if (Iter != Defs->rend()) |
| 152 | return &*Iter; |
| 153 | } else { |
| 154 | // Otherwise, have to walk the all access iterator. |
Alina Sbirlea | 33e5872 | 2017-06-07 16:46:53 +0000 | [diff] [blame] | 155 | auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend(); |
| 156 | for (auto &U : make_range(++MA->getReverseIterator(), End)) |
| 157 | if (!isa<MemoryUse>(U)) |
| 158 | return cast<MemoryAccess>(&U); |
| 159 | // Note that if MA comes before Defs->begin(), we won't hit a def. |
| 160 | return nullptr; |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 161 | } |
| 162 | } |
| 163 | return nullptr; |
| 164 | } |
| 165 | |
| 166 | // This starts at the end of block |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 167 | MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd( |
| 168 | BasicBlock *BB, |
| 169 | DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 170 | auto *Defs = MSSA->getWritableBlockDefs(BB); |
| 171 | |
Alina Sbirlea | f9f073a | 2019-04-12 21:58:52 +0000 | [diff] [blame] | 172 | if (Defs) { |
| 173 | CachedPreviousDef.insert({BB, &*Defs->rbegin()}); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 174 | return &*Defs->rbegin(); |
Alina Sbirlea | f9f073a | 2019-04-12 21:58:52 +0000 | [diff] [blame] | 175 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 176 | |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 177 | return getPreviousDefRecursive(BB, CachedPreviousDef); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 178 | } |
| 179 | // Recurse over a set of phi uses to eliminate the trivial ones |
| 180 | MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) { |
| 181 | if (!Phi) |
| 182 | return nullptr; |
| 183 | TrackingVH<MemoryAccess> Res(Phi); |
| 184 | SmallVector<TrackingVH<Value>, 8> Uses; |
| 185 | std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses)); |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 186 | for (auto &U : Uses) |
| 187 | if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) |
| 188 | tryRemoveTrivialPhi(UsePhi); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 189 | return Res; |
| 190 | } |
| 191 | |
| 192 | // Eliminate trivial phis |
| 193 | // Phis are trivial if they are defined either by themselves, or all the same |
| 194 | // argument. |
| 195 | // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c) |
| 196 | // We recursively try to remove them. |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 197 | MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi) { |
| 198 | assert(Phi && "Can only remove concrete Phi."); |
| 199 | auto OperRange = Phi->operands(); |
| 200 | return tryRemoveTrivialPhi(Phi, OperRange); |
| 201 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 202 | template <class RangeType> |
| 203 | MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi, |
| 204 | RangeType &Operands) { |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 205 | // Bail out on non-opt Phis. |
| 206 | if (NonOptPhis.count(Phi)) |
| 207 | return Phi; |
| 208 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 209 | // Detect equal or self arguments |
| 210 | MemoryAccess *Same = nullptr; |
| 211 | for (auto &Op : Operands) { |
| 212 | // If the same or self, good so far |
| 213 | if (Op == Phi || Op == Same) |
| 214 | continue; |
| 215 | // not the same, return the phi since it's not eliminatable by us |
| 216 | if (Same) |
| 217 | return Phi; |
Alexandros Lamprineas | bf6009c | 2018-07-23 10:56:30 +0000 | [diff] [blame] | 218 | Same = cast<MemoryAccess>(&*Op); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 219 | } |
| 220 | // Never found a non-self reference, the phi is undef |
| 221 | if (Same == nullptr) |
| 222 | return MSSA->getLiveOnEntryDef(); |
| 223 | if (Phi) { |
| 224 | Phi->replaceAllUsesWith(Same); |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 225 | removeMemoryAccess(Phi); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 226 | } |
| 227 | |
| 228 | // We should only end up recursing in case we replaced something, in which |
| 229 | // case, we may have made other Phis trivial. |
| 230 | return recursePhi(Same); |
| 231 | } |
| 232 | |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 233 | void MemorySSAUpdater::insertUse(MemoryUse *MU, bool RenameUses) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 234 | InsertedPHIs.clear(); |
| 235 | MU->setDefiningAccess(getPreviousDef(MU)); |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 236 | // In cases without unreachable blocks, because uses do not create new |
| 237 | // may-defs, there are only two cases: |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 238 | // 1. There was a def already below us, and therefore, we should not have |
| 239 | // created a phi node because it was already needed for the def. |
| 240 | // |
| 241 | // 2. There is no def below us, and therefore, there is no extra renaming work |
| 242 | // to do. |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 243 | |
| 244 | // In cases with unreachable blocks, where the unnecessary Phis were |
| 245 | // optimized out, adding the Use may re-insert those Phis. Hence, when |
| 246 | // inserting Uses outside of the MSSA creation process, and new Phis were |
| 247 | // added, rename all uses if we are asked. |
| 248 | |
| 249 | if (!RenameUses && !InsertedPHIs.empty()) { |
| 250 | auto *Defs = MSSA->getBlockDefs(MU->getBlock()); |
| 251 | (void)Defs; |
| 252 | assert((!Defs || (++Defs->begin() == Defs->end())) && |
| 253 | "Block may have only a Phi or no defs"); |
| 254 | } |
| 255 | |
| 256 | if (RenameUses && InsertedPHIs.size()) { |
| 257 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 258 | BasicBlock *StartBlock = MU->getBlock(); |
| 259 | |
| 260 | if (auto *Defs = MSSA->getWritableBlockDefs(StartBlock)) { |
| 261 | MemoryAccess *FirstDef = &*Defs->begin(); |
| 262 | // Convert to incoming value if it's a memorydef. A phi *is* already an |
| 263 | // incoming value. |
| 264 | if (auto *MD = dyn_cast<MemoryDef>(FirstDef)) |
| 265 | FirstDef = MD->getDefiningAccess(); |
| 266 | |
| 267 | MSSA->renamePass(MU->getBlock(), FirstDef, Visited); |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 268 | } |
Alina Sbirlea | 228ffac | 2019-08-27 00:34:47 +0000 | [diff] [blame] | 269 | // We just inserted a phi into this block, so the incoming value will |
| 270 | // become the phi anyway, so it does not matter what we pass. |
| 271 | for (auto &MP : InsertedPHIs) |
| 272 | if (MemoryPhi *Phi = cast_or_null<MemoryPhi>(MP)) |
| 273 | MSSA->renamePass(Phi->getBlock(), nullptr, Visited); |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 274 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 275 | } |
| 276 | |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 277 | // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef. |
George Burgess IV | 56169ed | 2017-04-21 04:54:52 +0000 | [diff] [blame] | 278 | static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB, |
| 279 | MemoryAccess *NewDef) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 280 | // Replace any operand with us an incoming block with the new defining |
| 281 | // access. |
| 282 | int i = MP->getBasicBlockIndex(BB); |
| 283 | assert(i != -1 && "Should have found the basic block in the phi"); |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 284 | // We can't just compare i against getNumOperands since one is signed and the |
| 285 | // other not. So use it to index into the block iterator. |
| 286 | for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end(); |
| 287 | ++BBIter) { |
| 288 | if (*BBIter != BB) |
| 289 | break; |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 290 | MP->setIncomingValue(i, NewDef); |
| 291 | ++i; |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // A brief description of the algorithm: |
| 296 | // First, we compute what should define the new def, using the SSA |
| 297 | // construction algorithm. |
| 298 | // Then, we update the defs below us (and any new phi nodes) in the graph to |
| 299 | // point to the correct new defs, to ensure we only have one variable, and no |
| 300 | // disconnected stores. |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 301 | void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 302 | InsertedPHIs.clear(); |
| 303 | |
| 304 | // See if we had a local def, and if not, go hunting. |
Eli Friedman | 88e2bac | 2018-03-26 19:52:54 +0000 | [diff] [blame] | 305 | MemoryAccess *DefBefore = getPreviousDef(MD); |
Alina Sbirlea | ae40dfc | 2019-10-01 18:34:39 +0000 | [diff] [blame^] | 306 | bool DefBeforeSameBlock = false; |
| 307 | if (DefBefore->getBlock() == MD->getBlock() && |
| 308 | !(isa<MemoryPhi>(DefBefore) && |
| 309 | std::find(InsertedPHIs.begin(), InsertedPHIs.end(), DefBefore) != |
| 310 | InsertedPHIs.end())) |
| 311 | DefBeforeSameBlock = true; |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 312 | |
| 313 | // There is a def before us, which means we can replace any store/phi uses |
| 314 | // of that thing with us, since we are in the way of whatever was there |
| 315 | // before. |
| 316 | // We now define that def's memorydefs and memoryphis |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 317 | if (DefBeforeSameBlock) { |
Roman Lebedev | 081e990 | 2019-08-01 12:32:08 +0000 | [diff] [blame] | 318 | DefBefore->replaceUsesWithIf(MD, [MD](Use &U) { |
Alexandros Lamprineas | 96762b3 | 2018-09-11 14:29:59 +0000 | [diff] [blame] | 319 | // Leave the MemoryUses alone. |
| 320 | // Also make sure we skip ourselves to avoid self references. |
Roman Lebedev | 081e990 | 2019-08-01 12:32:08 +0000 | [diff] [blame] | 321 | User *Usr = U.getUser(); |
| 322 | return !isa<MemoryUse>(Usr) && Usr != MD; |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 323 | // Defs are automatically unoptimized when the user is set to MD below, |
| 324 | // because the isOptimized() call will fail to find the same ID. |
Roman Lebedev | 081e990 | 2019-08-01 12:32:08 +0000 | [diff] [blame] | 325 | }); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 326 | } |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 327 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 328 | // and that def is now our defining access. |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 329 | MD->setDefiningAccess(DefBefore); |
| 330 | |
Alexandros Lamprineas | f854ce8 | 2018-07-16 07:51:27 +0000 | [diff] [blame] | 331 | SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end()); |
Alina Sbirlea | 2c5e664 | 2019-09-23 23:50:16 +0000 | [diff] [blame] | 332 | |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 333 | // Remember the index where we may insert new phis. |
| 334 | unsigned NewPhiIndex = InsertedPHIs.size(); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 335 | if (!DefBeforeSameBlock) { |
| 336 | // If there was a local def before us, we must have the same effect it |
| 337 | // did. Because every may-def is the same, any phis/etc we would create, it |
| 338 | // would also have created. If there was no local def before us, we |
| 339 | // performed a global update, and have to search all successors and make |
| 340 | // sure we update the first def in each of them (following all paths until |
| 341 | // we hit the first def along each path). This may also insert phi nodes. |
| 342 | // TODO: There are other cases we can skip this work, such as when we have a |
| 343 | // single successor, and only used a straight line of single pred blocks |
| 344 | // backwards to find the def. To make that work, we'd have to track whether |
| 345 | // getDefRecursive only ever used the single predecessor case. These types |
| 346 | // of paths also only exist in between CFG simplifications. |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 347 | |
| 348 | // If this is the first def in the block and this insert is in an arbitrary |
| 349 | // place, compute IDF and place phis. |
| 350 | auto Iter = MD->getDefsIterator(); |
| 351 | ++Iter; |
| 352 | auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end(); |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 353 | if (Iter == IterEnd) { |
| 354 | SmallPtrSet<BasicBlock *, 2> DefiningBlocks; |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 355 | DefiningBlocks.insert(MD->getBlock()); |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 356 | for (const auto &VH : InsertedPHIs) |
| 357 | if (const auto *RealPHI = cast_or_null<MemoryPhi>(VH)) |
| 358 | DefiningBlocks.insert(RealPHI->getBlock()); |
| 359 | ForwardIDFCalculator IDFs(*MSSA->DT); |
| 360 | SmallVector<BasicBlock *, 32> IDFBlocks; |
| 361 | IDFs.setDefiningBlocks(DefiningBlocks); |
| 362 | IDFs.calculate(IDFBlocks); |
| 363 | SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs; |
| 364 | for (auto *BBIDF : IDFBlocks) { |
| 365 | auto *MPhi = MSSA->getMemoryAccess(BBIDF); |
| 366 | if (!MPhi) { |
| 367 | MPhi = MSSA->createMemoryPhi(BBIDF); |
| 368 | NewInsertedPHIs.push_back(MPhi); |
| 369 | } |
| 370 | // Add the phis created into the IDF blocks to NonOptPhis, so they are |
| 371 | // not optimized out as trivial by the call to getPreviousDefFromEnd |
| 372 | // below. Once they are complete, all these Phis are added to the |
| 373 | // FixupList, and removed from NonOptPhis inside fixupDefs(). Existing |
| 374 | // Phis in IDF may need fixing as well, and potentially be trivial |
| 375 | // before this insertion, hence add all IDF Phis. See PR43044. |
| 376 | NonOptPhis.insert(MPhi); |
| 377 | } |
| 378 | for (auto &MPhi : NewInsertedPHIs) { |
| 379 | auto *BBIDF = MPhi->getBlock(); |
| 380 | for (auto *Pred : predecessors(BBIDF)) { |
| 381 | DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef; |
| 382 | MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef), |
| 383 | Pred); |
| 384 | } |
| 385 | } |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 386 | |
Alina Sbirlea | 6720ed8 | 2019-09-25 23:24:39 +0000 | [diff] [blame] | 387 | // Re-take the index where we're adding the new phis, because the above |
| 388 | // call to getPreviousDefFromEnd, may have inserted into InsertedPHIs. |
| 389 | NewPhiIndex = InsertedPHIs.size(); |
| 390 | for (auto &MPhi : NewInsertedPHIs) { |
| 391 | InsertedPHIs.push_back(&*MPhi); |
| 392 | FixupList.push_back(&*MPhi); |
| 393 | } |
| 394 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 395 | FixupList.push_back(MD); |
| 396 | } |
| 397 | |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 398 | // Remember the index where we stopped inserting new phis above, since the |
| 399 | // fixupDefs call in the loop below may insert more, that are already minimal. |
| 400 | unsigned NewPhiIndexEnd = InsertedPHIs.size(); |
| 401 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 402 | while (!FixupList.empty()) { |
| 403 | unsigned StartingPHISize = InsertedPHIs.size(); |
| 404 | fixupDefs(FixupList); |
| 405 | FixupList.clear(); |
| 406 | // Put any new phis on the fixup list, and process them |
Alexandros Lamprineas | f854ce8 | 2018-07-16 07:51:27 +0000 | [diff] [blame] | 407 | FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end()); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 408 | } |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 409 | |
| 410 | // Optimize potentially non-minimal phis added in this method. |
Alina Sbirlea | 151ab48 | 2019-05-02 23:12:49 +0000 | [diff] [blame] | 411 | unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex; |
| 412 | if (NewPhiSize) |
| 413 | tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize)); |
Alina Sbirlea | fcfa7c5 | 2019-02-27 22:20:22 +0000 | [diff] [blame] | 414 | |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 415 | // Now that all fixups are done, rename all uses if we are asked. |
| 416 | if (RenameUses) { |
| 417 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 418 | BasicBlock *StartBlock = MD->getBlock(); |
| 419 | // We are guaranteed there is a def in the block, because we just got it |
| 420 | // handed to us in this function. |
| 421 | MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin(); |
| 422 | // Convert to incoming value if it's a memorydef. A phi *is* already an |
| 423 | // incoming value. |
| 424 | if (auto *MD = dyn_cast<MemoryDef>(FirstDef)) |
| 425 | FirstDef = MD->getDefiningAccess(); |
| 426 | |
| 427 | MSSA->renamePass(MD->getBlock(), FirstDef, Visited); |
| 428 | // We just inserted a phi into this block, so the incoming value will become |
| 429 | // the phi anyway, so it does not matter what we pass. |
Alexandros Lamprineas | f854ce8 | 2018-07-16 07:51:27 +0000 | [diff] [blame] | 430 | for (auto &MP : InsertedPHIs) { |
| 431 | MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP); |
| 432 | if (Phi) |
| 433 | MSSA->renamePass(Phi->getBlock(), nullptr, Visited); |
| 434 | } |
Daniel Berlin | 78cbd28 | 2017-02-20 22:26:03 +0000 | [diff] [blame] | 435 | } |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 436 | } |
| 437 | |
Alexandros Lamprineas | f854ce8 | 2018-07-16 07:51:27 +0000 | [diff] [blame] | 438 | void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) { |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 439 | SmallPtrSet<const BasicBlock *, 8> Seen; |
| 440 | SmallVector<const BasicBlock *, 16> Worklist; |
Alexandros Lamprineas | f854ce8 | 2018-07-16 07:51:27 +0000 | [diff] [blame] | 441 | for (auto &Var : Vars) { |
| 442 | MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var); |
| 443 | if (!NewDef) |
| 444 | continue; |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 445 | // First, see if there is a local def after the operand. |
| 446 | auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock()); |
| 447 | auto DefIter = NewDef->getDefsIterator(); |
| 448 | |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 449 | // The temporary Phi is being fixed, unmark it for not to optimize. |
George Burgess IV | e7cdb7e | 2018-07-12 21:56:31 +0000 | [diff] [blame] | 450 | if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef)) |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 451 | NonOptPhis.erase(Phi); |
| 452 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 453 | // If there is a local def after us, we only have to rename that. |
| 454 | if (++DefIter != Defs->end()) { |
| 455 | cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef); |
| 456 | continue; |
| 457 | } |
| 458 | |
| 459 | // Otherwise, we need to search down through the CFG. |
| 460 | // For each of our successors, handle it directly if their is a phi, or |
| 461 | // place on the fixup worklist. |
| 462 | for (const auto *S : successors(NewDef->getBlock())) { |
| 463 | if (auto *MP = MSSA->getMemoryAccess(S)) |
| 464 | setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef); |
| 465 | else |
| 466 | Worklist.push_back(S); |
| 467 | } |
| 468 | |
| 469 | while (!Worklist.empty()) { |
| 470 | const BasicBlock *FixupBlock = Worklist.back(); |
| 471 | Worklist.pop_back(); |
| 472 | |
| 473 | // Get the first def in the block that isn't a phi node. |
| 474 | if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) { |
| 475 | auto *FirstDef = &*Defs->begin(); |
| 476 | // The loop above and below should have taken care of phi nodes |
| 477 | assert(!isa<MemoryPhi>(FirstDef) && |
| 478 | "Should have already handled phi nodes!"); |
| 479 | // We are now this def's defining access, make sure we actually dominate |
| 480 | // it |
| 481 | assert(MSSA->dominates(NewDef, FirstDef) && |
| 482 | "Should have dominated the new access"); |
| 483 | |
| 484 | // This may insert new phi nodes, because we are not guaranteed the |
| 485 | // block we are processing has a single pred, and depending where the |
| 486 | // store was inserted, it may require phi nodes below it. |
| 487 | cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef)); |
| 488 | return; |
| 489 | } |
| 490 | // We didn't find a def, so we must continue. |
| 491 | for (const auto *S : successors(FixupBlock)) { |
| 492 | // If there is a phi node, handle it. |
| 493 | // Otherwise, put the block on the worklist |
| 494 | if (auto *MP = MSSA->getMemoryAccess(S)) |
| 495 | setMemoryPhiValueForBlock(MP, FixupBlock, NewDef); |
| 496 | else { |
| 497 | // If we cycle, we should have ended up at a phi node that we already |
| 498 | // processed. FIXME: Double check this |
| 499 | if (!Seen.insert(S).second) |
| 500 | continue; |
| 501 | Worklist.push_back(S); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 508 | void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) { |
| 509 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) { |
| 510 | MPhi->unorderedDeleteIncomingBlock(From); |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 511 | tryRemoveTrivialPhi(MPhi); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 512 | } |
| 513 | } |
| 514 | |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 515 | void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From, |
| 516 | const BasicBlock *To) { |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 517 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) { |
| 518 | bool Found = false; |
| 519 | MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) { |
| 520 | if (From != B) |
| 521 | return false; |
| 522 | if (Found) |
| 523 | return true; |
| 524 | Found = true; |
| 525 | return false; |
| 526 | }); |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 527 | tryRemoveTrivialPhi(MPhi); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 528 | } |
| 529 | } |
| 530 | |
Alina Sbirlea | 4bc625c | 2019-07-30 20:10:33 +0000 | [diff] [blame] | 531 | static MemoryAccess *getNewDefiningAccessForClone(MemoryAccess *MA, |
| 532 | const ValueToValueMapTy &VMap, |
| 533 | PhiToDefMap &MPhiMap, |
| 534 | bool CloneWasSimplified, |
| 535 | MemorySSA *MSSA) { |
| 536 | MemoryAccess *InsnDefining = MA; |
| 537 | if (MemoryDef *DefMUD = dyn_cast<MemoryDef>(InsnDefining)) { |
| 538 | if (!MSSA->isLiveOnEntryDef(DefMUD)) { |
| 539 | Instruction *DefMUDI = DefMUD->getMemoryInst(); |
| 540 | assert(DefMUDI && "Found MemoryUseOrDef with no Instruction."); |
| 541 | if (Instruction *NewDefMUDI = |
| 542 | cast_or_null<Instruction>(VMap.lookup(DefMUDI))) { |
| 543 | InsnDefining = MSSA->getMemoryAccess(NewDefMUDI); |
| 544 | if (!CloneWasSimplified) |
| 545 | assert(InsnDefining && "Defining instruction cannot be nullptr."); |
| 546 | else if (!InsnDefining || isa<MemoryUse>(InsnDefining)) { |
| 547 | // The clone was simplified, it's no longer a MemoryDef, look up. |
| 548 | auto DefIt = DefMUD->getDefsIterator(); |
| 549 | // Since simplified clones only occur in single block cloning, a |
| 550 | // previous definition must exist, otherwise NewDefMUDI would not |
| 551 | // have been found in VMap. |
| 552 | assert(DefIt != MSSA->getBlockDefs(DefMUD->getBlock())->begin() && |
| 553 | "Previous def must exist"); |
| 554 | InsnDefining = getNewDefiningAccessForClone( |
| 555 | &*(--DefIt), VMap, MPhiMap, CloneWasSimplified, MSSA); |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | } else { |
| 560 | MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining); |
| 561 | if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi)) |
| 562 | InsnDefining = NewDefPhi; |
| 563 | } |
| 564 | assert(InsnDefining && "Defining instruction cannot be nullptr."); |
| 565 | return InsnDefining; |
| 566 | } |
| 567 | |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 568 | void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB, |
| 569 | const ValueToValueMapTy &VMap, |
Alina Sbirlea | 7a0098a | 2019-06-17 18:58:40 +0000 | [diff] [blame] | 570 | PhiToDefMap &MPhiMap, |
| 571 | bool CloneWasSimplified) { |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 572 | const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); |
| 573 | if (!Acc) |
| 574 | return; |
| 575 | for (const MemoryAccess &MA : *Acc) { |
| 576 | if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) { |
| 577 | Instruction *Insn = MUD->getMemoryInst(); |
| 578 | // Entry does not exist if the clone of the block did not clone all |
| 579 | // instructions. This occurs in LoopRotate when cloning instructions |
| 580 | // from the old header to the old preheader. The cloned instruction may |
| 581 | // also be a simplified Value, not an Instruction (see LoopRotate). |
Alina Sbirlea | 7a0098a | 2019-06-17 18:58:40 +0000 | [diff] [blame] | 582 | // Also in LoopRotate, even when it's an instruction, due to it being |
| 583 | // simplified, it may be a Use rather than a Def, so we cannot use MUD as |
| 584 | // template. Calls coming from updateForClonedBlockIntoPred, ensure this. |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 585 | if (Instruction *NewInsn = |
| 586 | dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) { |
| 587 | MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess( |
Alina Sbirlea | 4bc625c | 2019-07-30 20:10:33 +0000 | [diff] [blame] | 588 | NewInsn, |
| 589 | getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap, |
| 590 | MPhiMap, CloneWasSimplified, MSSA), |
| 591 | /*Template=*/CloneWasSimplified ? nullptr : MUD, |
| 592 | /*CreationMustSucceed=*/CloneWasSimplified ? false : true); |
| 593 | if (NewUseOrDef) |
| 594 | MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 595 | } |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 600 | void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock( |
| 601 | BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) { |
| 602 | auto *MPhi = MSSA->getMemoryAccess(Header); |
| 603 | if (!MPhi) |
| 604 | return; |
| 605 | |
| 606 | // Create phi node in the backedge block and populate it with the same |
| 607 | // incoming values as MPhi. Skip incoming values coming from Preheader. |
| 608 | auto *NewMPhi = MSSA->createMemoryPhi(BEBlock); |
| 609 | bool HasUniqueIncomingValue = true; |
| 610 | MemoryAccess *UniqueValue = nullptr; |
| 611 | for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) { |
| 612 | BasicBlock *IBB = MPhi->getIncomingBlock(I); |
| 613 | MemoryAccess *IV = MPhi->getIncomingValue(I); |
| 614 | if (IBB != Preheader) { |
| 615 | NewMPhi->addIncoming(IV, IBB); |
| 616 | if (HasUniqueIncomingValue) { |
| 617 | if (!UniqueValue) |
| 618 | UniqueValue = IV; |
| 619 | else if (UniqueValue != IV) |
| 620 | HasUniqueIncomingValue = false; |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | // Update incoming edges into MPhi. Remove all but the incoming edge from |
| 626 | // Preheader. Add an edge from NewMPhi |
| 627 | auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader); |
| 628 | MPhi->setIncomingValue(0, AccFromPreheader); |
| 629 | MPhi->setIncomingBlock(0, Preheader); |
| 630 | for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I) |
| 631 | MPhi->unorderedDeleteIncoming(I); |
| 632 | MPhi->addIncoming(NewMPhi, BEBlock); |
| 633 | |
| 634 | // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be |
| 635 | // replaced with the unique value. |
Alina Sbirlea | ae40dfc | 2019-10-01 18:34:39 +0000 | [diff] [blame^] | 636 | tryRemoveTrivialPhi(NewMPhi); |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 637 | } |
| 638 | |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 639 | void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks, |
| 640 | ArrayRef<BasicBlock *> ExitBlocks, |
| 641 | const ValueToValueMapTy &VMap, |
| 642 | bool IgnoreIncomingWithNoClones) { |
| 643 | PhiToDefMap MPhiMap; |
| 644 | |
| 645 | auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) { |
| 646 | assert(Phi && NewPhi && "Invalid Phi nodes."); |
| 647 | BasicBlock *NewPhiBB = NewPhi->getBlock(); |
| 648 | SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB), |
| 649 | pred_end(NewPhiBB)); |
| 650 | for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) { |
| 651 | MemoryAccess *IncomingAccess = Phi->getIncomingValue(It); |
| 652 | BasicBlock *IncBB = Phi->getIncomingBlock(It); |
| 653 | |
| 654 | if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB))) |
| 655 | IncBB = NewIncBB; |
| 656 | else if (IgnoreIncomingWithNoClones) |
| 657 | continue; |
| 658 | |
| 659 | // Now we have IncBB, and will need to add incoming from it to NewPhi. |
| 660 | |
| 661 | // If IncBB is not a predecessor of NewPhiBB, then do not add it. |
| 662 | // NewPhiBB was cloned without that edge. |
| 663 | if (!NewPhiBBPreds.count(IncBB)) |
| 664 | continue; |
| 665 | |
| 666 | // Determine incoming value and add it as incoming from IncBB. |
| 667 | if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) { |
| 668 | if (!MSSA->isLiveOnEntryDef(IncMUD)) { |
| 669 | Instruction *IncI = IncMUD->getMemoryInst(); |
| 670 | assert(IncI && "Found MemoryUseOrDef with no Instruction."); |
| 671 | if (Instruction *NewIncI = |
| 672 | cast_or_null<Instruction>(VMap.lookup(IncI))) { |
| 673 | IncMUD = MSSA->getMemoryAccess(NewIncI); |
| 674 | assert(IncMUD && |
| 675 | "MemoryUseOrDef cannot be null, all preds processed."); |
| 676 | } |
| 677 | } |
| 678 | NewPhi->addIncoming(IncMUD, IncBB); |
| 679 | } else { |
| 680 | MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess); |
| 681 | if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi)) |
| 682 | NewPhi->addIncoming(NewDefPhi, IncBB); |
| 683 | else |
| 684 | NewPhi->addIncoming(IncPhi, IncBB); |
| 685 | } |
| 686 | } |
| 687 | }; |
| 688 | |
| 689 | auto ProcessBlock = [&](BasicBlock *BB) { |
| 690 | BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB)); |
| 691 | if (!NewBlock) |
| 692 | return; |
| 693 | |
| 694 | assert(!MSSA->getWritableBlockAccesses(NewBlock) && |
| 695 | "Cloned block should have no accesses"); |
| 696 | |
| 697 | // Add MemoryPhi. |
| 698 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) { |
| 699 | MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock); |
| 700 | MPhiMap[MPhi] = NewPhi; |
| 701 | } |
| 702 | // Update Uses and Defs. |
| 703 | cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap); |
| 704 | }; |
| 705 | |
| 706 | for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks)) |
| 707 | ProcessBlock(BB); |
| 708 | |
| 709 | for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks)) |
| 710 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) |
| 711 | if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi)) |
| 712 | FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi)); |
| 713 | } |
| 714 | |
| 715 | void MemorySSAUpdater::updateForClonedBlockIntoPred( |
| 716 | BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) { |
| 717 | // All defs/phis from outside BB that are used in BB, are valid uses in P1. |
| 718 | // Since those defs/phis must have dominated BB, and also dominate P1. |
| 719 | // Defs from BB being used in BB will be replaced with the cloned defs from |
| 720 | // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the |
| 721 | // incoming def into the Phi from P1. |
Alina Sbirlea | 7a0098a | 2019-06-17 18:58:40 +0000 | [diff] [blame] | 722 | // Instructions cloned into the predecessor are in practice sometimes |
| 723 | // simplified, so disable the use of the template, and create an access from |
| 724 | // scratch. |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 725 | PhiToDefMap MPhiMap; |
| 726 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) |
| 727 | MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1); |
Alina Sbirlea | 7a0098a | 2019-06-17 18:58:40 +0000 | [diff] [blame] | 728 | cloneUsesAndDefs(BB, P1, VM, MPhiMap, /*CloneWasSimplified=*/true); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 729 | } |
| 730 | |
| 731 | template <typename Iter> |
| 732 | void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop( |
| 733 | ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd, |
| 734 | DominatorTree &DT) { |
| 735 | SmallVector<CFGUpdate, 4> Updates; |
| 736 | // Update/insert phis in all successors of exit blocks. |
| 737 | for (auto *Exit : ExitBlocks) |
| 738 | for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd)) |
| 739 | if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) { |
| 740 | BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); |
| 741 | Updates.push_back({DT.Insert, NewExit, ExitSucc}); |
| 742 | } |
| 743 | applyInsertUpdates(Updates, DT); |
| 744 | } |
| 745 | |
| 746 | void MemorySSAUpdater::updateExitBlocksForClonedLoop( |
| 747 | ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, |
| 748 | DominatorTree &DT) { |
| 749 | const ValueToValueMapTy *const Arr[] = {&VMap}; |
| 750 | privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr), |
| 751 | std::end(Arr), DT); |
| 752 | } |
| 753 | |
| 754 | void MemorySSAUpdater::updateExitBlocksForClonedLoop( |
| 755 | ArrayRef<BasicBlock *> ExitBlocks, |
| 756 | ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) { |
| 757 | auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) { |
| 758 | return I.get(); |
| 759 | }; |
| 760 | using MappedIteratorType = |
| 761 | mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *, |
| 762 | decltype(GetPtr)>; |
| 763 | auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr); |
| 764 | auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr); |
| 765 | privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT); |
| 766 | } |
| 767 | |
| 768 | void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates, |
| 769 | DominatorTree &DT) { |
| 770 | SmallVector<CFGUpdate, 4> RevDeleteUpdates; |
| 771 | SmallVector<CFGUpdate, 4> InsertUpdates; |
| 772 | for (auto &Update : Updates) { |
| 773 | if (Update.getKind() == DT.Insert) |
| 774 | InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()}); |
| 775 | else |
| 776 | RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()}); |
| 777 | } |
| 778 | |
| 779 | if (!RevDeleteUpdates.empty()) { |
| 780 | // Update for inserted edges: use newDT and snapshot CFG as if deletes had |
Hiroshi Inoue | 02a2bb2 | 2019-02-05 08:30:48 +0000 | [diff] [blame] | 781 | // not occurred. |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 782 | // FIXME: This creates a new DT, so it's more expensive to do mix |
| 783 | // delete/inserts vs just inserts. We can do an incremental update on the DT |
| 784 | // to revert deletes, than re-delete the edges. Teaching DT to do this, is |
| 785 | // part of a pending cleanup. |
| 786 | DominatorTree NewDT(DT, RevDeleteUpdates); |
| 787 | GraphDiff<BasicBlock *> GD(RevDeleteUpdates); |
| 788 | applyInsertUpdates(InsertUpdates, NewDT, &GD); |
| 789 | } else { |
| 790 | GraphDiff<BasicBlock *> GD; |
| 791 | applyInsertUpdates(InsertUpdates, DT, &GD); |
| 792 | } |
| 793 | |
| 794 | // Update for deleted edges |
| 795 | for (auto &Update : RevDeleteUpdates) |
| 796 | removeEdge(Update.getFrom(), Update.getTo()); |
| 797 | } |
| 798 | |
| 799 | void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates, |
| 800 | DominatorTree &DT) { |
| 801 | GraphDiff<BasicBlock *> GD; |
| 802 | applyInsertUpdates(Updates, DT, &GD); |
| 803 | } |
| 804 | |
| 805 | void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates, |
| 806 | DominatorTree &DT, |
| 807 | const GraphDiff<BasicBlock *> *GD) { |
| 808 | // Get recursive last Def, assuming well formed MSSA and updated DT. |
| 809 | auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * { |
| 810 | while (true) { |
| 811 | MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB); |
| 812 | // Return last Def or Phi in BB, if it exists. |
| 813 | if (Defs) |
| 814 | return &*(--Defs->end()); |
| 815 | |
| 816 | // Check number of predecessors, we only care if there's more than one. |
| 817 | unsigned Count = 0; |
| 818 | BasicBlock *Pred = nullptr; |
| 819 | for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) { |
| 820 | Pred = Pair.second; |
| 821 | Count++; |
| 822 | if (Count == 2) |
| 823 | break; |
| 824 | } |
| 825 | |
| 826 | // If BB has multiple predecessors, get last definition from IDom. |
| 827 | if (Count != 1) { |
| 828 | // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its |
| 829 | // DT is invalidated. Return LoE as its last def. This will be added to |
| 830 | // MemoryPhi node, and later deleted when the block is deleted. |
| 831 | if (!DT.getNode(BB)) |
| 832 | return MSSA->getLiveOnEntryDef(); |
| 833 | if (auto *IDom = DT.getNode(BB)->getIDom()) |
| 834 | if (IDom->getBlock() != BB) { |
| 835 | BB = IDom->getBlock(); |
| 836 | continue; |
| 837 | } |
| 838 | return MSSA->getLiveOnEntryDef(); |
| 839 | } else { |
| 840 | // Single predecessor, BB cannot be dead. GetLastDef of Pred. |
| 841 | assert(Count == 1 && Pred && "Single predecessor expected."); |
| 842 | BB = Pred; |
| 843 | } |
| 844 | }; |
| 845 | llvm_unreachable("Unable to get last definition."); |
| 846 | }; |
| 847 | |
| 848 | // Get nearest IDom given a set of blocks. |
| 849 | // TODO: this can be optimized by starting the search at the node with the |
| 850 | // lowest level (highest in the tree). |
| 851 | auto FindNearestCommonDominator = |
| 852 | [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * { |
| 853 | BasicBlock *PrevIDom = *BBSet.begin(); |
| 854 | for (auto *BB : BBSet) |
| 855 | PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB); |
| 856 | return PrevIDom; |
| 857 | }; |
| 858 | |
| 859 | // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not |
| 860 | // include CurrIDom. |
| 861 | auto GetNoLongerDomBlocks = |
| 862 | [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom, |
| 863 | SmallVectorImpl<BasicBlock *> &BlocksPrevDom) { |
| 864 | if (PrevIDom == CurrIDom) |
| 865 | return; |
| 866 | BlocksPrevDom.push_back(PrevIDom); |
| 867 | BasicBlock *NextIDom = PrevIDom; |
| 868 | while (BasicBlock *UpIDom = |
| 869 | DT.getNode(NextIDom)->getIDom()->getBlock()) { |
| 870 | if (UpIDom == CurrIDom) |
| 871 | break; |
| 872 | BlocksPrevDom.push_back(UpIDom); |
| 873 | NextIDom = UpIDom; |
| 874 | } |
| 875 | }; |
| 876 | |
| 877 | // Map a BB to its predecessors: added + previously existing. To get a |
| 878 | // deterministic order, store predecessors as SetVectors. The order in each |
Hiroshi Inoue | 02a2bb2 | 2019-02-05 08:30:48 +0000 | [diff] [blame] | 879 | // will be defined by the order in Updates (fixed) and the order given by |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 880 | // children<> (also fixed). Since we further iterate over these ordered sets, |
| 881 | // we lose the information of multiple edges possibly existing between two |
| 882 | // blocks, so we'll keep and EdgeCount map for that. |
| 883 | // An alternate implementation could keep unordered set for the predecessors, |
| 884 | // traverse either Updates or children<> each time to get the deterministic |
| 885 | // order, and drop the usage of EdgeCount. This alternate approach would still |
| 886 | // require querying the maps for each predecessor, and children<> call has |
| 887 | // additional computation inside for creating the snapshot-graph predecessors. |
| 888 | // As such, we favor using a little additional storage and less compute time. |
| 889 | // This decision can be revisited if we find the alternative more favorable. |
| 890 | |
| 891 | struct PredInfo { |
| 892 | SmallSetVector<BasicBlock *, 2> Added; |
| 893 | SmallSetVector<BasicBlock *, 2> Prev; |
| 894 | }; |
| 895 | SmallDenseMap<BasicBlock *, PredInfo> PredMap; |
| 896 | |
| 897 | for (auto &Edge : Updates) { |
| 898 | BasicBlock *BB = Edge.getTo(); |
| 899 | auto &AddedBlockSet = PredMap[BB].Added; |
| 900 | AddedBlockSet.insert(Edge.getFrom()); |
| 901 | } |
| 902 | |
| 903 | // Store all existing predecessor for each BB, at least one must exist. |
| 904 | SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap; |
| 905 | SmallPtrSet<BasicBlock *, 2> NewBlocks; |
| 906 | for (auto &BBPredPair : PredMap) { |
| 907 | auto *BB = BBPredPair.first; |
| 908 | const auto &AddedBlockSet = BBPredPair.second.Added; |
| 909 | auto &PrevBlockSet = BBPredPair.second.Prev; |
| 910 | for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) { |
| 911 | BasicBlock *Pi = Pair.second; |
| 912 | if (!AddedBlockSet.count(Pi)) |
| 913 | PrevBlockSet.insert(Pi); |
| 914 | EdgeCountMap[{Pi, BB}]++; |
| 915 | } |
| 916 | |
| 917 | if (PrevBlockSet.empty()) { |
| 918 | assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added."); |
| 919 | LLVM_DEBUG( |
| 920 | dbgs() |
| 921 | << "Adding a predecessor to a block with no predecessors. " |
| 922 | "This must be an edge added to a new, likely cloned, block. " |
| 923 | "Its memory accesses must be already correct, assuming completed " |
| 924 | "via the updateExitBlocksForClonedLoop API. " |
| 925 | "Assert a single such edge is added so no phi addition or " |
| 926 | "additional processing is required.\n"); |
| 927 | assert(AddedBlockSet.size() == 1 && |
| 928 | "Can only handle adding one predecessor to a new block."); |
| 929 | // Need to remove new blocks from PredMap. Remove below to not invalidate |
| 930 | // iterator here. |
| 931 | NewBlocks.insert(BB); |
| 932 | } |
| 933 | } |
| 934 | // Nothing to process for new/cloned blocks. |
| 935 | for (auto *BB : NewBlocks) |
| 936 | PredMap.erase(BB); |
| 937 | |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 938 | SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace; |
Alina Sbirlea | cb4ed8a | 2019-06-11 19:09:34 +0000 | [diff] [blame] | 939 | SmallVector<WeakVH, 8> InsertedPhis; |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 940 | |
| 941 | // First create MemoryPhis in all blocks that don't have one. Create in the |
| 942 | // order found in Updates, not in PredMap, to get deterministic numbering. |
| 943 | for (auto &Edge : Updates) { |
| 944 | BasicBlock *BB = Edge.getTo(); |
| 945 | if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB)) |
Alina Sbirlea | cb4ed8a | 2019-06-11 19:09:34 +0000 | [diff] [blame] | 946 | InsertedPhis.push_back(MSSA->createMemoryPhi(BB)); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 947 | } |
| 948 | |
| 949 | // Now we'll fill in the MemoryPhis with the right incoming values. |
| 950 | for (auto &BBPredPair : PredMap) { |
| 951 | auto *BB = BBPredPair.first; |
| 952 | const auto &PrevBlockSet = BBPredPair.second.Prev; |
| 953 | const auto &AddedBlockSet = BBPredPair.second.Added; |
| 954 | assert(!PrevBlockSet.empty() && |
| 955 | "At least one previous predecessor must exist."); |
| 956 | |
| 957 | // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by |
| 958 | // keeping this map before the loop. We can reuse already populated entries |
| 959 | // if an edge is added from the same predecessor to two different blocks, |
| 960 | // and this does happen in rotate. Note that the map needs to be updated |
| 961 | // when deleting non-necessary phis below, if the phi is in the map by |
| 962 | // replacing the value with DefP1. |
| 963 | SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred; |
| 964 | for (auto *AddedPred : AddedBlockSet) { |
| 965 | auto *DefPn = GetLastDef(AddedPred); |
| 966 | assert(DefPn != nullptr && "Unable to find last definition."); |
| 967 | LastDefAddedPred[AddedPred] = DefPn; |
| 968 | } |
| 969 | |
| 970 | MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB); |
| 971 | // If Phi is not empty, add an incoming edge from each added pred. Must |
| 972 | // still compute blocks with defs to replace for this block below. |
| 973 | if (NewPhi->getNumOperands()) { |
| 974 | for (auto *Pred : AddedBlockSet) { |
| 975 | auto *LastDefForPred = LastDefAddedPred[Pred]; |
| 976 | for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) |
| 977 | NewPhi->addIncoming(LastDefForPred, Pred); |
| 978 | } |
| 979 | } else { |
| 980 | // Pick any existing predecessor and get its definition. All other |
| 981 | // existing predecessors should have the same one, since no phi existed. |
| 982 | auto *P1 = *PrevBlockSet.begin(); |
| 983 | MemoryAccess *DefP1 = GetLastDef(P1); |
| 984 | |
| 985 | // Check DefP1 against all Defs in LastDefPredPair. If all the same, |
| 986 | // nothing to add. |
| 987 | bool InsertPhi = false; |
| 988 | for (auto LastDefPredPair : LastDefAddedPred) |
| 989 | if (DefP1 != LastDefPredPair.second) { |
| 990 | InsertPhi = true; |
| 991 | break; |
| 992 | } |
| 993 | if (!InsertPhi) { |
| 994 | // Since NewPhi may be used in other newly added Phis, replace all uses |
| 995 | // of NewPhi with the definition coming from all predecessors (DefP1), |
| 996 | // before deleting it. |
| 997 | NewPhi->replaceAllUsesWith(DefP1); |
| 998 | removeMemoryAccess(NewPhi); |
| 999 | continue; |
| 1000 | } |
| 1001 | |
| 1002 | // Update Phi with new values for new predecessors and old value for all |
| 1003 | // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered |
| 1004 | // sets, the order of entries in NewPhi is deterministic. |
| 1005 | for (auto *Pred : AddedBlockSet) { |
| 1006 | auto *LastDefForPred = LastDefAddedPred[Pred]; |
| 1007 | for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) |
| 1008 | NewPhi->addIncoming(LastDefForPred, Pred); |
| 1009 | } |
| 1010 | for (auto *Pred : PrevBlockSet) |
| 1011 | for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I) |
| 1012 | NewPhi->addIncoming(DefP1, Pred); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1013 | } |
| 1014 | |
| 1015 | // Get all blocks that used to dominate BB and no longer do after adding |
| 1016 | // AddedBlockSet, where PrevBlockSet are the previously known predecessors. |
| 1017 | assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom"); |
| 1018 | BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet); |
| 1019 | assert(PrevIDom && "Previous IDom should exists"); |
| 1020 | BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock(); |
| 1021 | assert(NewIDom && "BB should have a new valid idom"); |
| 1022 | assert(DT.dominates(NewIDom, PrevIDom) && |
| 1023 | "New idom should dominate old idom"); |
| 1024 | GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace); |
| 1025 | } |
| 1026 | |
Alina Sbirlea | 109d2ea | 2019-06-19 21:33:09 +0000 | [diff] [blame] | 1027 | tryRemoveTrivialPhis(InsertedPhis); |
| 1028 | // Create the set of blocks that now have a definition. We'll use this to |
| 1029 | // compute IDF and add Phis there next. |
| 1030 | SmallVector<BasicBlock *, 8> BlocksToProcess; |
| 1031 | for (auto &VH : InsertedPhis) |
| 1032 | if (auto *MPhi = cast_or_null<MemoryPhi>(VH)) |
| 1033 | BlocksToProcess.push_back(MPhi->getBlock()); |
| 1034 | |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1035 | // Compute IDF and add Phis in all IDF blocks that do not have one. |
| 1036 | SmallVector<BasicBlock *, 32> IDFBlocks; |
| 1037 | if (!BlocksToProcess.empty()) { |
Alina Sbirlea | 238b8e6 | 2019-06-19 21:17:31 +0000 | [diff] [blame] | 1038 | ForwardIDFCalculator IDFs(DT, GD); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1039 | SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(), |
| 1040 | BlocksToProcess.end()); |
| 1041 | IDFs.setDefiningBlocks(DefiningBlocks); |
| 1042 | IDFs.calculate(IDFBlocks); |
Alina Sbirlea | 05f7780 | 2019-06-17 18:16:53 +0000 | [diff] [blame] | 1043 | |
| 1044 | SmallSetVector<MemoryPhi *, 4> PhisToFill; |
| 1045 | // First create all needed Phis. |
| 1046 | for (auto *BBIDF : IDFBlocks) |
| 1047 | if (!MSSA->getMemoryAccess(BBIDF)) { |
| 1048 | auto *IDFPhi = MSSA->createMemoryPhi(BBIDF); |
| 1049 | InsertedPhis.push_back(IDFPhi); |
| 1050 | PhisToFill.insert(IDFPhi); |
| 1051 | } |
| 1052 | // Then update or insert their correct incoming values. |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1053 | for (auto *BBIDF : IDFBlocks) { |
Alina Sbirlea | 05f7780 | 2019-06-17 18:16:53 +0000 | [diff] [blame] | 1054 | auto *IDFPhi = MSSA->getMemoryAccess(BBIDF); |
| 1055 | assert(IDFPhi && "Phi must exist"); |
| 1056 | if (!PhisToFill.count(IDFPhi)) { |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1057 | // Update existing Phi. |
| 1058 | // FIXME: some updates may be redundant, try to optimize and skip some. |
| 1059 | for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I) |
| 1060 | IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I))); |
| 1061 | } else { |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1062 | for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) { |
| 1063 | BasicBlock *Pi = Pair.second; |
| 1064 | IDFPhi->addIncoming(GetLastDef(Pi), Pi); |
| 1065 | } |
| 1066 | } |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | // Now for all defs in BlocksWithDefsToReplace, if there are uses they no |
| 1071 | // longer dominate, replace those with the closest dominating def. |
| 1072 | // This will also update optimized accesses, as they're also uses. |
| 1073 | for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) { |
| 1074 | if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) { |
| 1075 | for (auto &DefToReplaceUses : *DefsList) { |
| 1076 | BasicBlock *DominatingBlock = DefToReplaceUses.getBlock(); |
| 1077 | Value::use_iterator UI = DefToReplaceUses.use_begin(), |
| 1078 | E = DefToReplaceUses.use_end(); |
| 1079 | for (; UI != E;) { |
| 1080 | Use &U = *UI; |
| 1081 | ++UI; |
| 1082 | MemoryAccess *Usr = dyn_cast<MemoryAccess>(U.getUser()); |
| 1083 | if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) { |
| 1084 | BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U); |
| 1085 | if (!DT.dominates(DominatingBlock, DominatedBlock)) |
| 1086 | U.set(GetLastDef(DominatedBlock)); |
| 1087 | } else { |
| 1088 | BasicBlock *DominatedBlock = Usr->getBlock(); |
| 1089 | if (!DT.dominates(DominatingBlock, DominatedBlock)) { |
| 1090 | if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock)) |
| 1091 | U.set(DomBlPhi); |
| 1092 | else { |
| 1093 | auto *IDom = DT.getNode(DominatedBlock)->getIDom(); |
| 1094 | assert(IDom && "Block must have a valid IDom."); |
| 1095 | U.set(GetLastDef(IDom->getBlock())); |
| 1096 | } |
| 1097 | cast<MemoryUseOrDef>(Usr)->resetOptimized(); |
| 1098 | } |
| 1099 | } |
| 1100 | } |
| 1101 | } |
| 1102 | } |
| 1103 | } |
Alina Sbirlea | cb4ed8a | 2019-06-11 19:09:34 +0000 | [diff] [blame] | 1104 | tryRemoveTrivialPhis(InsertedPhis); |
Alina Sbirlea | 7980099 | 2018-09-10 20:13:01 +0000 | [diff] [blame] | 1105 | } |
| 1106 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1107 | // Move What before Where in the MemorySSA IR. |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1108 | template <class WhereType> |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1109 | void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB, |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1110 | WhereType Where) { |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 1111 | // Mark MemoryPhi users of What not to be optimized. |
| 1112 | for (auto *U : What->users()) |
George Burgess IV | e7cdb7e | 2018-07-12 21:56:31 +0000 | [diff] [blame] | 1113 | if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U)) |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 1114 | NonOptPhis.insert(PhiUser); |
| 1115 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1116 | // Replace all our users with our defining access. |
| 1117 | What->replaceAllUsesWith(What->getDefiningAccess()); |
| 1118 | |
| 1119 | // Let MemorySSA take care of moving it around in the lists. |
| 1120 | MSSA->moveTo(What, BB, Where); |
| 1121 | |
| 1122 | // Now reinsert it into the IR and do whatever fixups needed. |
| 1123 | if (auto *MD = dyn_cast<MemoryDef>(What)) |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 1124 | insertDef(MD, /*RenameUses=*/true); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1125 | else |
Alina Sbirlea | 1a3fdaf | 2019-08-19 18:57:40 +0000 | [diff] [blame] | 1126 | insertUse(cast<MemoryUse>(What), /*RenameUses=*/true); |
Zhaoshi Zheng | 43af17b | 2018-04-09 20:55:37 +0000 | [diff] [blame] | 1127 | |
| 1128 | // Clear dangling pointers. We added all MemoryPhi users, but not all |
| 1129 | // of them are removed by fixupDefs(). |
| 1130 | NonOptPhis.clear(); |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1131 | } |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1132 | |
Daniel Berlin | ae6b8b6 | 2017-01-28 01:35:02 +0000 | [diff] [blame] | 1133 | // Move What before Where in the MemorySSA IR. |
| 1134 | void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) { |
| 1135 | moveTo(What, Where->getBlock(), Where->getIterator()); |
| 1136 | } |
| 1137 | |
| 1138 | // Move What after Where in the MemorySSA IR. |
| 1139 | void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) { |
| 1140 | moveTo(What, Where->getBlock(), ++Where->getIterator()); |
| 1141 | } |
| 1142 | |
Daniel Berlin | 9d8a335 | 2017-01-30 11:35:39 +0000 | [diff] [blame] | 1143 | void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, |
| 1144 | MemorySSA::InsertionPlace Where) { |
| 1145 | return moveTo(What, BB, Where); |
| 1146 | } |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1147 | |
Alina Sbirlea | 0f53355 | 2018-07-11 22:11:46 +0000 | [diff] [blame] | 1148 | // All accesses in To used to be in From. Move to end and update access lists. |
| 1149 | void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To, |
| 1150 | Instruction *Start) { |
| 1151 | |
| 1152 | MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From); |
| 1153 | if (!Accs) |
| 1154 | return; |
| 1155 | |
| 1156 | MemoryAccess *FirstInNew = nullptr; |
| 1157 | for (Instruction &I : make_range(Start->getIterator(), To->end())) |
| 1158 | if ((FirstInNew = MSSA->getMemoryAccess(&I))) |
| 1159 | break; |
| 1160 | if (!FirstInNew) |
| 1161 | return; |
| 1162 | |
| 1163 | auto *MUD = cast<MemoryUseOrDef>(FirstInNew); |
| 1164 | do { |
| 1165 | auto NextIt = ++MUD->getIterator(); |
| 1166 | MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end()) |
| 1167 | ? nullptr |
| 1168 | : cast<MemoryUseOrDef>(&*NextIt); |
| 1169 | MSSA->moveTo(MUD, To, MemorySSA::End); |
| 1170 | // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to |
| 1171 | // retrieve it again. |
| 1172 | Accs = MSSA->getWritableBlockAccesses(From); |
| 1173 | MUD = NextMUD; |
| 1174 | } while (MUD); |
| 1175 | } |
| 1176 | |
| 1177 | void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From, |
| 1178 | BasicBlock *To, |
| 1179 | Instruction *Start) { |
| 1180 | assert(MSSA->getBlockAccesses(To) == nullptr && |
| 1181 | "To block is expected to be free of MemoryAccesses."); |
| 1182 | moveAllAccesses(From, To, Start); |
| 1183 | for (BasicBlock *Succ : successors(To)) |
| 1184 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ)) |
| 1185 | MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To); |
| 1186 | } |
| 1187 | |
| 1188 | void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, |
| 1189 | Instruction *Start) { |
| 1190 | assert(From->getSinglePredecessor() == To && |
| 1191 | "From block is expected to have a single predecessor (To)."); |
| 1192 | moveAllAccesses(From, To, Start); |
| 1193 | for (BasicBlock *Succ : successors(From)) |
| 1194 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ)) |
| 1195 | MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To); |
| 1196 | } |
| 1197 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 1198 | /// If all arguments of a MemoryPHI are defined by the same incoming |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1199 | /// argument, return that argument. |
| 1200 | static MemoryAccess *onlySingleValue(MemoryPhi *MP) { |
| 1201 | MemoryAccess *MA = nullptr; |
| 1202 | |
| 1203 | for (auto &Arg : MP->operands()) { |
| 1204 | if (!MA) |
| 1205 | MA = cast<MemoryAccess>(Arg); |
| 1206 | else if (MA != Arg) |
| 1207 | return nullptr; |
| 1208 | } |
| 1209 | return MA; |
| 1210 | } |
George Burgess IV | 56169ed | 2017-04-21 04:54:52 +0000 | [diff] [blame] | 1211 | |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1212 | void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor( |
Alina Sbirlea | f98c2c5 | 2018-09-07 21:14:48 +0000 | [diff] [blame] | 1213 | BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds, |
| 1214 | bool IdenticalEdgesWereMerged) { |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1215 | assert(!MSSA->getWritableBlockAccesses(New) && |
| 1216 | "Access list should be null for a new block."); |
| 1217 | MemoryPhi *Phi = MSSA->getMemoryAccess(Old); |
| 1218 | if (!Phi) |
| 1219 | return; |
Vedant Kumar | 4de31bb | 2018-11-19 19:54:27 +0000 | [diff] [blame] | 1220 | if (Old->hasNPredecessors(1)) { |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1221 | assert(pred_size(New) == Preds.size() && |
| 1222 | "Should have moved all predecessors."); |
| 1223 | MSSA->moveTo(Phi, New, MemorySSA::Beginning); |
| 1224 | } else { |
| 1225 | assert(!Preds.empty() && "Must be moving at least one predecessor to the " |
| 1226 | "new immediate predecessor."); |
| 1227 | MemoryPhi *NewPhi = MSSA->createMemoryPhi(New); |
| 1228 | SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end()); |
Alina Sbirlea | f98c2c5 | 2018-09-07 21:14:48 +0000 | [diff] [blame] | 1229 | // Currently only support the case of removing a single incoming edge when |
| 1230 | // identical edges were not merged. |
| 1231 | if (!IdenticalEdgesWereMerged) |
| 1232 | assert(PredsSet.size() == Preds.size() && |
| 1233 | "If identical edges were not merged, we cannot have duplicate " |
| 1234 | "blocks in the predecessors"); |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1235 | Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) { |
| 1236 | if (PredsSet.count(B)) { |
| 1237 | NewPhi->addIncoming(MA, B); |
Alina Sbirlea | f98c2c5 | 2018-09-07 21:14:48 +0000 | [diff] [blame] | 1238 | if (!IdenticalEdgesWereMerged) |
| 1239 | PredsSet.erase(B); |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1240 | return true; |
| 1241 | } |
| 1242 | return false; |
| 1243 | }); |
| 1244 | Phi->addIncoming(NewPhi, New); |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 1245 | tryRemoveTrivialPhi(NewPhi); |
Alina Sbirlea | 20c2962 | 2018-07-20 17:13:05 +0000 | [diff] [blame] | 1246 | } |
| 1247 | } |
| 1248 | |
Alina Sbirlea | 240a90a | 2019-01-31 20:13:47 +0000 | [diff] [blame] | 1249 | void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) { |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1250 | assert(!MSSA->isLiveOnEntryDef(MA) && |
| 1251 | "Trying to remove the live on entry def"); |
| 1252 | // We can only delete phi nodes if they have no uses, or we can replace all |
| 1253 | // uses with a single definition. |
| 1254 | MemoryAccess *NewDefTarget = nullptr; |
| 1255 | if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) { |
| 1256 | // Note that it is sufficient to know that all edges of the phi node have |
| 1257 | // the same argument. If they do, by the definition of dominance frontiers |
| 1258 | // (which we used to place this phi), that argument must dominate this phi, |
| 1259 | // and thus, must dominate the phi's uses, and so we will not hit the assert |
| 1260 | // below. |
| 1261 | NewDefTarget = onlySingleValue(MP); |
| 1262 | assert((NewDefTarget || MP->use_empty()) && |
| 1263 | "We can't delete this memory phi"); |
| 1264 | } else { |
| 1265 | NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess(); |
| 1266 | } |
| 1267 | |
Alina Sbirlea | 240a90a | 2019-01-31 20:13:47 +0000 | [diff] [blame] | 1268 | SmallSetVector<MemoryPhi *, 4> PhisToCheck; |
| 1269 | |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1270 | // Re-point the uses at our defining access |
| 1271 | if (!isa<MemoryUse>(MA) && !MA->use_empty()) { |
| 1272 | // Reset optimized on users of this store, and reset the uses. |
| 1273 | // A few notes: |
| 1274 | // 1. This is a slightly modified version of RAUW to avoid walking the |
| 1275 | // uses twice here. |
| 1276 | // 2. If we wanted to be complete, we would have to reset the optimized |
| 1277 | // flags on users of phi nodes if doing the below makes a phi node have all |
| 1278 | // the same arguments. Instead, we prefer users to removeMemoryAccess those |
| 1279 | // phi nodes, because doing it here would be N^3. |
| 1280 | if (MA->hasValueHandle()) |
| 1281 | ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget); |
| 1282 | // Note: We assume MemorySSA is not used in metadata since it's not really |
| 1283 | // part of the IR. |
| 1284 | |
| 1285 | while (!MA->use_empty()) { |
| 1286 | Use &U = *MA->use_begin(); |
Daniel Berlin | e33bc31 | 2017-04-04 23:43:10 +0000 | [diff] [blame] | 1287 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser())) |
| 1288 | MUD->resetOptimized(); |
Alina Sbirlea | 240a90a | 2019-01-31 20:13:47 +0000 | [diff] [blame] | 1289 | if (OptimizePhis) |
| 1290 | if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser())) |
| 1291 | PhisToCheck.insert(MP); |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1292 | U.set(NewDefTarget); |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | // The call below to erase will destroy MA, so we can't change the order we |
| 1297 | // are doing things here |
| 1298 | MSSA->removeFromLookups(MA); |
| 1299 | MSSA->removeFromLists(MA); |
Alina Sbirlea | 240a90a | 2019-01-31 20:13:47 +0000 | [diff] [blame] | 1300 | |
| 1301 | // Optionally optimize Phi uses. This will recursively remove trivial phis. |
| 1302 | if (!PhisToCheck.empty()) { |
| 1303 | SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(), |
| 1304 | PhisToCheck.end()}; |
| 1305 | PhisToCheck.clear(); |
| 1306 | |
| 1307 | unsigned PhisSize = PhisToOptimize.size(); |
| 1308 | while (PhisSize-- > 0) |
| 1309 | if (MemoryPhi *MP = |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 1310 | cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val())) |
| 1311 | tryRemoveTrivialPhi(MP); |
Alina Sbirlea | 240a90a | 2019-01-31 20:13:47 +0000 | [diff] [blame] | 1312 | } |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1313 | } |
| 1314 | |
Alina Sbirlea | da1e80f | 2018-06-29 20:46:16 +0000 | [diff] [blame] | 1315 | void MemorySSAUpdater::removeBlocks( |
Alina Sbirlea | db10186 | 2019-07-12 22:30:30 +0000 | [diff] [blame] | 1316 | const SmallSetVector<BasicBlock *, 8> &DeadBlocks) { |
Alina Sbirlea | da1e80f | 2018-06-29 20:46:16 +0000 | [diff] [blame] | 1317 | // First delete all uses of BB in MemoryPhis. |
| 1318 | for (BasicBlock *BB : DeadBlocks) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1319 | Instruction *TI = BB->getTerminator(); |
Alina Sbirlea | da1e80f | 2018-06-29 20:46:16 +0000 | [diff] [blame] | 1320 | assert(TI && "Basic block expected to have a terminator instruction"); |
Chandler Carruth | 96fc1de | 2018-08-26 08:41:15 +0000 | [diff] [blame] | 1321 | for (BasicBlock *Succ : successors(TI)) |
Alina Sbirlea | da1e80f | 2018-06-29 20:46:16 +0000 | [diff] [blame] | 1322 | if (!DeadBlocks.count(Succ)) |
| 1323 | if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) { |
| 1324 | MP->unorderedDeleteIncomingBlock(BB); |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 1325 | tryRemoveTrivialPhi(MP); |
Alina Sbirlea | da1e80f | 2018-06-29 20:46:16 +0000 | [diff] [blame] | 1326 | } |
| 1327 | // Drop all references of all accesses in BB |
| 1328 | if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB)) |
| 1329 | for (MemoryAccess &MA : *Acc) |
| 1330 | MA.dropAllReferences(); |
| 1331 | } |
| 1332 | |
| 1333 | // Next, delete all memory accesses in each block |
| 1334 | for (BasicBlock *BB : DeadBlocks) { |
| 1335 | MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB); |
| 1336 | if (!Acc) |
| 1337 | continue; |
| 1338 | for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) { |
| 1339 | MemoryAccess *MA = &*AB; |
| 1340 | ++AB; |
| 1341 | MSSA->removeFromLookups(MA); |
| 1342 | MSSA->removeFromLists(MA); |
| 1343 | } |
| 1344 | } |
| 1345 | } |
| 1346 | |
Alina Sbirlea | 151ab48 | 2019-05-02 23:12:49 +0000 | [diff] [blame] | 1347 | void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) { |
| 1348 | for (auto &VH : UpdatedPHIs) |
Alina Sbirlea | 2863721 | 2019-08-20 22:47:58 +0000 | [diff] [blame] | 1349 | if (auto *MPhi = cast_or_null<MemoryPhi>(VH)) |
| 1350 | tryRemoveTrivialPhi(MPhi); |
Alina Sbirlea | 151ab48 | 2019-05-02 23:12:49 +0000 | [diff] [blame] | 1351 | } |
| 1352 | |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 1353 | void MemorySSAUpdater::changeToUnreachable(const Instruction *I) { |
| 1354 | const BasicBlock *BB = I->getParent(); |
| 1355 | // Remove memory accesses in BB for I and all following instructions. |
| 1356 | auto BBI = I->getIterator(), BBE = BB->end(); |
| 1357 | // FIXME: If this becomes too expensive, iterate until the first instruction |
| 1358 | // with a memory access, then iterate over MemoryAccesses. |
| 1359 | while (BBI != BBE) |
| 1360 | removeMemoryAccess(&*(BBI++)); |
| 1361 | // Update phis in BB's successors to remove BB. |
| 1362 | SmallVector<WeakVH, 16> UpdatedPHIs; |
| 1363 | for (const BasicBlock *Successor : successors(BB)) { |
| 1364 | removeDuplicatePhiEdgesBetween(BB, Successor); |
| 1365 | if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) { |
| 1366 | MPhi->unorderedDeleteIncomingBlock(BB); |
| 1367 | UpdatedPHIs.push_back(MPhi); |
| 1368 | } |
| 1369 | } |
| 1370 | // Optimize trivial phis. |
| 1371 | tryRemoveTrivialPhis(UpdatedPHIs); |
| 1372 | } |
| 1373 | |
| 1374 | void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst *BI, |
| 1375 | const BasicBlock *To) { |
| 1376 | const BasicBlock *BB = BI->getParent(); |
| 1377 | SmallVector<WeakVH, 16> UpdatedPHIs; |
| 1378 | for (const BasicBlock *Succ : successors(BB)) { |
| 1379 | removeDuplicatePhiEdgesBetween(BB, Succ); |
| 1380 | if (Succ != To) |
| 1381 | if (auto *MPhi = MSSA->getMemoryAccess(Succ)) { |
| 1382 | MPhi->unorderedDeleteIncomingBlock(BB); |
| 1383 | UpdatedPHIs.push_back(MPhi); |
| 1384 | } |
| 1385 | } |
| 1386 | // Optimize trivial phis. |
| 1387 | tryRemoveTrivialPhis(UpdatedPHIs); |
| 1388 | } |
| 1389 | |
Daniel Berlin | 17e8d0e | 2017-02-22 22:19:55 +0000 | [diff] [blame] | 1390 | MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB( |
| 1391 | Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, |
| 1392 | MemorySSA::InsertionPlace Point) { |
| 1393 | MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); |
| 1394 | MSSA->insertIntoListsForBlock(NewAccess, BB, Point); |
| 1395 | return NewAccess; |
| 1396 | } |
| 1397 | |
| 1398 | MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore( |
| 1399 | Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) { |
| 1400 | assert(I->getParent() == InsertPt->getBlock() && |
| 1401 | "New and old access must be in the same block"); |
| 1402 | MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); |
| 1403 | MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), |
| 1404 | InsertPt->getIterator()); |
| 1405 | return NewAccess; |
| 1406 | } |
| 1407 | |
| 1408 | MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter( |
| 1409 | Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) { |
| 1410 | assert(I->getParent() == InsertPt->getBlock() && |
| 1411 | "New and old access must be in the same block"); |
| 1412 | MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition); |
| 1413 | MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(), |
| 1414 | ++InsertPt->getIterator()); |
| 1415 | return NewAccess; |
| 1416 | } |