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