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