1 //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
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
7 //===----------------------------------------------------------------===//
9 // This file implements the MemorySSAUpdater class.
11 //===----------------------------------------------------------------===//
12 #include "llvm/Analysis/MemorySSAUpdater.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/Analysis/IteratedDominanceFrontier.h"
17 #include "llvm/Analysis/MemorySSA.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/IRBuilder.h"
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"
29 #define DEBUG_TYPE "memoryssa"
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.
41 MemoryAccess
*MemorySSAUpdater::getPreviousDefRecursive(
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
;
51 if (BasicBlock
*Pred
= BB
->getSinglePredecessor()) {
52 // Single predecessor case, just recurse, we can only have one definition.
53 MemoryAccess
*Result
= getPreviousDefFromEnd(Pred
, CachedPreviousDef
);
54 CachedPreviousDef
.insert({BB
, Result
});
58 if (VisitedBlocks
.count(BB
)) {
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.
62 MemoryAccess
*Result
= MSSA
->createMemoryPhi(BB
);
63 CachedPreviousDef
.insert({BB
, Result
});
67 if (VisitedBlocks
.insert(BB
).second
) {
68 // Mark us visited so we can detect a cycle
69 SmallVector
<TrackingVH
<MemoryAccess
>, 8> PhiOps
;
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
))
75 if (MSSA
->DT
->isReachableFromEntry(Pred
))
76 PhiOps
.push_back(getPreviousDefFromEnd(Pred
, CachedPreviousDef
));
78 PhiOps
.push_back(MSSA
->getLiveOnEntryDef());
80 // Now try to simplify the ops to avoid placing a phi.
81 // This may return null if we never created a phi yet, that's okay
82 MemoryPhi
*Phi
= dyn_cast_or_null
<MemoryPhi
>(MSSA
->getMemoryAccess(BB
));
84 // See if we can avoid the phi by simplifying it.
85 auto *Result
= tryRemoveTrivialPhi(Phi
, PhiOps
);
86 // If we couldn't simplify, we may have to create a phi
89 Phi
= MSSA
->createMemoryPhi(BB
);
91 // See if the existing phi operands match what we need.
92 // Unlike normal SSA, we only allow one phi node per block, so we can't just
94 if (Phi
->getNumOperands() != 0) {
95 // FIXME: Figure out whether this is dead code and if so remove it.
96 if (!std::equal(Phi
->op_begin(), Phi
->op_end(), PhiOps
.begin())) {
97 // These will have been filled in by the recursive read we did above.
98 llvm::copy(PhiOps
, Phi
->op_begin());
99 std::copy(pred_begin(BB
), pred_end(BB
), Phi
->block_begin());
103 for (auto *Pred
: predecessors(BB
))
104 Phi
->addIncoming(&*PhiOps
[i
++], Pred
);
105 InsertedPHIs
.push_back(Phi
);
110 // Set ourselves up for the next variable by resetting visited state.
111 VisitedBlocks
.erase(BB
);
112 CachedPreviousDef
.insert({BB
, Result
});
115 llvm_unreachable("Should have hit one of the three cases above");
118 // This starts at the memory access, and goes backwards in the block to find the
119 // previous definition. If a definition is not found the block of the access,
120 // it continues globally, creating phi nodes to ensure we have a single
122 MemoryAccess
*MemorySSAUpdater::getPreviousDef(MemoryAccess
*MA
) {
123 if (auto *LocalResult
= getPreviousDefInBlock(MA
))
125 DenseMap
<BasicBlock
*, TrackingVH
<MemoryAccess
>> CachedPreviousDef
;
126 return getPreviousDefRecursive(MA
->getBlock(), CachedPreviousDef
);
129 // This starts at the memory access, and goes backwards in the block to the find
130 // the previous definition. If the definition is not found in the block of the
131 // access, it returns nullptr.
132 MemoryAccess
*MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess
*MA
) {
133 auto *Defs
= MSSA
->getWritableBlockDefs(MA
->getBlock());
135 // It's possible there are no defs, or we got handed the first def to start.
137 // If this is a def, we can just use the def iterators.
138 if (!isa
<MemoryUse
>(MA
)) {
139 auto Iter
= MA
->getReverseDefsIterator();
141 if (Iter
!= Defs
->rend())
144 // Otherwise, have to walk the all access iterator.
145 auto End
= MSSA
->getWritableBlockAccesses(MA
->getBlock())->rend();
146 for (auto &U
: make_range(++MA
->getReverseIterator(), End
))
147 if (!isa
<MemoryUse
>(U
))
148 return cast
<MemoryAccess
>(&U
);
149 // Note that if MA comes before Defs->begin(), we won't hit a def.
156 // This starts at the end of block
157 MemoryAccess
*MemorySSAUpdater::getPreviousDefFromEnd(
159 DenseMap
<BasicBlock
*, TrackingVH
<MemoryAccess
>> &CachedPreviousDef
) {
160 auto *Defs
= MSSA
->getWritableBlockDefs(BB
);
163 CachedPreviousDef
.insert({BB
, &*Defs
->rbegin()});
164 return &*Defs
->rbegin();
167 return getPreviousDefRecursive(BB
, CachedPreviousDef
);
169 // Recurse over a set of phi uses to eliminate the trivial ones
170 MemoryAccess
*MemorySSAUpdater::recursePhi(MemoryAccess
*Phi
) {
173 TrackingVH
<MemoryAccess
> Res(Phi
);
174 SmallVector
<TrackingVH
<Value
>, 8> Uses
;
175 std::copy(Phi
->user_begin(), Phi
->user_end(), std::back_inserter(Uses
));
177 if (MemoryPhi
*UsePhi
= dyn_cast
<MemoryPhi
>(&*U
))
178 tryRemoveTrivialPhi(UsePhi
);
182 // Eliminate trivial phis
183 // Phis are trivial if they are defined either by themselves, or all the same
185 // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
186 // We recursively try to remove them.
187 MemoryAccess
*MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi
*Phi
) {
188 assert(Phi
&& "Can only remove concrete Phi.");
189 auto OperRange
= Phi
->operands();
190 return tryRemoveTrivialPhi(Phi
, OperRange
);
192 template <class RangeType
>
193 MemoryAccess
*MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi
*Phi
,
194 RangeType
&Operands
) {
195 // Bail out on non-opt Phis.
196 if (NonOptPhis
.count(Phi
))
199 // Detect equal or self arguments
200 MemoryAccess
*Same
= nullptr;
201 for (auto &Op
: Operands
) {
202 // If the same or self, good so far
203 if (Op
== Phi
|| Op
== Same
)
205 // not the same, return the phi since it's not eliminatable by us
208 Same
= cast
<MemoryAccess
>(&*Op
);
210 // Never found a non-self reference, the phi is undef
212 return MSSA
->getLiveOnEntryDef();
214 Phi
->replaceAllUsesWith(Same
);
215 removeMemoryAccess(Phi
);
218 // We should only end up recursing in case we replaced something, in which
219 // case, we may have made other Phis trivial.
220 return recursePhi(Same
);
223 void MemorySSAUpdater::insertUse(MemoryUse
*MU
, bool RenameUses
) {
224 InsertedPHIs
.clear();
225 MU
->setDefiningAccess(getPreviousDef(MU
));
226 // In cases without unreachable blocks, because uses do not create new
227 // may-defs, there are only two cases:
228 // 1. There was a def already below us, and therefore, we should not have
229 // created a phi node because it was already needed for the def.
231 // 2. There is no def below us, and therefore, there is no extra renaming work
234 // In cases with unreachable blocks, where the unnecessary Phis were
235 // optimized out, adding the Use may re-insert those Phis. Hence, when
236 // inserting Uses outside of the MSSA creation process, and new Phis were
237 // added, rename all uses if we are asked.
239 if (!RenameUses
&& !InsertedPHIs
.empty()) {
240 auto *Defs
= MSSA
->getBlockDefs(MU
->getBlock());
242 assert((!Defs
|| (++Defs
->begin() == Defs
->end())) &&
243 "Block may have only a Phi or no defs");
246 if (RenameUses
&& InsertedPHIs
.size()) {
247 SmallPtrSet
<BasicBlock
*, 16> Visited
;
248 BasicBlock
*StartBlock
= MU
->getBlock();
250 if (auto *Defs
= MSSA
->getWritableBlockDefs(StartBlock
)) {
251 MemoryAccess
*FirstDef
= &*Defs
->begin();
252 // Convert to incoming value if it's a memorydef. A phi *is* already an
254 if (auto *MD
= dyn_cast
<MemoryDef
>(FirstDef
))
255 FirstDef
= MD
->getDefiningAccess();
257 MSSA
->renamePass(MU
->getBlock(), FirstDef
, Visited
);
259 // We just inserted a phi into this block, so the incoming value will
260 // become the phi anyway, so it does not matter what we pass.
261 for (auto &MP
: InsertedPHIs
)
262 if (MemoryPhi
*Phi
= cast_or_null
<MemoryPhi
>(MP
))
263 MSSA
->renamePass(Phi
->getBlock(), nullptr, Visited
);
267 // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
268 static void setMemoryPhiValueForBlock(MemoryPhi
*MP
, const BasicBlock
*BB
,
269 MemoryAccess
*NewDef
) {
270 // Replace any operand with us an incoming block with the new defining
272 int i
= MP
->getBasicBlockIndex(BB
);
273 assert(i
!= -1 && "Should have found the basic block in the phi");
274 // We can't just compare i against getNumOperands since one is signed and the
275 // other not. So use it to index into the block iterator.
276 for (auto BBIter
= MP
->block_begin() + i
; BBIter
!= MP
->block_end();
280 MP
->setIncomingValue(i
, NewDef
);
285 // A brief description of the algorithm:
286 // First, we compute what should define the new def, using the SSA
287 // construction algorithm.
288 // Then, we update the defs below us (and any new phi nodes) in the graph to
289 // point to the correct new defs, to ensure we only have one variable, and no
290 // disconnected stores.
291 void MemorySSAUpdater::insertDef(MemoryDef
*MD
, bool RenameUses
) {
292 InsertedPHIs
.clear();
294 // See if we had a local def, and if not, go hunting.
295 MemoryAccess
*DefBefore
= getPreviousDef(MD
);
296 bool DefBeforeSameBlock
= DefBefore
->getBlock() == MD
->getBlock();
298 // There is a def before us, which means we can replace any store/phi uses
299 // of that thing with us, since we are in the way of whatever was there
301 // We now define that def's memorydefs and memoryphis
302 if (DefBeforeSameBlock
) {
303 DefBefore
->replaceUsesWithIf(MD
, [MD
](Use
&U
) {
304 // Leave the MemoryUses alone.
305 // Also make sure we skip ourselves to avoid self references.
306 User
*Usr
= U
.getUser();
307 return !isa
<MemoryUse
>(Usr
) && Usr
!= MD
;
308 // Defs are automatically unoptimized when the user is set to MD below,
309 // because the isOptimized() call will fail to find the same ID.
313 // and that def is now our defining access.
314 MD
->setDefiningAccess(DefBefore
);
316 SmallVector
<WeakVH
, 8> FixupList(InsertedPHIs
.begin(), InsertedPHIs
.end());
318 SmallPtrSet
<BasicBlock
*, 2> DefiningBlocks
;
320 if (!DefBeforeSameBlock
) {
321 // If there was a local def before us, we must have the same effect it
322 // did. Because every may-def is the same, any phis/etc we would create, it
323 // would also have created. If there was no local def before us, we
324 // performed a global update, and have to search all successors and make
325 // sure we update the first def in each of them (following all paths until
326 // we hit the first def along each path). This may also insert phi nodes.
327 // TODO: There are other cases we can skip this work, such as when we have a
328 // single successor, and only used a straight line of single pred blocks
329 // backwards to find the def. To make that work, we'd have to track whether
330 // getDefRecursive only ever used the single predecessor case. These types
331 // of paths also only exist in between CFG simplifications.
333 // If this is the first def in the block and this insert is in an arbitrary
334 // place, compute IDF and place phis.
335 auto Iter
= MD
->getDefsIterator();
337 auto IterEnd
= MSSA
->getBlockDefs(MD
->getBlock())->end();
339 DefiningBlocks
.insert(MD
->getBlock());
341 FixupList
.push_back(MD
);
344 ForwardIDFCalculator
IDFs(*MSSA
->DT
);
345 SmallVector
<BasicBlock
*, 32> IDFBlocks
;
346 for (const auto &VH
: InsertedPHIs
)
347 if (const auto *RealPHI
= cast_or_null
<MemoryPhi
>(VH
))
348 DefiningBlocks
.insert(RealPHI
->getBlock());
349 IDFs
.setDefiningBlocks(DefiningBlocks
);
350 IDFs
.calculate(IDFBlocks
);
351 SmallVector
<AssertingVH
<MemoryPhi
>, 4> NewInsertedPHIs
;
352 for (auto *BBIDF
: IDFBlocks
) {
353 auto *MPhi
= MSSA
->getMemoryAccess(BBIDF
);
355 MPhi
= MSSA
->createMemoryPhi(BBIDF
);
356 NewInsertedPHIs
.push_back(MPhi
);
358 // Add the phis created into the IDF blocks to NonOptPhis, so they are not
359 // optimized out as trivial by the call to getPreviousDefFromEnd below. Once
360 // they are complete, all these Phis are added to the FixupList, and removed
361 // from NonOptPhis inside fixupDefs(). Existing Phis in IDF may need fixing
362 // as well, and potentially be trivial before this insertion, hence add all
363 // IDF Phis. See PR43044.
364 NonOptPhis
.insert(MPhi
);
367 for (auto &MPhi
: NewInsertedPHIs
) {
368 auto *BBIDF
= MPhi
->getBlock();
369 for (auto *Pred
: predecessors(BBIDF
)) {
370 DenseMap
<BasicBlock
*, TrackingVH
<MemoryAccess
>> CachedPreviousDef
;
371 MPhi
->addIncoming(getPreviousDefFromEnd(Pred
, CachedPreviousDef
), Pred
);
375 // Remember the index where we may insert new phis.
376 unsigned NewPhiIndex
= InsertedPHIs
.size();
377 for (auto &MPhi
: NewInsertedPHIs
) {
378 InsertedPHIs
.push_back(&*MPhi
);
379 FixupList
.push_back(&*MPhi
);
381 // Remember the index where we stopped inserting new phis above, since the
382 // fixupDefs call in the loop below may insert more, that are already minimal.
383 unsigned NewPhiIndexEnd
= InsertedPHIs
.size();
385 while (!FixupList
.empty()) {
386 unsigned StartingPHISize
= InsertedPHIs
.size();
387 fixupDefs(FixupList
);
389 // Put any new phis on the fixup list, and process them
390 FixupList
.append(InsertedPHIs
.begin() + StartingPHISize
, InsertedPHIs
.end());
393 // Optimize potentially non-minimal phis added in this method.
394 unsigned NewPhiSize
= NewPhiIndexEnd
- NewPhiIndex
;
396 tryRemoveTrivialPhis(ArrayRef
<WeakVH
>(&InsertedPHIs
[NewPhiIndex
], NewPhiSize
));
398 // Now that all fixups are done, rename all uses if we are asked.
400 SmallPtrSet
<BasicBlock
*, 16> Visited
;
401 BasicBlock
*StartBlock
= MD
->getBlock();
402 // We are guaranteed there is a def in the block, because we just got it
403 // handed to us in this function.
404 MemoryAccess
*FirstDef
= &*MSSA
->getWritableBlockDefs(StartBlock
)->begin();
405 // Convert to incoming value if it's a memorydef. A phi *is* already an
407 if (auto *MD
= dyn_cast
<MemoryDef
>(FirstDef
))
408 FirstDef
= MD
->getDefiningAccess();
410 MSSA
->renamePass(MD
->getBlock(), FirstDef
, Visited
);
411 // We just inserted a phi into this block, so the incoming value will become
412 // the phi anyway, so it does not matter what we pass.
413 for (auto &MP
: InsertedPHIs
) {
414 MemoryPhi
*Phi
= dyn_cast_or_null
<MemoryPhi
>(MP
);
416 MSSA
->renamePass(Phi
->getBlock(), nullptr, Visited
);
421 void MemorySSAUpdater::fixupDefs(const SmallVectorImpl
<WeakVH
> &Vars
) {
422 SmallPtrSet
<const BasicBlock
*, 8> Seen
;
423 SmallVector
<const BasicBlock
*, 16> Worklist
;
424 for (auto &Var
: Vars
) {
425 MemoryAccess
*NewDef
= dyn_cast_or_null
<MemoryAccess
>(Var
);
428 // First, see if there is a local def after the operand.
429 auto *Defs
= MSSA
->getWritableBlockDefs(NewDef
->getBlock());
430 auto DefIter
= NewDef
->getDefsIterator();
432 // The temporary Phi is being fixed, unmark it for not to optimize.
433 if (MemoryPhi
*Phi
= dyn_cast
<MemoryPhi
>(NewDef
))
434 NonOptPhis
.erase(Phi
);
436 // If there is a local def after us, we only have to rename that.
437 if (++DefIter
!= Defs
->end()) {
438 cast
<MemoryDef
>(DefIter
)->setDefiningAccess(NewDef
);
442 // Otherwise, we need to search down through the CFG.
443 // For each of our successors, handle it directly if their is a phi, or
444 // place on the fixup worklist.
445 for (const auto *S
: successors(NewDef
->getBlock())) {
446 if (auto *MP
= MSSA
->getMemoryAccess(S
))
447 setMemoryPhiValueForBlock(MP
, NewDef
->getBlock(), NewDef
);
449 Worklist
.push_back(S
);
452 while (!Worklist
.empty()) {
453 const BasicBlock
*FixupBlock
= Worklist
.back();
456 // Get the first def in the block that isn't a phi node.
457 if (auto *Defs
= MSSA
->getWritableBlockDefs(FixupBlock
)) {
458 auto *FirstDef
= &*Defs
->begin();
459 // The loop above and below should have taken care of phi nodes
460 assert(!isa
<MemoryPhi
>(FirstDef
) &&
461 "Should have already handled phi nodes!");
462 // We are now this def's defining access, make sure we actually dominate
464 assert(MSSA
->dominates(NewDef
, FirstDef
) &&
465 "Should have dominated the new access");
467 // This may insert new phi nodes, because we are not guaranteed the
468 // block we are processing has a single pred, and depending where the
469 // store was inserted, it may require phi nodes below it.
470 cast
<MemoryDef
>(FirstDef
)->setDefiningAccess(getPreviousDef(FirstDef
));
473 // We didn't find a def, so we must continue.
474 for (const auto *S
: successors(FixupBlock
)) {
475 // If there is a phi node, handle it.
476 // Otherwise, put the block on the worklist
477 if (auto *MP
= MSSA
->getMemoryAccess(S
))
478 setMemoryPhiValueForBlock(MP
, FixupBlock
, NewDef
);
480 // If we cycle, we should have ended up at a phi node that we already
481 // processed. FIXME: Double check this
482 if (!Seen
.insert(S
).second
)
484 Worklist
.push_back(S
);
491 void MemorySSAUpdater::removeEdge(BasicBlock
*From
, BasicBlock
*To
) {
492 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(To
)) {
493 MPhi
->unorderedDeleteIncomingBlock(From
);
494 tryRemoveTrivialPhi(MPhi
);
498 void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock
*From
,
499 const BasicBlock
*To
) {
500 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(To
)) {
502 MPhi
->unorderedDeleteIncomingIf([&](const MemoryAccess
*, BasicBlock
*B
) {
510 tryRemoveTrivialPhi(MPhi
);
514 static MemoryAccess
*getNewDefiningAccessForClone(MemoryAccess
*MA
,
515 const ValueToValueMapTy
&VMap
,
516 PhiToDefMap
&MPhiMap
,
517 bool CloneWasSimplified
,
519 MemoryAccess
*InsnDefining
= MA
;
520 if (MemoryDef
*DefMUD
= dyn_cast
<MemoryDef
>(InsnDefining
)) {
521 if (!MSSA
->isLiveOnEntryDef(DefMUD
)) {
522 Instruction
*DefMUDI
= DefMUD
->getMemoryInst();
523 assert(DefMUDI
&& "Found MemoryUseOrDef with no Instruction.");
524 if (Instruction
*NewDefMUDI
=
525 cast_or_null
<Instruction
>(VMap
.lookup(DefMUDI
))) {
526 InsnDefining
= MSSA
->getMemoryAccess(NewDefMUDI
);
527 if (!CloneWasSimplified
)
528 assert(InsnDefining
&& "Defining instruction cannot be nullptr.");
529 else if (!InsnDefining
|| isa
<MemoryUse
>(InsnDefining
)) {
530 // The clone was simplified, it's no longer a MemoryDef, look up.
531 auto DefIt
= DefMUD
->getDefsIterator();
532 // Since simplified clones only occur in single block cloning, a
533 // previous definition must exist, otherwise NewDefMUDI would not
534 // have been found in VMap.
535 assert(DefIt
!= MSSA
->getBlockDefs(DefMUD
->getBlock())->begin() &&
536 "Previous def must exist");
537 InsnDefining
= getNewDefiningAccessForClone(
538 &*(--DefIt
), VMap
, MPhiMap
, CloneWasSimplified
, MSSA
);
543 MemoryPhi
*DefPhi
= cast
<MemoryPhi
>(InsnDefining
);
544 if (MemoryAccess
*NewDefPhi
= MPhiMap
.lookup(DefPhi
))
545 InsnDefining
= NewDefPhi
;
547 assert(InsnDefining
&& "Defining instruction cannot be nullptr.");
551 void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock
*BB
, BasicBlock
*NewBB
,
552 const ValueToValueMapTy
&VMap
,
553 PhiToDefMap
&MPhiMap
,
554 bool CloneWasSimplified
) {
555 const MemorySSA::AccessList
*Acc
= MSSA
->getBlockAccesses(BB
);
558 for (const MemoryAccess
&MA
: *Acc
) {
559 if (const MemoryUseOrDef
*MUD
= dyn_cast
<MemoryUseOrDef
>(&MA
)) {
560 Instruction
*Insn
= MUD
->getMemoryInst();
561 // Entry does not exist if the clone of the block did not clone all
562 // instructions. This occurs in LoopRotate when cloning instructions
563 // from the old header to the old preheader. The cloned instruction may
564 // also be a simplified Value, not an Instruction (see LoopRotate).
565 // Also in LoopRotate, even when it's an instruction, due to it being
566 // simplified, it may be a Use rather than a Def, so we cannot use MUD as
567 // template. Calls coming from updateForClonedBlockIntoPred, ensure this.
568 if (Instruction
*NewInsn
=
569 dyn_cast_or_null
<Instruction
>(VMap
.lookup(Insn
))) {
570 MemoryAccess
*NewUseOrDef
= MSSA
->createDefinedAccess(
572 getNewDefiningAccessForClone(MUD
->getDefiningAccess(), VMap
,
573 MPhiMap
, CloneWasSimplified
, MSSA
),
574 /*Template=*/CloneWasSimplified
? nullptr : MUD
,
575 /*CreationMustSucceed=*/CloneWasSimplified
? false : true);
577 MSSA
->insertIntoListsForBlock(NewUseOrDef
, NewBB
, MemorySSA::End
);
583 void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
584 BasicBlock
*Header
, BasicBlock
*Preheader
, BasicBlock
*BEBlock
) {
585 auto *MPhi
= MSSA
->getMemoryAccess(Header
);
589 // Create phi node in the backedge block and populate it with the same
590 // incoming values as MPhi. Skip incoming values coming from Preheader.
591 auto *NewMPhi
= MSSA
->createMemoryPhi(BEBlock
);
592 bool HasUniqueIncomingValue
= true;
593 MemoryAccess
*UniqueValue
= nullptr;
594 for (unsigned I
= 0, E
= MPhi
->getNumIncomingValues(); I
!= E
; ++I
) {
595 BasicBlock
*IBB
= MPhi
->getIncomingBlock(I
);
596 MemoryAccess
*IV
= MPhi
->getIncomingValue(I
);
597 if (IBB
!= Preheader
) {
598 NewMPhi
->addIncoming(IV
, IBB
);
599 if (HasUniqueIncomingValue
) {
602 else if (UniqueValue
!= IV
)
603 HasUniqueIncomingValue
= false;
608 // Update incoming edges into MPhi. Remove all but the incoming edge from
609 // Preheader. Add an edge from NewMPhi
610 auto *AccFromPreheader
= MPhi
->getIncomingValueForBlock(Preheader
);
611 MPhi
->setIncomingValue(0, AccFromPreheader
);
612 MPhi
->setIncomingBlock(0, Preheader
);
613 for (unsigned I
= MPhi
->getNumIncomingValues() - 1; I
>= 1; --I
)
614 MPhi
->unorderedDeleteIncoming(I
);
615 MPhi
->addIncoming(NewMPhi
, BEBlock
);
617 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be
618 // replaced with the unique value.
619 tryRemoveTrivialPhi(MPhi
);
622 void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO
&LoopBlocks
,
623 ArrayRef
<BasicBlock
*> ExitBlocks
,
624 const ValueToValueMapTy
&VMap
,
625 bool IgnoreIncomingWithNoClones
) {
628 auto FixPhiIncomingValues
= [&](MemoryPhi
*Phi
, MemoryPhi
*NewPhi
) {
629 assert(Phi
&& NewPhi
&& "Invalid Phi nodes.");
630 BasicBlock
*NewPhiBB
= NewPhi
->getBlock();
631 SmallPtrSet
<BasicBlock
*, 4> NewPhiBBPreds(pred_begin(NewPhiBB
),
633 for (unsigned It
= 0, E
= Phi
->getNumIncomingValues(); It
< E
; ++It
) {
634 MemoryAccess
*IncomingAccess
= Phi
->getIncomingValue(It
);
635 BasicBlock
*IncBB
= Phi
->getIncomingBlock(It
);
637 if (BasicBlock
*NewIncBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(IncBB
)))
639 else if (IgnoreIncomingWithNoClones
)
642 // Now we have IncBB, and will need to add incoming from it to NewPhi.
644 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
645 // NewPhiBB was cloned without that edge.
646 if (!NewPhiBBPreds
.count(IncBB
))
649 // Determine incoming value and add it as incoming from IncBB.
650 if (MemoryUseOrDef
*IncMUD
= dyn_cast
<MemoryUseOrDef
>(IncomingAccess
)) {
651 if (!MSSA
->isLiveOnEntryDef(IncMUD
)) {
652 Instruction
*IncI
= IncMUD
->getMemoryInst();
653 assert(IncI
&& "Found MemoryUseOrDef with no Instruction.");
654 if (Instruction
*NewIncI
=
655 cast_or_null
<Instruction
>(VMap
.lookup(IncI
))) {
656 IncMUD
= MSSA
->getMemoryAccess(NewIncI
);
658 "MemoryUseOrDef cannot be null, all preds processed.");
661 NewPhi
->addIncoming(IncMUD
, IncBB
);
663 MemoryPhi
*IncPhi
= cast
<MemoryPhi
>(IncomingAccess
);
664 if (MemoryAccess
*NewDefPhi
= MPhiMap
.lookup(IncPhi
))
665 NewPhi
->addIncoming(NewDefPhi
, IncBB
);
667 NewPhi
->addIncoming(IncPhi
, IncBB
);
672 auto ProcessBlock
= [&](BasicBlock
*BB
) {
673 BasicBlock
*NewBlock
= cast_or_null
<BasicBlock
>(VMap
.lookup(BB
));
677 assert(!MSSA
->getWritableBlockAccesses(NewBlock
) &&
678 "Cloned block should have no accesses");
681 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
)) {
682 MemoryPhi
*NewPhi
= MSSA
->createMemoryPhi(NewBlock
);
683 MPhiMap
[MPhi
] = NewPhi
;
685 // Update Uses and Defs.
686 cloneUsesAndDefs(BB
, NewBlock
, VMap
, MPhiMap
);
689 for (auto BB
: llvm::concat
<BasicBlock
*const>(LoopBlocks
, ExitBlocks
))
692 for (auto BB
: llvm::concat
<BasicBlock
*const>(LoopBlocks
, ExitBlocks
))
693 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
))
694 if (MemoryAccess
*NewPhi
= MPhiMap
.lookup(MPhi
))
695 FixPhiIncomingValues(MPhi
, cast
<MemoryPhi
>(NewPhi
));
698 void MemorySSAUpdater::updateForClonedBlockIntoPred(
699 BasicBlock
*BB
, BasicBlock
*P1
, const ValueToValueMapTy
&VM
) {
700 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
701 // Since those defs/phis must have dominated BB, and also dominate P1.
702 // Defs from BB being used in BB will be replaced with the cloned defs from
703 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
704 // incoming def into the Phi from P1.
705 // Instructions cloned into the predecessor are in practice sometimes
706 // simplified, so disable the use of the template, and create an access from
709 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
))
710 MPhiMap
[MPhi
] = MPhi
->getIncomingValueForBlock(P1
);
711 cloneUsesAndDefs(BB
, P1
, VM
, MPhiMap
, /*CloneWasSimplified=*/true);
714 template <typename Iter
>
715 void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
716 ArrayRef
<BasicBlock
*> ExitBlocks
, Iter ValuesBegin
, Iter ValuesEnd
,
718 SmallVector
<CFGUpdate
, 4> Updates
;
719 // Update/insert phis in all successors of exit blocks.
720 for (auto *Exit
: ExitBlocks
)
721 for (const ValueToValueMapTy
*VMap
: make_range(ValuesBegin
, ValuesEnd
))
722 if (BasicBlock
*NewExit
= cast_or_null
<BasicBlock
>(VMap
->lookup(Exit
))) {
723 BasicBlock
*ExitSucc
= NewExit
->getTerminator()->getSuccessor(0);
724 Updates
.push_back({DT
.Insert
, NewExit
, ExitSucc
});
726 applyInsertUpdates(Updates
, DT
);
729 void MemorySSAUpdater::updateExitBlocksForClonedLoop(
730 ArrayRef
<BasicBlock
*> ExitBlocks
, const ValueToValueMapTy
&VMap
,
732 const ValueToValueMapTy
*const Arr
[] = {&VMap
};
733 privateUpdateExitBlocksForClonedLoop(ExitBlocks
, std::begin(Arr
),
737 void MemorySSAUpdater::updateExitBlocksForClonedLoop(
738 ArrayRef
<BasicBlock
*> ExitBlocks
,
739 ArrayRef
<std::unique_ptr
<ValueToValueMapTy
>> VMaps
, DominatorTree
&DT
) {
740 auto GetPtr
= [&](const std::unique_ptr
<ValueToValueMapTy
> &I
) {
743 using MappedIteratorType
=
744 mapped_iterator
<const std::unique_ptr
<ValueToValueMapTy
> *,
746 auto MapBegin
= MappedIteratorType(VMaps
.begin(), GetPtr
);
747 auto MapEnd
= MappedIteratorType(VMaps
.end(), GetPtr
);
748 privateUpdateExitBlocksForClonedLoop(ExitBlocks
, MapBegin
, MapEnd
, DT
);
751 void MemorySSAUpdater::applyUpdates(ArrayRef
<CFGUpdate
> Updates
,
753 SmallVector
<CFGUpdate
, 4> RevDeleteUpdates
;
754 SmallVector
<CFGUpdate
, 4> InsertUpdates
;
755 for (auto &Update
: Updates
) {
756 if (Update
.getKind() == DT
.Insert
)
757 InsertUpdates
.push_back({DT
.Insert
, Update
.getFrom(), Update
.getTo()});
759 RevDeleteUpdates
.push_back({DT
.Insert
, Update
.getFrom(), Update
.getTo()});
762 if (!RevDeleteUpdates
.empty()) {
763 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
765 // FIXME: This creates a new DT, so it's more expensive to do mix
766 // delete/inserts vs just inserts. We can do an incremental update on the DT
767 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
768 // part of a pending cleanup.
769 DominatorTree
NewDT(DT
, RevDeleteUpdates
);
770 GraphDiff
<BasicBlock
*> GD(RevDeleteUpdates
);
771 applyInsertUpdates(InsertUpdates
, NewDT
, &GD
);
773 GraphDiff
<BasicBlock
*> GD
;
774 applyInsertUpdates(InsertUpdates
, DT
, &GD
);
777 // Update for deleted edges
778 for (auto &Update
: RevDeleteUpdates
)
779 removeEdge(Update
.getFrom(), Update
.getTo());
782 void MemorySSAUpdater::applyInsertUpdates(ArrayRef
<CFGUpdate
> Updates
,
784 GraphDiff
<BasicBlock
*> GD
;
785 applyInsertUpdates(Updates
, DT
, &GD
);
788 void MemorySSAUpdater::applyInsertUpdates(ArrayRef
<CFGUpdate
> Updates
,
790 const GraphDiff
<BasicBlock
*> *GD
) {
791 // Get recursive last Def, assuming well formed MSSA and updated DT.
792 auto GetLastDef
= [&](BasicBlock
*BB
) -> MemoryAccess
* {
794 MemorySSA::DefsList
*Defs
= MSSA
->getWritableBlockDefs(BB
);
795 // Return last Def or Phi in BB, if it exists.
797 return &*(--Defs
->end());
799 // Check number of predecessors, we only care if there's more than one.
801 BasicBlock
*Pred
= nullptr;
802 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BB
})) {
809 // If BB has multiple predecessors, get last definition from IDom.
811 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
812 // DT is invalidated. Return LoE as its last def. This will be added to
813 // MemoryPhi node, and later deleted when the block is deleted.
815 return MSSA
->getLiveOnEntryDef();
816 if (auto *IDom
= DT
.getNode(BB
)->getIDom())
817 if (IDom
->getBlock() != BB
) {
818 BB
= IDom
->getBlock();
821 return MSSA
->getLiveOnEntryDef();
823 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
824 assert(Count
== 1 && Pred
&& "Single predecessor expected.");
828 llvm_unreachable("Unable to get last definition.");
831 // Get nearest IDom given a set of blocks.
832 // TODO: this can be optimized by starting the search at the node with the
833 // lowest level (highest in the tree).
834 auto FindNearestCommonDominator
=
835 [&](const SmallSetVector
<BasicBlock
*, 2> &BBSet
) -> BasicBlock
* {
836 BasicBlock
*PrevIDom
= *BBSet
.begin();
837 for (auto *BB
: BBSet
)
838 PrevIDom
= DT
.findNearestCommonDominator(PrevIDom
, BB
);
842 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
844 auto GetNoLongerDomBlocks
=
845 [&](BasicBlock
*PrevIDom
, BasicBlock
*CurrIDom
,
846 SmallVectorImpl
<BasicBlock
*> &BlocksPrevDom
) {
847 if (PrevIDom
== CurrIDom
)
849 BlocksPrevDom
.push_back(PrevIDom
);
850 BasicBlock
*NextIDom
= PrevIDom
;
851 while (BasicBlock
*UpIDom
=
852 DT
.getNode(NextIDom
)->getIDom()->getBlock()) {
853 if (UpIDom
== CurrIDom
)
855 BlocksPrevDom
.push_back(UpIDom
);
860 // Map a BB to its predecessors: added + previously existing. To get a
861 // deterministic order, store predecessors as SetVectors. The order in each
862 // will be defined by the order in Updates (fixed) and the order given by
863 // children<> (also fixed). Since we further iterate over these ordered sets,
864 // we lose the information of multiple edges possibly existing between two
865 // blocks, so we'll keep and EdgeCount map for that.
866 // An alternate implementation could keep unordered set for the predecessors,
867 // traverse either Updates or children<> each time to get the deterministic
868 // order, and drop the usage of EdgeCount. This alternate approach would still
869 // require querying the maps for each predecessor, and children<> call has
870 // additional computation inside for creating the snapshot-graph predecessors.
871 // As such, we favor using a little additional storage and less compute time.
872 // This decision can be revisited if we find the alternative more favorable.
875 SmallSetVector
<BasicBlock
*, 2> Added
;
876 SmallSetVector
<BasicBlock
*, 2> Prev
;
878 SmallDenseMap
<BasicBlock
*, PredInfo
> PredMap
;
880 for (auto &Edge
: Updates
) {
881 BasicBlock
*BB
= Edge
.getTo();
882 auto &AddedBlockSet
= PredMap
[BB
].Added
;
883 AddedBlockSet
.insert(Edge
.getFrom());
886 // Store all existing predecessor for each BB, at least one must exist.
887 SmallDenseMap
<std::pair
<BasicBlock
*, BasicBlock
*>, int> EdgeCountMap
;
888 SmallPtrSet
<BasicBlock
*, 2> NewBlocks
;
889 for (auto &BBPredPair
: PredMap
) {
890 auto *BB
= BBPredPair
.first
;
891 const auto &AddedBlockSet
= BBPredPair
.second
.Added
;
892 auto &PrevBlockSet
= BBPredPair
.second
.Prev
;
893 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BB
})) {
894 BasicBlock
*Pi
= Pair
.second
;
895 if (!AddedBlockSet
.count(Pi
))
896 PrevBlockSet
.insert(Pi
);
897 EdgeCountMap
[{Pi
, BB
}]++;
900 if (PrevBlockSet
.empty()) {
901 assert(pred_size(BB
) == AddedBlockSet
.size() && "Duplicate edges added.");
904 << "Adding a predecessor to a block with no predecessors. "
905 "This must be an edge added to a new, likely cloned, block. "
906 "Its memory accesses must be already correct, assuming completed "
907 "via the updateExitBlocksForClonedLoop API. "
908 "Assert a single such edge is added so no phi addition or "
909 "additional processing is required.\n");
910 assert(AddedBlockSet
.size() == 1 &&
911 "Can only handle adding one predecessor to a new block.");
912 // Need to remove new blocks from PredMap. Remove below to not invalidate
914 NewBlocks
.insert(BB
);
917 // Nothing to process for new/cloned blocks.
918 for (auto *BB
: NewBlocks
)
921 SmallVector
<BasicBlock
*, 16> BlocksWithDefsToReplace
;
922 SmallVector
<WeakVH
, 8> InsertedPhis
;
924 // First create MemoryPhis in all blocks that don't have one. Create in the
925 // order found in Updates, not in PredMap, to get deterministic numbering.
926 for (auto &Edge
: Updates
) {
927 BasicBlock
*BB
= Edge
.getTo();
928 if (PredMap
.count(BB
) && !MSSA
->getMemoryAccess(BB
))
929 InsertedPhis
.push_back(MSSA
->createMemoryPhi(BB
));
932 // Now we'll fill in the MemoryPhis with the right incoming values.
933 for (auto &BBPredPair
: PredMap
) {
934 auto *BB
= BBPredPair
.first
;
935 const auto &PrevBlockSet
= BBPredPair
.second
.Prev
;
936 const auto &AddedBlockSet
= BBPredPair
.second
.Added
;
937 assert(!PrevBlockSet
.empty() &&
938 "At least one previous predecessor must exist.");
940 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
941 // keeping this map before the loop. We can reuse already populated entries
942 // if an edge is added from the same predecessor to two different blocks,
943 // and this does happen in rotate. Note that the map needs to be updated
944 // when deleting non-necessary phis below, if the phi is in the map by
945 // replacing the value with DefP1.
946 SmallDenseMap
<BasicBlock
*, MemoryAccess
*> LastDefAddedPred
;
947 for (auto *AddedPred
: AddedBlockSet
) {
948 auto *DefPn
= GetLastDef(AddedPred
);
949 assert(DefPn
!= nullptr && "Unable to find last definition.");
950 LastDefAddedPred
[AddedPred
] = DefPn
;
953 MemoryPhi
*NewPhi
= MSSA
->getMemoryAccess(BB
);
954 // If Phi is not empty, add an incoming edge from each added pred. Must
955 // still compute blocks with defs to replace for this block below.
956 if (NewPhi
->getNumOperands()) {
957 for (auto *Pred
: AddedBlockSet
) {
958 auto *LastDefForPred
= LastDefAddedPred
[Pred
];
959 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
960 NewPhi
->addIncoming(LastDefForPred
, Pred
);
963 // Pick any existing predecessor and get its definition. All other
964 // existing predecessors should have the same one, since no phi existed.
965 auto *P1
= *PrevBlockSet
.begin();
966 MemoryAccess
*DefP1
= GetLastDef(P1
);
968 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
970 bool InsertPhi
= false;
971 for (auto LastDefPredPair
: LastDefAddedPred
)
972 if (DefP1
!= LastDefPredPair
.second
) {
977 // Since NewPhi may be used in other newly added Phis, replace all uses
978 // of NewPhi with the definition coming from all predecessors (DefP1),
979 // before deleting it.
980 NewPhi
->replaceAllUsesWith(DefP1
);
981 removeMemoryAccess(NewPhi
);
985 // Update Phi with new values for new predecessors and old value for all
986 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
987 // sets, the order of entries in NewPhi is deterministic.
988 for (auto *Pred
: AddedBlockSet
) {
989 auto *LastDefForPred
= LastDefAddedPred
[Pred
];
990 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
991 NewPhi
->addIncoming(LastDefForPred
, Pred
);
993 for (auto *Pred
: PrevBlockSet
)
994 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
995 NewPhi
->addIncoming(DefP1
, Pred
);
998 // Get all blocks that used to dominate BB and no longer do after adding
999 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
1000 assert(DT
.getNode(BB
)->getIDom() && "BB does not have valid idom");
1001 BasicBlock
*PrevIDom
= FindNearestCommonDominator(PrevBlockSet
);
1002 assert(PrevIDom
&& "Previous IDom should exists");
1003 BasicBlock
*NewIDom
= DT
.getNode(BB
)->getIDom()->getBlock();
1004 assert(NewIDom
&& "BB should have a new valid idom");
1005 assert(DT
.dominates(NewIDom
, PrevIDom
) &&
1006 "New idom should dominate old idom");
1007 GetNoLongerDomBlocks(PrevIDom
, NewIDom
, BlocksWithDefsToReplace
);
1010 tryRemoveTrivialPhis(InsertedPhis
);
1011 // Create the set of blocks that now have a definition. We'll use this to
1012 // compute IDF and add Phis there next.
1013 SmallVector
<BasicBlock
*, 8> BlocksToProcess
;
1014 for (auto &VH
: InsertedPhis
)
1015 if (auto *MPhi
= cast_or_null
<MemoryPhi
>(VH
))
1016 BlocksToProcess
.push_back(MPhi
->getBlock());
1018 // Compute IDF and add Phis in all IDF blocks that do not have one.
1019 SmallVector
<BasicBlock
*, 32> IDFBlocks
;
1020 if (!BlocksToProcess
.empty()) {
1021 ForwardIDFCalculator
IDFs(DT
, GD
);
1022 SmallPtrSet
<BasicBlock
*, 16> DefiningBlocks(BlocksToProcess
.begin(),
1023 BlocksToProcess
.end());
1024 IDFs
.setDefiningBlocks(DefiningBlocks
);
1025 IDFs
.calculate(IDFBlocks
);
1027 SmallSetVector
<MemoryPhi
*, 4> PhisToFill
;
1028 // First create all needed Phis.
1029 for (auto *BBIDF
: IDFBlocks
)
1030 if (!MSSA
->getMemoryAccess(BBIDF
)) {
1031 auto *IDFPhi
= MSSA
->createMemoryPhi(BBIDF
);
1032 InsertedPhis
.push_back(IDFPhi
);
1033 PhisToFill
.insert(IDFPhi
);
1035 // Then update or insert their correct incoming values.
1036 for (auto *BBIDF
: IDFBlocks
) {
1037 auto *IDFPhi
= MSSA
->getMemoryAccess(BBIDF
);
1038 assert(IDFPhi
&& "Phi must exist");
1039 if (!PhisToFill
.count(IDFPhi
)) {
1040 // Update existing Phi.
1041 // FIXME: some updates may be redundant, try to optimize and skip some.
1042 for (unsigned I
= 0, E
= IDFPhi
->getNumIncomingValues(); I
< E
; ++I
)
1043 IDFPhi
->setIncomingValue(I
, GetLastDef(IDFPhi
->getIncomingBlock(I
)));
1045 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BBIDF
})) {
1046 BasicBlock
*Pi
= Pair
.second
;
1047 IDFPhi
->addIncoming(GetLastDef(Pi
), Pi
);
1053 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
1054 // longer dominate, replace those with the closest dominating def.
1055 // This will also update optimized accesses, as they're also uses.
1056 for (auto *BlockWithDefsToReplace
: BlocksWithDefsToReplace
) {
1057 if (auto DefsList
= MSSA
->getWritableBlockDefs(BlockWithDefsToReplace
)) {
1058 for (auto &DefToReplaceUses
: *DefsList
) {
1059 BasicBlock
*DominatingBlock
= DefToReplaceUses
.getBlock();
1060 Value::use_iterator UI
= DefToReplaceUses
.use_begin(),
1061 E
= DefToReplaceUses
.use_end();
1065 MemoryAccess
*Usr
= dyn_cast
<MemoryAccess
>(U
.getUser());
1066 if (MemoryPhi
*UsrPhi
= dyn_cast
<MemoryPhi
>(Usr
)) {
1067 BasicBlock
*DominatedBlock
= UsrPhi
->getIncomingBlock(U
);
1068 if (!DT
.dominates(DominatingBlock
, DominatedBlock
))
1069 U
.set(GetLastDef(DominatedBlock
));
1071 BasicBlock
*DominatedBlock
= Usr
->getBlock();
1072 if (!DT
.dominates(DominatingBlock
, DominatedBlock
)) {
1073 if (auto *DomBlPhi
= MSSA
->getMemoryAccess(DominatedBlock
))
1076 auto *IDom
= DT
.getNode(DominatedBlock
)->getIDom();
1077 assert(IDom
&& "Block must have a valid IDom.");
1078 U
.set(GetLastDef(IDom
->getBlock()));
1080 cast
<MemoryUseOrDef
>(Usr
)->resetOptimized();
1087 tryRemoveTrivialPhis(InsertedPhis
);
1090 // Move What before Where in the MemorySSA IR.
1091 template <class WhereType
>
1092 void MemorySSAUpdater::moveTo(MemoryUseOrDef
*What
, BasicBlock
*BB
,
1094 // Mark MemoryPhi users of What not to be optimized.
1095 for (auto *U
: What
->users())
1096 if (MemoryPhi
*PhiUser
= dyn_cast
<MemoryPhi
>(U
))
1097 NonOptPhis
.insert(PhiUser
);
1099 // Replace all our users with our defining access.
1100 What
->replaceAllUsesWith(What
->getDefiningAccess());
1102 // Let MemorySSA take care of moving it around in the lists.
1103 MSSA
->moveTo(What
, BB
, Where
);
1105 // Now reinsert it into the IR and do whatever fixups needed.
1106 if (auto *MD
= dyn_cast
<MemoryDef
>(What
))
1107 insertDef(MD
, /*RenameUses=*/true);
1109 insertUse(cast
<MemoryUse
>(What
), /*RenameUses=*/true);
1111 // Clear dangling pointers. We added all MemoryPhi users, but not all
1112 // of them are removed by fixupDefs().
1116 // Move What before Where in the MemorySSA IR.
1117 void MemorySSAUpdater::moveBefore(MemoryUseOrDef
*What
, MemoryUseOrDef
*Where
) {
1118 moveTo(What
, Where
->getBlock(), Where
->getIterator());
1121 // Move What after Where in the MemorySSA IR.
1122 void MemorySSAUpdater::moveAfter(MemoryUseOrDef
*What
, MemoryUseOrDef
*Where
) {
1123 moveTo(What
, Where
->getBlock(), ++Where
->getIterator());
1126 void MemorySSAUpdater::moveToPlace(MemoryUseOrDef
*What
, BasicBlock
*BB
,
1127 MemorySSA::InsertionPlace Where
) {
1128 return moveTo(What
, BB
, Where
);
1131 // All accesses in To used to be in From. Move to end and update access lists.
1132 void MemorySSAUpdater::moveAllAccesses(BasicBlock
*From
, BasicBlock
*To
,
1133 Instruction
*Start
) {
1135 MemorySSA::AccessList
*Accs
= MSSA
->getWritableBlockAccesses(From
);
1139 MemoryAccess
*FirstInNew
= nullptr;
1140 for (Instruction
&I
: make_range(Start
->getIterator(), To
->end()))
1141 if ((FirstInNew
= MSSA
->getMemoryAccess(&I
)))
1146 auto *MUD
= cast
<MemoryUseOrDef
>(FirstInNew
);
1148 auto NextIt
= ++MUD
->getIterator();
1149 MemoryUseOrDef
*NextMUD
= (!Accs
|| NextIt
== Accs
->end())
1151 : cast
<MemoryUseOrDef
>(&*NextIt
);
1152 MSSA
->moveTo(MUD
, To
, MemorySSA::End
);
1153 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
1154 // retrieve it again.
1155 Accs
= MSSA
->getWritableBlockAccesses(From
);
1160 void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock
*From
,
1162 Instruction
*Start
) {
1163 assert(MSSA
->getBlockAccesses(To
) == nullptr &&
1164 "To block is expected to be free of MemoryAccesses.");
1165 moveAllAccesses(From
, To
, Start
);
1166 for (BasicBlock
*Succ
: successors(To
))
1167 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Succ
))
1168 MPhi
->setIncomingBlock(MPhi
->getBasicBlockIndex(From
), To
);
1171 void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock
*From
, BasicBlock
*To
,
1172 Instruction
*Start
) {
1173 assert(From
->getSinglePredecessor() == To
&&
1174 "From block is expected to have a single predecessor (To).");
1175 moveAllAccesses(From
, To
, Start
);
1176 for (BasicBlock
*Succ
: successors(From
))
1177 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Succ
))
1178 MPhi
->setIncomingBlock(MPhi
->getBasicBlockIndex(From
), To
);
1181 /// If all arguments of a MemoryPHI are defined by the same incoming
1182 /// argument, return that argument.
1183 static MemoryAccess
*onlySingleValue(MemoryPhi
*MP
) {
1184 MemoryAccess
*MA
= nullptr;
1186 for (auto &Arg
: MP
->operands()) {
1188 MA
= cast
<MemoryAccess
>(Arg
);
1195 void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
1196 BasicBlock
*Old
, BasicBlock
*New
, ArrayRef
<BasicBlock
*> Preds
,
1197 bool IdenticalEdgesWereMerged
) {
1198 assert(!MSSA
->getWritableBlockAccesses(New
) &&
1199 "Access list should be null for a new block.");
1200 MemoryPhi
*Phi
= MSSA
->getMemoryAccess(Old
);
1203 if (Old
->hasNPredecessors(1)) {
1204 assert(pred_size(New
) == Preds
.size() &&
1205 "Should have moved all predecessors.");
1206 MSSA
->moveTo(Phi
, New
, MemorySSA::Beginning
);
1208 assert(!Preds
.empty() && "Must be moving at least one predecessor to the "
1209 "new immediate predecessor.");
1210 MemoryPhi
*NewPhi
= MSSA
->createMemoryPhi(New
);
1211 SmallPtrSet
<BasicBlock
*, 16> PredsSet(Preds
.begin(), Preds
.end());
1212 // Currently only support the case of removing a single incoming edge when
1213 // identical edges were not merged.
1214 if (!IdenticalEdgesWereMerged
)
1215 assert(PredsSet
.size() == Preds
.size() &&
1216 "If identical edges were not merged, we cannot have duplicate "
1217 "blocks in the predecessors");
1218 Phi
->unorderedDeleteIncomingIf([&](MemoryAccess
*MA
, BasicBlock
*B
) {
1219 if (PredsSet
.count(B
)) {
1220 NewPhi
->addIncoming(MA
, B
);
1221 if (!IdenticalEdgesWereMerged
)
1227 Phi
->addIncoming(NewPhi
, New
);
1228 tryRemoveTrivialPhi(NewPhi
);
1232 void MemorySSAUpdater::removeMemoryAccess(MemoryAccess
*MA
, bool OptimizePhis
) {
1233 assert(!MSSA
->isLiveOnEntryDef(MA
) &&
1234 "Trying to remove the live on entry def");
1235 // We can only delete phi nodes if they have no uses, or we can replace all
1236 // uses with a single definition.
1237 MemoryAccess
*NewDefTarget
= nullptr;
1238 if (MemoryPhi
*MP
= dyn_cast
<MemoryPhi
>(MA
)) {
1239 // Note that it is sufficient to know that all edges of the phi node have
1240 // the same argument. If they do, by the definition of dominance frontiers
1241 // (which we used to place this phi), that argument must dominate this phi,
1242 // and thus, must dominate the phi's uses, and so we will not hit the assert
1244 NewDefTarget
= onlySingleValue(MP
);
1245 assert((NewDefTarget
|| MP
->use_empty()) &&
1246 "We can't delete this memory phi");
1248 NewDefTarget
= cast
<MemoryUseOrDef
>(MA
)->getDefiningAccess();
1251 SmallSetVector
<MemoryPhi
*, 4> PhisToCheck
;
1253 // Re-point the uses at our defining access
1254 if (!isa
<MemoryUse
>(MA
) && !MA
->use_empty()) {
1255 // Reset optimized on users of this store, and reset the uses.
1257 // 1. This is a slightly modified version of RAUW to avoid walking the
1259 // 2. If we wanted to be complete, we would have to reset the optimized
1260 // flags on users of phi nodes if doing the below makes a phi node have all
1261 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1262 // phi nodes, because doing it here would be N^3.
1263 if (MA
->hasValueHandle())
1264 ValueHandleBase::ValueIsRAUWd(MA
, NewDefTarget
);
1265 // Note: We assume MemorySSA is not used in metadata since it's not really
1268 while (!MA
->use_empty()) {
1269 Use
&U
= *MA
->use_begin();
1270 if (auto *MUD
= dyn_cast
<MemoryUseOrDef
>(U
.getUser()))
1271 MUD
->resetOptimized();
1273 if (MemoryPhi
*MP
= dyn_cast
<MemoryPhi
>(U
.getUser()))
1274 PhisToCheck
.insert(MP
);
1275 U
.set(NewDefTarget
);
1279 // The call below to erase will destroy MA, so we can't change the order we
1280 // are doing things here
1281 MSSA
->removeFromLookups(MA
);
1282 MSSA
->removeFromLists(MA
);
1284 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1285 if (!PhisToCheck
.empty()) {
1286 SmallVector
<WeakVH
, 16> PhisToOptimize
{PhisToCheck
.begin(),
1288 PhisToCheck
.clear();
1290 unsigned PhisSize
= PhisToOptimize
.size();
1291 while (PhisSize
-- > 0)
1293 cast_or_null
<MemoryPhi
>(PhisToOptimize
.pop_back_val()))
1294 tryRemoveTrivialPhi(MP
);
1298 void MemorySSAUpdater::removeBlocks(
1299 const SmallSetVector
<BasicBlock
*, 8> &DeadBlocks
) {
1300 // First delete all uses of BB in MemoryPhis.
1301 for (BasicBlock
*BB
: DeadBlocks
) {
1302 Instruction
*TI
= BB
->getTerminator();
1303 assert(TI
&& "Basic block expected to have a terminator instruction");
1304 for (BasicBlock
*Succ
: successors(TI
))
1305 if (!DeadBlocks
.count(Succ
))
1306 if (MemoryPhi
*MP
= MSSA
->getMemoryAccess(Succ
)) {
1307 MP
->unorderedDeleteIncomingBlock(BB
);
1308 tryRemoveTrivialPhi(MP
);
1310 // Drop all references of all accesses in BB
1311 if (MemorySSA::AccessList
*Acc
= MSSA
->getWritableBlockAccesses(BB
))
1312 for (MemoryAccess
&MA
: *Acc
)
1313 MA
.dropAllReferences();
1316 // Next, delete all memory accesses in each block
1317 for (BasicBlock
*BB
: DeadBlocks
) {
1318 MemorySSA::AccessList
*Acc
= MSSA
->getWritableBlockAccesses(BB
);
1321 for (auto AB
= Acc
->begin(), AE
= Acc
->end(); AB
!= AE
;) {
1322 MemoryAccess
*MA
= &*AB
;
1324 MSSA
->removeFromLookups(MA
);
1325 MSSA
->removeFromLists(MA
);
1330 void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef
<WeakVH
> UpdatedPHIs
) {
1331 for (auto &VH
: UpdatedPHIs
)
1332 if (auto *MPhi
= cast_or_null
<MemoryPhi
>(VH
))
1333 tryRemoveTrivialPhi(MPhi
);
1336 void MemorySSAUpdater::changeToUnreachable(const Instruction
*I
) {
1337 const BasicBlock
*BB
= I
->getParent();
1338 // Remove memory accesses in BB for I and all following instructions.
1339 auto BBI
= I
->getIterator(), BBE
= BB
->end();
1340 // FIXME: If this becomes too expensive, iterate until the first instruction
1341 // with a memory access, then iterate over MemoryAccesses.
1343 removeMemoryAccess(&*(BBI
++));
1344 // Update phis in BB's successors to remove BB.
1345 SmallVector
<WeakVH
, 16> UpdatedPHIs
;
1346 for (const BasicBlock
*Successor
: successors(BB
)) {
1347 removeDuplicatePhiEdgesBetween(BB
, Successor
);
1348 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Successor
)) {
1349 MPhi
->unorderedDeleteIncomingBlock(BB
);
1350 UpdatedPHIs
.push_back(MPhi
);
1353 // Optimize trivial phis.
1354 tryRemoveTrivialPhis(UpdatedPHIs
);
1357 void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst
*BI
,
1358 const BasicBlock
*To
) {
1359 const BasicBlock
*BB
= BI
->getParent();
1360 SmallVector
<WeakVH
, 16> UpdatedPHIs
;
1361 for (const BasicBlock
*Succ
: successors(BB
)) {
1362 removeDuplicatePhiEdgesBetween(BB
, Succ
);
1364 if (auto *MPhi
= MSSA
->getMemoryAccess(Succ
)) {
1365 MPhi
->unorderedDeleteIncomingBlock(BB
);
1366 UpdatedPHIs
.push_back(MPhi
);
1369 // Optimize trivial phis.
1370 tryRemoveTrivialPhis(UpdatedPHIs
);
1373 MemoryAccess
*MemorySSAUpdater::createMemoryAccessInBB(
1374 Instruction
*I
, MemoryAccess
*Definition
, const BasicBlock
*BB
,
1375 MemorySSA::InsertionPlace Point
) {
1376 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1377 MSSA
->insertIntoListsForBlock(NewAccess
, BB
, Point
);
1381 MemoryUseOrDef
*MemorySSAUpdater::createMemoryAccessBefore(
1382 Instruction
*I
, MemoryAccess
*Definition
, MemoryUseOrDef
*InsertPt
) {
1383 assert(I
->getParent() == InsertPt
->getBlock() &&
1384 "New and old access must be in the same block");
1385 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1386 MSSA
->insertIntoListsBefore(NewAccess
, InsertPt
->getBlock(),
1387 InsertPt
->getIterator());
1391 MemoryUseOrDef
*MemorySSAUpdater::createMemoryAccessAfter(
1392 Instruction
*I
, MemoryAccess
*Definition
, MemoryAccess
*InsertPt
) {
1393 assert(I
->getParent() == InsertPt
->getBlock() &&
1394 "New and old access must be in the same block");
1395 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1396 MSSA
->insertIntoListsBefore(NewAccess
, InsertPt
->getBlock(),
1397 ++InsertPt
->getIterator());