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