blob: fe84ca1207ed2f89d4ef250809077286c8bee157 [file] [log] [blame]
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001//===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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 Berlinae6b8b62017-01-28 01:35:02 +00006//
7//===----------------------------------------------------------------===//
8//
9// This file implements the MemorySSAUpdater class.
10//
11//===----------------------------------------------------------------===//
Daniel Berlin554dcd82017-04-11 20:06:36 +000012#include "llvm/Analysis/MemorySSAUpdater.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000013#include "llvm/ADT/STLExtras.h"
Alina Sbirlea79800992018-09-10 20:13:01 +000014#include "llvm/ADT/SetVector.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000015#include "llvm/ADT/SmallPtrSet.h"
Alina Sbirlea79800992018-09-10 20:13:01 +000016#include "llvm/Analysis/IteratedDominanceFrontier.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/Analysis/MemorySSA.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/Dominators.h"
20#include "llvm/IR/GlobalVariable.h"
21#include "llvm/IR/IRBuilder.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000022#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 Berlinae6b8b62017-01-28 01:35:02 +000027#include <algorithm>
28
29#define DEBUG_TYPE "memoryssa"
30using namespace llvm;
George Burgess IV56169ed2017-04-21 04:54:52 +000031
Daniel Berlinae6b8b62017-01-28 01:35:02 +000032// 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 Friedman88e2bac2018-03-26 19:52:54 +000041MemoryAccess *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 IV45f263d2018-05-26 02:28:55 +000049 }
50
51 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
Eli Friedman88e2bac2018-03-26 19:52:54 +000052 // 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 IV45f263d2018-05-26 02:28:55 +000056 }
57
58 if (VisitedBlocks.count(BB)) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +000059 // 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 Friedman88e2bac2018-03-26 19:52:54 +000062 MemoryAccess *Result = MSSA->createMemoryPhi(BB);
63 CachedPreviousDef.insert({BB, Result});
64 return Result;
George Burgess IV45f263d2018-05-26 02:28:55 +000065 }
66
67 if (VisitedBlocks.insert(BB).second) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +000068 // Mark us visited so we can detect a cycle
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000069 SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps;
Daniel Berlinae6b8b62017-01-28 01:35:02 +000070
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.
74 for (auto *Pred : predecessors(BB))
Eli Friedman88e2bac2018-03-26 19:52:54 +000075 PhiOps.push_back(getPreviousDefFromEnd(Pred, CachedPreviousDef));
Daniel Berlinae6b8b62017-01-28 01:35:02 +000076
77 // Now try to simplify the ops to avoid placing a phi.
78 // This may return null if we never created a phi yet, that's okay
79 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
Daniel Berlinae6b8b62017-01-28 01:35:02 +000080
81 // See if we can avoid the phi by simplifying it.
82 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
83 // If we couldn't simplify, we may have to create a phi
84 if (Result == Phi) {
85 if (!Phi)
86 Phi = MSSA->createMemoryPhi(BB);
87
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000088 // See if the existing phi operands match what we need.
89 // Unlike normal SSA, we only allow one phi node per block, so we can't just
90 // create a new one.
91 if (Phi->getNumOperands() != 0) {
92 // FIXME: Figure out whether this is dead code and if so remove it.
93 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
94 // These will have been filled in by the recursive read we did above.
Fangrui Song75709322018-11-17 01:44:25 +000095 llvm::copy(PhiOps, Phi->op_begin());
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000096 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
97 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +000098 } else {
99 unsigned i = 0;
100 for (auto *Pred : predecessors(BB))
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000101 Phi->addIncoming(&*PhiOps[i++], Pred);
Daniel Berlin97f34e82017-09-27 05:35:19 +0000102 InsertedPHIs.push_back(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000103 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000104 Result = Phi;
105 }
Daniel Berlin97f34e82017-09-27 05:35:19 +0000106
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000107 // Set ourselves up for the next variable by resetting visited state.
108 VisitedBlocks.erase(BB);
Eli Friedman88e2bac2018-03-26 19:52:54 +0000109 CachedPreviousDef.insert({BB, Result});
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000110 return Result;
111 }
112 llvm_unreachable("Should have hit one of the three cases above");
113}
114
115// This starts at the memory access, and goes backwards in the block to find the
116// previous definition. If a definition is not found the block of the access,
117// it continues globally, creating phi nodes to ensure we have a single
118// definition.
119MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
Eli Friedman88e2bac2018-03-26 19:52:54 +0000120 if (auto *LocalResult = getPreviousDefInBlock(MA))
121 return LocalResult;
122 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
123 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000124}
125
126// This starts at the memory access, and goes backwards in the block to the find
127// the previous definition. If the definition is not found in the block of the
128// access, it returns nullptr.
129MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
130 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
131
132 // It's possible there are no defs, or we got handed the first def to start.
133 if (Defs) {
134 // If this is a def, we can just use the def iterators.
135 if (!isa<MemoryUse>(MA)) {
136 auto Iter = MA->getReverseDefsIterator();
137 ++Iter;
138 if (Iter != Defs->rend())
139 return &*Iter;
140 } else {
141 // Otherwise, have to walk the all access iterator.
Alina Sbirlea33e58722017-06-07 16:46:53 +0000142 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend();
143 for (auto &U : make_range(++MA->getReverseIterator(), End))
144 if (!isa<MemoryUse>(U))
145 return cast<MemoryAccess>(&U);
146 // Note that if MA comes before Defs->begin(), we won't hit a def.
147 return nullptr;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000148 }
149 }
150 return nullptr;
151}
152
153// This starts at the end of block
Eli Friedman88e2bac2018-03-26 19:52:54 +0000154MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(
155 BasicBlock *BB,
156 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000157 auto *Defs = MSSA->getWritableBlockDefs(BB);
158
159 if (Defs)
160 return &*Defs->rbegin();
161
Eli Friedman88e2bac2018-03-26 19:52:54 +0000162 return getPreviousDefRecursive(BB, CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000163}
164// Recurse over a set of phi uses to eliminate the trivial ones
165MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
166 if (!Phi)
167 return nullptr;
168 TrackingVH<MemoryAccess> Res(Phi);
169 SmallVector<TrackingVH<Value>, 8> Uses;
170 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
171 for (auto &U : Uses) {
172 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) {
173 auto OperRange = UsePhi->operands();
174 tryRemoveTrivialPhi(UsePhi, OperRange);
175 }
176 }
177 return Res;
178}
179
180// Eliminate trivial phis
181// Phis are trivial if they are defined either by themselves, or all the same
182// argument.
183// IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
184// We recursively try to remove them.
185template <class RangeType>
186MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
187 RangeType &Operands) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000188 // Bail out on non-opt Phis.
189 if (NonOptPhis.count(Phi))
190 return Phi;
191
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000192 // Detect equal or self arguments
193 MemoryAccess *Same = nullptr;
194 for (auto &Op : Operands) {
195 // If the same or self, good so far
196 if (Op == Phi || Op == Same)
197 continue;
198 // not the same, return the phi since it's not eliminatable by us
199 if (Same)
200 return Phi;
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000201 Same = cast<MemoryAccess>(&*Op);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000202 }
203 // Never found a non-self reference, the phi is undef
204 if (Same == nullptr)
205 return MSSA->getLiveOnEntryDef();
206 if (Phi) {
207 Phi->replaceAllUsesWith(Same);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000208 removeMemoryAccess(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000209 }
210
211 // We should only end up recursing in case we replaced something, in which
212 // case, we may have made other Phis trivial.
213 return recursePhi(Same);
214}
215
216void MemorySSAUpdater::insertUse(MemoryUse *MU) {
217 InsertedPHIs.clear();
218 MU->setDefiningAccess(getPreviousDef(MU));
219 // Unlike for defs, there is no extra work to do. Because uses do not create
220 // new may-defs, there are only two cases:
221 //
222 // 1. There was a def already below us, and therefore, we should not have
223 // created a phi node because it was already needed for the def.
224 //
225 // 2. There is no def below us, and therefore, there is no extra renaming work
226 // to do.
227}
228
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000229// Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
George Burgess IV56169ed2017-04-21 04:54:52 +0000230static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
231 MemoryAccess *NewDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000232 // Replace any operand with us an incoming block with the new defining
233 // access.
234 int i = MP->getBasicBlockIndex(BB);
235 assert(i != -1 && "Should have found the basic block in the phi");
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000236 // We can't just compare i against getNumOperands since one is signed and the
237 // other not. So use it to index into the block iterator.
238 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end();
239 ++BBIter) {
240 if (*BBIter != BB)
241 break;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000242 MP->setIncomingValue(i, NewDef);
243 ++i;
244 }
245}
246
247// A brief description of the algorithm:
248// First, we compute what should define the new def, using the SSA
249// construction algorithm.
250// Then, we update the defs below us (and any new phi nodes) in the graph to
251// point to the correct new defs, to ensure we only have one variable, and no
252// disconnected stores.
Daniel Berlin78cbd282017-02-20 22:26:03 +0000253void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000254 InsertedPHIs.clear();
255
256 // See if we had a local def, and if not, go hunting.
Eli Friedman88e2bac2018-03-26 19:52:54 +0000257 MemoryAccess *DefBefore = getPreviousDef(MD);
258 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000259
260 // There is a def before us, which means we can replace any store/phi uses
261 // of that thing with us, since we are in the way of whatever was there
262 // before.
263 // We now define that def's memorydefs and memoryphis
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000264 if (DefBeforeSameBlock) {
265 for (auto UI = DefBefore->use_begin(), UE = DefBefore->use_end();
266 UI != UE;) {
267 Use &U = *UI++;
Alexandros Lamprineas96762b32018-09-11 14:29:59 +0000268 // Leave the MemoryUses alone.
269 // Also make sure we skip ourselves to avoid self references.
270 if (isa<MemoryUse>(U.getUser()) || U.getUser() == MD)
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000271 continue;
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000272 // Defs are automatically unoptimized when the user is set to MD below,
273 // because the isOptimized() call will fail to find the same ID.
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000274 U.set(MD);
275 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000276 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000277
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000278 // and that def is now our defining access.
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000279 MD->setDefiningAccess(DefBefore);
280
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000281 // Remember the index where we may insert new phis below.
282 unsigned NewPhiIndex = InsertedPHIs.size();
283
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000284 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000285 if (!DefBeforeSameBlock) {
286 // If there was a local def before us, we must have the same effect it
287 // did. Because every may-def is the same, any phis/etc we would create, it
288 // would also have created. If there was no local def before us, we
289 // performed a global update, and have to search all successors and make
290 // sure we update the first def in each of them (following all paths until
291 // we hit the first def along each path). This may also insert phi nodes.
292 // TODO: There are other cases we can skip this work, such as when we have a
293 // single successor, and only used a straight line of single pred blocks
294 // backwards to find the def. To make that work, we'd have to track whether
295 // getDefRecursive only ever used the single predecessor case. These types
296 // of paths also only exist in between CFG simplifications.
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000297
298 // If this is the first def in the block and this insert is in an arbitrary
299 // place, compute IDF and place phis.
300 auto Iter = MD->getDefsIterator();
301 ++Iter;
302 auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end();
303 if (Iter == IterEnd) {
304 ForwardIDFCalculator IDFs(*MSSA->DT);
305 SmallVector<BasicBlock *, 32> IDFBlocks;
306 SmallPtrSet<BasicBlock *, 2> DefiningBlocks;
307 DefiningBlocks.insert(MD->getBlock());
308 IDFs.setDefiningBlocks(DefiningBlocks);
309 IDFs.calculate(IDFBlocks);
310 SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs;
311 for (auto *BBIDF : IDFBlocks)
Alina Sbirleae5890672019-03-29 21:16:31 +0000312 if (!MSSA->getMemoryAccess(BBIDF)) {
313 auto *MPhi = MSSA->createMemoryPhi(BBIDF);
314 NewInsertedPHIs.push_back(MPhi);
315 // Add the phis created into the IDF blocks to NonOptPhis, so they are
316 // not optimized out as trivial by the call to getPreviousDefFromEnd
317 // below. Once they are complete, all these Phis are added to the
318 // FixupList, and removed from NonOptPhis inside fixupDefs().
319 NonOptPhis.insert(MPhi);
320 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000321
322 for (auto &MPhi : NewInsertedPHIs) {
323 auto *BBIDF = MPhi->getBlock();
324 for (auto *Pred : predecessors(BBIDF)) {
325 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
326 MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef),
327 Pred);
328 }
329 }
330
331 // Re-take the index where we're adding the new phis, because the above
332 // call to getPreviousDefFromEnd, may have inserted into InsertedPHIs.
333 NewPhiIndex = InsertedPHIs.size();
334 for (auto &MPhi : NewInsertedPHIs) {
335 InsertedPHIs.push_back(&*MPhi);
336 FixupList.push_back(&*MPhi);
337 }
338 }
339
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000340 FixupList.push_back(MD);
341 }
342
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000343 // Remember the index where we stopped inserting new phis above, since the
344 // fixupDefs call in the loop below may insert more, that are already minimal.
345 unsigned NewPhiIndexEnd = InsertedPHIs.size();
346
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000347 while (!FixupList.empty()) {
348 unsigned StartingPHISize = InsertedPHIs.size();
349 fixupDefs(FixupList);
350 FixupList.clear();
351 // Put any new phis on the fixup list, and process them
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000352 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000353 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000354
355 // Optimize potentially non-minimal phis added in this method.
356 for (unsigned Idx = NewPhiIndex; Idx < NewPhiIndexEnd; ++Idx) {
357 if (auto *MPhi = cast_or_null<MemoryPhi>(InsertedPHIs[Idx])) {
358 auto OperRange = MPhi->operands();
359 tryRemoveTrivialPhi(MPhi, OperRange);
360 }
361 }
362
Daniel Berlin78cbd282017-02-20 22:26:03 +0000363 // Now that all fixups are done, rename all uses if we are asked.
364 if (RenameUses) {
365 SmallPtrSet<BasicBlock *, 16> Visited;
366 BasicBlock *StartBlock = MD->getBlock();
367 // We are guaranteed there is a def in the block, because we just got it
368 // handed to us in this function.
369 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
370 // Convert to incoming value if it's a memorydef. A phi *is* already an
371 // incoming value.
372 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
373 FirstDef = MD->getDefiningAccess();
374
375 MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
376 // We just inserted a phi into this block, so the incoming value will become
377 // the phi anyway, so it does not matter what we pass.
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000378 for (auto &MP : InsertedPHIs) {
379 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
380 if (Phi)
381 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
382 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000383 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000384}
385
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000386void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000387 SmallPtrSet<const BasicBlock *, 8> Seen;
388 SmallVector<const BasicBlock *, 16> Worklist;
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000389 for (auto &Var : Vars) {
390 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
391 if (!NewDef)
392 continue;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000393 // First, see if there is a local def after the operand.
394 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
395 auto DefIter = NewDef->getDefsIterator();
396
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000397 // The temporary Phi is being fixed, unmark it for not to optimize.
George Burgess IVe7cdb7e2018-07-12 21:56:31 +0000398 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000399 NonOptPhis.erase(Phi);
400
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000401 // If there is a local def after us, we only have to rename that.
402 if (++DefIter != Defs->end()) {
403 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
404 continue;
405 }
406
407 // Otherwise, we need to search down through the CFG.
408 // For each of our successors, handle it directly if their is a phi, or
409 // place on the fixup worklist.
410 for (const auto *S : successors(NewDef->getBlock())) {
411 if (auto *MP = MSSA->getMemoryAccess(S))
412 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
413 else
414 Worklist.push_back(S);
415 }
416
417 while (!Worklist.empty()) {
418 const BasicBlock *FixupBlock = Worklist.back();
419 Worklist.pop_back();
420
421 // Get the first def in the block that isn't a phi node.
422 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
423 auto *FirstDef = &*Defs->begin();
424 // The loop above and below should have taken care of phi nodes
425 assert(!isa<MemoryPhi>(FirstDef) &&
426 "Should have already handled phi nodes!");
427 // We are now this def's defining access, make sure we actually dominate
428 // it
429 assert(MSSA->dominates(NewDef, FirstDef) &&
430 "Should have dominated the new access");
431
432 // This may insert new phi nodes, because we are not guaranteed the
433 // block we are processing has a single pred, and depending where the
434 // store was inserted, it may require phi nodes below it.
435 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
436 return;
437 }
438 // We didn't find a def, so we must continue.
439 for (const auto *S : successors(FixupBlock)) {
440 // If there is a phi node, handle it.
441 // Otherwise, put the block on the worklist
442 if (auto *MP = MSSA->getMemoryAccess(S))
443 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
444 else {
445 // If we cycle, we should have ended up at a phi node that we already
446 // processed. FIXME: Double check this
447 if (!Seen.insert(S).second)
448 continue;
449 Worklist.push_back(S);
450 }
451 }
452 }
453 }
454}
455
Alina Sbirlea79800992018-09-10 20:13:01 +0000456void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) {
457 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
458 MPhi->unorderedDeleteIncomingBlock(From);
459 if (MPhi->getNumIncomingValues() == 1)
460 removeMemoryAccess(MPhi);
461 }
462}
463
464void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(BasicBlock *From,
465 BasicBlock *To) {
466 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
467 bool Found = false;
468 MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) {
469 if (From != B)
470 return false;
471 if (Found)
472 return true;
473 Found = true;
474 return false;
475 });
476 if (MPhi->getNumIncomingValues() == 1)
477 removeMemoryAccess(MPhi);
478 }
479}
480
481void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
482 const ValueToValueMapTy &VMap,
483 PhiToDefMap &MPhiMap) {
484 auto GetNewDefiningAccess = [&](MemoryAccess *MA) -> MemoryAccess * {
485 MemoryAccess *InsnDefining = MA;
486 if (MemoryUseOrDef *DefMUD = dyn_cast<MemoryUseOrDef>(InsnDefining)) {
487 if (!MSSA->isLiveOnEntryDef(DefMUD)) {
488 Instruction *DefMUDI = DefMUD->getMemoryInst();
489 assert(DefMUDI && "Found MemoryUseOrDef with no Instruction.");
490 if (Instruction *NewDefMUDI =
491 cast_or_null<Instruction>(VMap.lookup(DefMUDI)))
492 InsnDefining = MSSA->getMemoryAccess(NewDefMUDI);
493 }
494 } else {
495 MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining);
496 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi))
497 InsnDefining = NewDefPhi;
498 }
499 assert(InsnDefining && "Defining instruction cannot be nullptr.");
500 return InsnDefining;
501 };
502
503 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
504 if (!Acc)
505 return;
506 for (const MemoryAccess &MA : *Acc) {
507 if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) {
508 Instruction *Insn = MUD->getMemoryInst();
509 // Entry does not exist if the clone of the block did not clone all
510 // instructions. This occurs in LoopRotate when cloning instructions
511 // from the old header to the old preheader. The cloned instruction may
512 // also be a simplified Value, not an Instruction (see LoopRotate).
513 if (Instruction *NewInsn =
514 dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
515 MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
516 NewInsn, GetNewDefiningAccess(MUD->getDefiningAccess()), MUD);
517 MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End);
518 }
519 }
520 }
521}
522
523void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
524 ArrayRef<BasicBlock *> ExitBlocks,
525 const ValueToValueMapTy &VMap,
526 bool IgnoreIncomingWithNoClones) {
527 PhiToDefMap MPhiMap;
528
529 auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) {
530 assert(Phi && NewPhi && "Invalid Phi nodes.");
531 BasicBlock *NewPhiBB = NewPhi->getBlock();
532 SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB),
533 pred_end(NewPhiBB));
534 for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) {
535 MemoryAccess *IncomingAccess = Phi->getIncomingValue(It);
536 BasicBlock *IncBB = Phi->getIncomingBlock(It);
537
538 if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB)))
539 IncBB = NewIncBB;
540 else if (IgnoreIncomingWithNoClones)
541 continue;
542
543 // Now we have IncBB, and will need to add incoming from it to NewPhi.
544
545 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
546 // NewPhiBB was cloned without that edge.
547 if (!NewPhiBBPreds.count(IncBB))
548 continue;
549
550 // Determine incoming value and add it as incoming from IncBB.
551 if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) {
552 if (!MSSA->isLiveOnEntryDef(IncMUD)) {
553 Instruction *IncI = IncMUD->getMemoryInst();
554 assert(IncI && "Found MemoryUseOrDef with no Instruction.");
555 if (Instruction *NewIncI =
556 cast_or_null<Instruction>(VMap.lookup(IncI))) {
557 IncMUD = MSSA->getMemoryAccess(NewIncI);
558 assert(IncMUD &&
559 "MemoryUseOrDef cannot be null, all preds processed.");
560 }
561 }
562 NewPhi->addIncoming(IncMUD, IncBB);
563 } else {
564 MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess);
565 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi))
566 NewPhi->addIncoming(NewDefPhi, IncBB);
567 else
568 NewPhi->addIncoming(IncPhi, IncBB);
569 }
570 }
571 };
572
573 auto ProcessBlock = [&](BasicBlock *BB) {
574 BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB));
575 if (!NewBlock)
576 return;
577
578 assert(!MSSA->getWritableBlockAccesses(NewBlock) &&
579 "Cloned block should have no accesses");
580
581 // Add MemoryPhi.
582 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) {
583 MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock);
584 MPhiMap[MPhi] = NewPhi;
585 }
586 // Update Uses and Defs.
587 cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap);
588 };
589
590 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
591 ProcessBlock(BB);
592
593 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
594 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
595 if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi))
596 FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi));
597}
598
599void MemorySSAUpdater::updateForClonedBlockIntoPred(
600 BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) {
601 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
602 // Since those defs/phis must have dominated BB, and also dominate P1.
603 // Defs from BB being used in BB will be replaced with the cloned defs from
604 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
605 // incoming def into the Phi from P1.
606 PhiToDefMap MPhiMap;
607 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
608 MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1);
609 cloneUsesAndDefs(BB, P1, VM, MPhiMap);
610}
611
612template <typename Iter>
613void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
614 ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd,
615 DominatorTree &DT) {
616 SmallVector<CFGUpdate, 4> Updates;
617 // Update/insert phis in all successors of exit blocks.
618 for (auto *Exit : ExitBlocks)
619 for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd))
620 if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) {
621 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
622 Updates.push_back({DT.Insert, NewExit, ExitSucc});
623 }
624 applyInsertUpdates(Updates, DT);
625}
626
627void MemorySSAUpdater::updateExitBlocksForClonedLoop(
628 ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap,
629 DominatorTree &DT) {
630 const ValueToValueMapTy *const Arr[] = {&VMap};
631 privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr),
632 std::end(Arr), DT);
633}
634
635void MemorySSAUpdater::updateExitBlocksForClonedLoop(
636 ArrayRef<BasicBlock *> ExitBlocks,
637 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) {
638 auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) {
639 return I.get();
640 };
641 using MappedIteratorType =
642 mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *,
643 decltype(GetPtr)>;
644 auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr);
645 auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr);
646 privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT);
647}
648
649void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates,
650 DominatorTree &DT) {
651 SmallVector<CFGUpdate, 4> RevDeleteUpdates;
652 SmallVector<CFGUpdate, 4> InsertUpdates;
653 for (auto &Update : Updates) {
654 if (Update.getKind() == DT.Insert)
655 InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
656 else
657 RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
658 }
659
660 if (!RevDeleteUpdates.empty()) {
661 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000662 // not occurred.
Alina Sbirlea79800992018-09-10 20:13:01 +0000663 // FIXME: This creates a new DT, so it's more expensive to do mix
664 // delete/inserts vs just inserts. We can do an incremental update on the DT
665 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
666 // part of a pending cleanup.
667 DominatorTree NewDT(DT, RevDeleteUpdates);
668 GraphDiff<BasicBlock *> GD(RevDeleteUpdates);
669 applyInsertUpdates(InsertUpdates, NewDT, &GD);
670 } else {
671 GraphDiff<BasicBlock *> GD;
672 applyInsertUpdates(InsertUpdates, DT, &GD);
673 }
674
675 // Update for deleted edges
676 for (auto &Update : RevDeleteUpdates)
677 removeEdge(Update.getFrom(), Update.getTo());
678}
679
680void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
681 DominatorTree &DT) {
682 GraphDiff<BasicBlock *> GD;
683 applyInsertUpdates(Updates, DT, &GD);
684}
685
686void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
687 DominatorTree &DT,
688 const GraphDiff<BasicBlock *> *GD) {
689 // Get recursive last Def, assuming well formed MSSA and updated DT.
690 auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * {
691 while (true) {
692 MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB);
693 // Return last Def or Phi in BB, if it exists.
694 if (Defs)
695 return &*(--Defs->end());
696
697 // Check number of predecessors, we only care if there's more than one.
698 unsigned Count = 0;
699 BasicBlock *Pred = nullptr;
700 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
701 Pred = Pair.second;
702 Count++;
703 if (Count == 2)
704 break;
705 }
706
707 // If BB has multiple predecessors, get last definition from IDom.
708 if (Count != 1) {
709 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
710 // DT is invalidated. Return LoE as its last def. This will be added to
711 // MemoryPhi node, and later deleted when the block is deleted.
712 if (!DT.getNode(BB))
713 return MSSA->getLiveOnEntryDef();
714 if (auto *IDom = DT.getNode(BB)->getIDom())
715 if (IDom->getBlock() != BB) {
716 BB = IDom->getBlock();
717 continue;
718 }
719 return MSSA->getLiveOnEntryDef();
720 } else {
721 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
722 assert(Count == 1 && Pred && "Single predecessor expected.");
723 BB = Pred;
724 }
725 };
726 llvm_unreachable("Unable to get last definition.");
727 };
728
729 // Get nearest IDom given a set of blocks.
730 // TODO: this can be optimized by starting the search at the node with the
731 // lowest level (highest in the tree).
732 auto FindNearestCommonDominator =
733 [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * {
734 BasicBlock *PrevIDom = *BBSet.begin();
735 for (auto *BB : BBSet)
736 PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB);
737 return PrevIDom;
738 };
739
740 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
741 // include CurrIDom.
742 auto GetNoLongerDomBlocks =
743 [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom,
744 SmallVectorImpl<BasicBlock *> &BlocksPrevDom) {
745 if (PrevIDom == CurrIDom)
746 return;
747 BlocksPrevDom.push_back(PrevIDom);
748 BasicBlock *NextIDom = PrevIDom;
749 while (BasicBlock *UpIDom =
750 DT.getNode(NextIDom)->getIDom()->getBlock()) {
751 if (UpIDom == CurrIDom)
752 break;
753 BlocksPrevDom.push_back(UpIDom);
754 NextIDom = UpIDom;
755 }
756 };
757
758 // Map a BB to its predecessors: added + previously existing. To get a
759 // deterministic order, store predecessors as SetVectors. The order in each
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000760 // will be defined by the order in Updates (fixed) and the order given by
Alina Sbirlea79800992018-09-10 20:13:01 +0000761 // children<> (also fixed). Since we further iterate over these ordered sets,
762 // we lose the information of multiple edges possibly existing between two
763 // blocks, so we'll keep and EdgeCount map for that.
764 // An alternate implementation could keep unordered set for the predecessors,
765 // traverse either Updates or children<> each time to get the deterministic
766 // order, and drop the usage of EdgeCount. This alternate approach would still
767 // require querying the maps for each predecessor, and children<> call has
768 // additional computation inside for creating the snapshot-graph predecessors.
769 // As such, we favor using a little additional storage and less compute time.
770 // This decision can be revisited if we find the alternative more favorable.
771
772 struct PredInfo {
773 SmallSetVector<BasicBlock *, 2> Added;
774 SmallSetVector<BasicBlock *, 2> Prev;
775 };
776 SmallDenseMap<BasicBlock *, PredInfo> PredMap;
777
778 for (auto &Edge : Updates) {
779 BasicBlock *BB = Edge.getTo();
780 auto &AddedBlockSet = PredMap[BB].Added;
781 AddedBlockSet.insert(Edge.getFrom());
782 }
783
784 // Store all existing predecessor for each BB, at least one must exist.
785 SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap;
786 SmallPtrSet<BasicBlock *, 2> NewBlocks;
787 for (auto &BBPredPair : PredMap) {
788 auto *BB = BBPredPair.first;
789 const auto &AddedBlockSet = BBPredPair.second.Added;
790 auto &PrevBlockSet = BBPredPair.second.Prev;
791 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
792 BasicBlock *Pi = Pair.second;
793 if (!AddedBlockSet.count(Pi))
794 PrevBlockSet.insert(Pi);
795 EdgeCountMap[{Pi, BB}]++;
796 }
797
798 if (PrevBlockSet.empty()) {
799 assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added.");
800 LLVM_DEBUG(
801 dbgs()
802 << "Adding a predecessor to a block with no predecessors. "
803 "This must be an edge added to a new, likely cloned, block. "
804 "Its memory accesses must be already correct, assuming completed "
805 "via the updateExitBlocksForClonedLoop API. "
806 "Assert a single such edge is added so no phi addition or "
807 "additional processing is required.\n");
808 assert(AddedBlockSet.size() == 1 &&
809 "Can only handle adding one predecessor to a new block.");
810 // Need to remove new blocks from PredMap. Remove below to not invalidate
811 // iterator here.
812 NewBlocks.insert(BB);
813 }
814 }
815 // Nothing to process for new/cloned blocks.
816 for (auto *BB : NewBlocks)
817 PredMap.erase(BB);
818
819 SmallVector<BasicBlock *, 8> BlocksToProcess;
820 SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace;
821
822 // First create MemoryPhis in all blocks that don't have one. Create in the
823 // order found in Updates, not in PredMap, to get deterministic numbering.
824 for (auto &Edge : Updates) {
825 BasicBlock *BB = Edge.getTo();
826 if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB))
827 MSSA->createMemoryPhi(BB);
828 }
829
830 // Now we'll fill in the MemoryPhis with the right incoming values.
831 for (auto &BBPredPair : PredMap) {
832 auto *BB = BBPredPair.first;
833 const auto &PrevBlockSet = BBPredPair.second.Prev;
834 const auto &AddedBlockSet = BBPredPair.second.Added;
835 assert(!PrevBlockSet.empty() &&
836 "At least one previous predecessor must exist.");
837
838 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
839 // keeping this map before the loop. We can reuse already populated entries
840 // if an edge is added from the same predecessor to two different blocks,
841 // and this does happen in rotate. Note that the map needs to be updated
842 // when deleting non-necessary phis below, if the phi is in the map by
843 // replacing the value with DefP1.
844 SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred;
845 for (auto *AddedPred : AddedBlockSet) {
846 auto *DefPn = GetLastDef(AddedPred);
847 assert(DefPn != nullptr && "Unable to find last definition.");
848 LastDefAddedPred[AddedPred] = DefPn;
849 }
850
851 MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB);
852 // If Phi is not empty, add an incoming edge from each added pred. Must
853 // still compute blocks with defs to replace for this block below.
854 if (NewPhi->getNumOperands()) {
855 for (auto *Pred : AddedBlockSet) {
856 auto *LastDefForPred = LastDefAddedPred[Pred];
857 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
858 NewPhi->addIncoming(LastDefForPred, Pred);
859 }
860 } else {
861 // Pick any existing predecessor and get its definition. All other
862 // existing predecessors should have the same one, since no phi existed.
863 auto *P1 = *PrevBlockSet.begin();
864 MemoryAccess *DefP1 = GetLastDef(P1);
865
866 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
867 // nothing to add.
868 bool InsertPhi = false;
869 for (auto LastDefPredPair : LastDefAddedPred)
870 if (DefP1 != LastDefPredPair.second) {
871 InsertPhi = true;
872 break;
873 }
874 if (!InsertPhi) {
875 // Since NewPhi may be used in other newly added Phis, replace all uses
876 // of NewPhi with the definition coming from all predecessors (DefP1),
877 // before deleting it.
878 NewPhi->replaceAllUsesWith(DefP1);
879 removeMemoryAccess(NewPhi);
880 continue;
881 }
882
883 // Update Phi with new values for new predecessors and old value for all
884 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
885 // sets, the order of entries in NewPhi is deterministic.
886 for (auto *Pred : AddedBlockSet) {
887 auto *LastDefForPred = LastDefAddedPred[Pred];
888 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
889 NewPhi->addIncoming(LastDefForPred, Pred);
890 }
891 for (auto *Pred : PrevBlockSet)
892 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
893 NewPhi->addIncoming(DefP1, Pred);
894
895 // Insert BB in the set of blocks that now have definition. We'll use this
896 // to compute IDF and add Phis there next.
897 BlocksToProcess.push_back(BB);
898 }
899
900 // Get all blocks that used to dominate BB and no longer do after adding
901 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
902 assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom");
903 BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet);
904 assert(PrevIDom && "Previous IDom should exists");
905 BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock();
906 assert(NewIDom && "BB should have a new valid idom");
907 assert(DT.dominates(NewIDom, PrevIDom) &&
908 "New idom should dominate old idom");
909 GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace);
910 }
911
912 // Compute IDF and add Phis in all IDF blocks that do not have one.
913 SmallVector<BasicBlock *, 32> IDFBlocks;
914 if (!BlocksToProcess.empty()) {
915 ForwardIDFCalculator IDFs(DT);
916 SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(),
917 BlocksToProcess.end());
918 IDFs.setDefiningBlocks(DefiningBlocks);
919 IDFs.calculate(IDFBlocks);
920 for (auto *BBIDF : IDFBlocks) {
921 if (auto *IDFPhi = MSSA->getMemoryAccess(BBIDF)) {
922 // Update existing Phi.
923 // FIXME: some updates may be redundant, try to optimize and skip some.
924 for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I)
925 IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I)));
926 } else {
927 IDFPhi = MSSA->createMemoryPhi(BBIDF);
928 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) {
929 BasicBlock *Pi = Pair.second;
930 IDFPhi->addIncoming(GetLastDef(Pi), Pi);
931 }
932 }
933 }
934 }
935
936 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
937 // longer dominate, replace those with the closest dominating def.
938 // This will also update optimized accesses, as they're also uses.
939 for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) {
940 if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) {
941 for (auto &DefToReplaceUses : *DefsList) {
942 BasicBlock *DominatingBlock = DefToReplaceUses.getBlock();
943 Value::use_iterator UI = DefToReplaceUses.use_begin(),
944 E = DefToReplaceUses.use_end();
945 for (; UI != E;) {
946 Use &U = *UI;
947 ++UI;
948 MemoryAccess *Usr = dyn_cast<MemoryAccess>(U.getUser());
949 if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) {
950 BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U);
951 if (!DT.dominates(DominatingBlock, DominatedBlock))
952 U.set(GetLastDef(DominatedBlock));
953 } else {
954 BasicBlock *DominatedBlock = Usr->getBlock();
955 if (!DT.dominates(DominatingBlock, DominatedBlock)) {
956 if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock))
957 U.set(DomBlPhi);
958 else {
959 auto *IDom = DT.getNode(DominatedBlock)->getIDom();
960 assert(IDom && "Block must have a valid IDom.");
961 U.set(GetLastDef(IDom->getBlock()));
962 }
963 cast<MemoryUseOrDef>(Usr)->resetOptimized();
964 }
965 }
966 }
967 }
968 }
969 }
970}
971
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000972// Move What before Where in the MemorySSA IR.
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000973template <class WhereType>
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000974void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000975 WhereType Where) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000976 // Mark MemoryPhi users of What not to be optimized.
977 for (auto *U : What->users())
George Burgess IVe7cdb7e2018-07-12 21:56:31 +0000978 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000979 NonOptPhis.insert(PhiUser);
980
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000981 // Replace all our users with our defining access.
982 What->replaceAllUsesWith(What->getDefiningAccess());
983
984 // Let MemorySSA take care of moving it around in the lists.
985 MSSA->moveTo(What, BB, Where);
986
987 // Now reinsert it into the IR and do whatever fixups needed.
988 if (auto *MD = dyn_cast<MemoryDef>(What))
989 insertDef(MD);
990 else
991 insertUse(cast<MemoryUse>(What));
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000992
993 // Clear dangling pointers. We added all MemoryPhi users, but not all
994 // of them are removed by fixupDefs().
995 NonOptPhis.clear();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000996}
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000997
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000998// Move What before Where in the MemorySSA IR.
999void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1000 moveTo(What, Where->getBlock(), Where->getIterator());
1001}
1002
1003// Move What after Where in the MemorySSA IR.
1004void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1005 moveTo(What, Where->getBlock(), ++Where->getIterator());
1006}
1007
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001008void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
1009 MemorySSA::InsertionPlace Where) {
1010 return moveTo(What, BB, Where);
1011}
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001012
Alina Sbirlea0f533552018-07-11 22:11:46 +00001013// All accesses in To used to be in From. Move to end and update access lists.
1014void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
1015 Instruction *Start) {
1016
1017 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
1018 if (!Accs)
1019 return;
1020
1021 MemoryAccess *FirstInNew = nullptr;
1022 for (Instruction &I : make_range(Start->getIterator(), To->end()))
1023 if ((FirstInNew = MSSA->getMemoryAccess(&I)))
1024 break;
1025 if (!FirstInNew)
1026 return;
1027
1028 auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
1029 do {
1030 auto NextIt = ++MUD->getIterator();
1031 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
1032 ? nullptr
1033 : cast<MemoryUseOrDef>(&*NextIt);
1034 MSSA->moveTo(MUD, To, MemorySSA::End);
1035 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
1036 // retrieve it again.
1037 Accs = MSSA->getWritableBlockAccesses(From);
1038 MUD = NextMUD;
1039 } while (MUD);
1040}
1041
1042void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
1043 BasicBlock *To,
1044 Instruction *Start) {
1045 assert(MSSA->getBlockAccesses(To) == nullptr &&
1046 "To block is expected to be free of MemoryAccesses.");
1047 moveAllAccesses(From, To, Start);
1048 for (BasicBlock *Succ : successors(To))
1049 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1050 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1051}
1052
1053void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
1054 Instruction *Start) {
1055 assert(From->getSinglePredecessor() == To &&
1056 "From block is expected to have a single predecessor (To).");
1057 moveAllAccesses(From, To, Start);
1058 for (BasicBlock *Succ : successors(From))
1059 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1060 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1061}
1062
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001063/// If all arguments of a MemoryPHI are defined by the same incoming
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001064/// argument, return that argument.
1065static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1066 MemoryAccess *MA = nullptr;
1067
1068 for (auto &Arg : MP->operands()) {
1069 if (!MA)
1070 MA = cast<MemoryAccess>(Arg);
1071 else if (MA != Arg)
1072 return nullptr;
1073 }
1074 return MA;
1075}
George Burgess IV56169ed2017-04-21 04:54:52 +00001076
Alina Sbirlea20c29622018-07-20 17:13:05 +00001077void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001078 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
1079 bool IdenticalEdgesWereMerged) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001080 assert(!MSSA->getWritableBlockAccesses(New) &&
1081 "Access list should be null for a new block.");
1082 MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
1083 if (!Phi)
1084 return;
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001085 if (Old->hasNPredecessors(1)) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001086 assert(pred_size(New) == Preds.size() &&
1087 "Should have moved all predecessors.");
1088 MSSA->moveTo(Phi, New, MemorySSA::Beginning);
1089 } else {
1090 assert(!Preds.empty() && "Must be moving at least one predecessor to the "
1091 "new immediate predecessor.");
1092 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
1093 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001094 // Currently only support the case of removing a single incoming edge when
1095 // identical edges were not merged.
1096 if (!IdenticalEdgesWereMerged)
1097 assert(PredsSet.size() == Preds.size() &&
1098 "If identical edges were not merged, we cannot have duplicate "
1099 "blocks in the predecessors");
Alina Sbirlea20c29622018-07-20 17:13:05 +00001100 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
1101 if (PredsSet.count(B)) {
1102 NewPhi->addIncoming(MA, B);
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001103 if (!IdenticalEdgesWereMerged)
1104 PredsSet.erase(B);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001105 return true;
1106 }
1107 return false;
1108 });
1109 Phi->addIncoming(NewPhi, New);
1110 if (onlySingleValue(NewPhi))
1111 removeMemoryAccess(NewPhi);
1112 }
1113}
1114
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001115void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) {
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001116 assert(!MSSA->isLiveOnEntryDef(MA) &&
1117 "Trying to remove the live on entry def");
1118 // We can only delete phi nodes if they have no uses, or we can replace all
1119 // uses with a single definition.
1120 MemoryAccess *NewDefTarget = nullptr;
1121 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1122 // Note that it is sufficient to know that all edges of the phi node have
1123 // the same argument. If they do, by the definition of dominance frontiers
1124 // (which we used to place this phi), that argument must dominate this phi,
1125 // and thus, must dominate the phi's uses, and so we will not hit the assert
1126 // below.
1127 NewDefTarget = onlySingleValue(MP);
1128 assert((NewDefTarget || MP->use_empty()) &&
1129 "We can't delete this memory phi");
1130 } else {
1131 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1132 }
1133
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001134 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
1135
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001136 // Re-point the uses at our defining access
1137 if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
1138 // Reset optimized on users of this store, and reset the uses.
1139 // A few notes:
1140 // 1. This is a slightly modified version of RAUW to avoid walking the
1141 // uses twice here.
1142 // 2. If we wanted to be complete, we would have to reset the optimized
1143 // flags on users of phi nodes if doing the below makes a phi node have all
1144 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1145 // phi nodes, because doing it here would be N^3.
1146 if (MA->hasValueHandle())
1147 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
1148 // Note: We assume MemorySSA is not used in metadata since it's not really
1149 // part of the IR.
1150
1151 while (!MA->use_empty()) {
1152 Use &U = *MA->use_begin();
Daniel Berline33bc312017-04-04 23:43:10 +00001153 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
1154 MUD->resetOptimized();
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001155 if (OptimizePhis)
1156 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser()))
1157 PhisToCheck.insert(MP);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001158 U.set(NewDefTarget);
1159 }
1160 }
1161
1162 // The call below to erase will destroy MA, so we can't change the order we
1163 // are doing things here
1164 MSSA->removeFromLookups(MA);
1165 MSSA->removeFromLists(MA);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001166
1167 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1168 if (!PhisToCheck.empty()) {
1169 SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(),
1170 PhisToCheck.end()};
1171 PhisToCheck.clear();
1172
1173 unsigned PhisSize = PhisToOptimize.size();
1174 while (PhisSize-- > 0)
1175 if (MemoryPhi *MP =
1176 cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val())) {
1177 auto OperRange = MP->operands();
1178 tryRemoveTrivialPhi(MP, OperRange);
1179 }
1180 }
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001181}
1182
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001183void MemorySSAUpdater::removeBlocks(
1184 const SmallPtrSetImpl<BasicBlock *> &DeadBlocks) {
1185 // First delete all uses of BB in MemoryPhis.
1186 for (BasicBlock *BB : DeadBlocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001187 Instruction *TI = BB->getTerminator();
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001188 assert(TI && "Basic block expected to have a terminator instruction");
Chandler Carruth96fc1de2018-08-26 08:41:15 +00001189 for (BasicBlock *Succ : successors(TI))
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001190 if (!DeadBlocks.count(Succ))
1191 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
1192 MP->unorderedDeleteIncomingBlock(BB);
1193 if (MP->getNumIncomingValues() == 1)
1194 removeMemoryAccess(MP);
1195 }
1196 // Drop all references of all accesses in BB
1197 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
1198 for (MemoryAccess &MA : *Acc)
1199 MA.dropAllReferences();
1200 }
1201
1202 // Next, delete all memory accesses in each block
1203 for (BasicBlock *BB : DeadBlocks) {
1204 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
1205 if (!Acc)
1206 continue;
1207 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) {
1208 MemoryAccess *MA = &*AB;
1209 ++AB;
1210 MSSA->removeFromLookups(MA);
1211 MSSA->removeFromLists(MA);
1212 }
1213 }
1214}
1215
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001216MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
1217 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
1218 MemorySSA::InsertionPlace Point) {
1219 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1220 MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
1221 return NewAccess;
1222}
1223
1224MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
1225 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
1226 assert(I->getParent() == InsertPt->getBlock() &&
1227 "New and old access must be in the same block");
1228 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1229 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1230 InsertPt->getIterator());
1231 return NewAccess;
1232}
1233
1234MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
1235 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
1236 assert(I->getParent() == InsertPt->getBlock() &&
1237 "New and old access must be in the same block");
1238 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1239 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1240 ++InsertPt->getIterator());
1241 return NewAccess;
1242}