1 //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------===//
9 //
10 // This file implements the MemorySSAUpdater class.
11 //
12 //===----------------------------------------------------------------===//
13 #include "llvm/Analysis/MemorySSAUpdater.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/Analysis/MemorySSA.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/FormattedStream.h"
26 #include <algorithm>
27
28 #define DEBUG_TYPE "memoryssa"
29 using namespace llvm;
30
31 // This is the marker algorithm from "Simple and Efficient Construction of
32 // Static Single Assignment Form"
33 // The simple, non-marker algorithm places phi nodes at any join
34 // Here, we place markers, and only place phi nodes if they end up necessary.
35 // They are only necessary if they break a cycle (IE we recursively visit
36 // ourselves again), or we discover, while getting the value of the operands,
37 // that there are two or more definitions needing to be merged.
38 // This still will leave non-minimal form in the case of irreducible control
39 // flow, where phi nodes may be in cycles with themselves, but unnecessary.
getPreviousDefRecursive(BasicBlock * BB,DenseMap<BasicBlock *,TrackingVH<MemoryAccess>> & CachedPreviousDef)40 MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(
41 BasicBlock *BB,
42 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
43 // First, do a cache lookup. Without this cache, certain CFG structures
44 // (like a series of if statements) take exponential time to visit.
45 auto Cached = CachedPreviousDef.find(BB);
46 if (Cached != CachedPreviousDef.end()) {
47 return Cached->second;
48 }
49
50 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
51 // Single predecessor case, just recurse, we can only have one definition.
52 MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef);
53 CachedPreviousDef.insert({BB, Result});
54 return Result;
55 }
56
57 if (VisitedBlocks.count(BB)) {
58 // We hit our node again, meaning we had a cycle, we must insert a phi
59 // node to break it so we have an operand. The only case this will
60 // insert useless phis is if we have irreducible control flow.
61 MemoryAccess *Result = MSSA->createMemoryPhi(BB);
62 CachedPreviousDef.insert({BB, Result});
63 return Result;
64 }
65
66 if (VisitedBlocks.insert(BB).second) {
67 // Mark us visited so we can detect a cycle
68 SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps;
69
70 // Recurse to get the values in our predecessors for placement of a
71 // potential phi node. This will insert phi nodes if we cycle in order to
72 // break the cycle and have an operand.
73 for (auto *Pred : predecessors(BB))
74 PhiOps.push_back(getPreviousDefFromEnd(Pred, CachedPreviousDef));
75
76 // Now try to simplify the ops to avoid placing a phi.
77 // This may return null if we never created a phi yet, that's okay
78 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
79
80 // See if we can avoid the phi by simplifying it.
81 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
82 // If we couldn't simplify, we may have to create a phi
83 if (Result == Phi) {
84 if (!Phi)
85 Phi = MSSA->createMemoryPhi(BB);
86
87 // See if the existing phi operands match what we need.
88 // Unlike normal SSA, we only allow one phi node per block, so we can't just
89 // create a new one.
90 if (Phi->getNumOperands() != 0) {
91 // FIXME: Figure out whether this is dead code and if so remove it.
92 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
93 // These will have been filled in by the recursive read we did above.
94 std::copy(PhiOps.begin(), PhiOps.end(), Phi->op_begin());
95 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
96 }
97 } else {
98 unsigned i = 0;
99 for (auto *Pred : predecessors(BB))
100 Phi->addIncoming(&*PhiOps[i++], Pred);
101 InsertedPHIs.push_back(Phi);
102 }
103 Result = Phi;
104 }
105
106 // Set ourselves up for the next variable by resetting visited state.
107 VisitedBlocks.erase(BB);
108 CachedPreviousDef.insert({BB, Result});
109 return Result;
110 }
111 llvm_unreachable("Should have hit one of the three cases above");
112 }
113
114 // This starts at the memory access, and goes backwards in the block to find the
115 // previous definition. If a definition is not found the block of the access,
116 // it continues globally, creating phi nodes to ensure we have a single
117 // definition.
getPreviousDef(MemoryAccess * MA)118 MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
119 if (auto *LocalResult = getPreviousDefInBlock(MA))
120 return LocalResult;
121 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
122 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef);
123 }
124
125 // This starts at the memory access, and goes backwards in the block to the find
126 // the previous definition. If the definition is not found in the block of the
127 // access, it returns nullptr.
getPreviousDefInBlock(MemoryAccess * MA)128 MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
129 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
130
131 // It's possible there are no defs, or we got handed the first def to start.
132 if (Defs) {
133 // If this is a def, we can just use the def iterators.
134 if (!isa<MemoryUse>(MA)) {
135 auto Iter = MA->getReverseDefsIterator();
136 ++Iter;
137 if (Iter != Defs->rend())
138 return &*Iter;
139 } else {
140 // Otherwise, have to walk the all access iterator.
141 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend();
142 for (auto &U : make_range(++MA->getReverseIterator(), End))
143 if (!isa<MemoryUse>(U))
144 return cast<MemoryAccess>(&U);
145 // Note that if MA comes before Defs->begin(), we won't hit a def.
146 return nullptr;
147 }
148 }
149 return nullptr;
150 }
151
152 // This starts at the end of block
getPreviousDefFromEnd(BasicBlock * BB,DenseMap<BasicBlock *,TrackingVH<MemoryAccess>> & CachedPreviousDef)153 MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(
154 BasicBlock *BB,
155 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
156 auto *Defs = MSSA->getWritableBlockDefs(BB);
157
158 if (Defs)
159 return &*Defs->rbegin();
160
161 return getPreviousDefRecursive(BB, CachedPreviousDef);
162 }
163 // Recurse over a set of phi uses to eliminate the trivial ones
recursePhi(MemoryAccess * Phi)164 MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
165 if (!Phi)
166 return nullptr;
167 TrackingVH<MemoryAccess> Res(Phi);
168 SmallVector<TrackingVH<Value>, 8> Uses;
169 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
170 for (auto &U : Uses) {
171 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) {
172 auto OperRange = UsePhi->operands();
173 tryRemoveTrivialPhi(UsePhi, OperRange);
174 }
175 }
176 return Res;
177 }
178
179 // Eliminate trivial phis
180 // Phis are trivial if they are defined either by themselves, or all the same
181 // argument.
182 // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
183 // We recursively try to remove them.
184 template <class RangeType>
tryRemoveTrivialPhi(MemoryPhi * Phi,RangeType & Operands)185 MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
186 RangeType &Operands) {
187 // Bail out on non-opt Phis.
188 if (NonOptPhis.count(Phi))
189 return Phi;
190
191 // Detect equal or self arguments
192 MemoryAccess *Same = nullptr;
193 for (auto &Op : Operands) {
194 // If the same or self, good so far
195 if (Op == Phi || Op == Same)
196 continue;
197 // not the same, return the phi since it's not eliminatable by us
198 if (Same)
199 return Phi;
200 Same = cast<MemoryAccess>(&*Op);
201 }
202 // Never found a non-self reference, the phi is undef
203 if (Same == nullptr)
204 return MSSA->getLiveOnEntryDef();
205 if (Phi) {
206 Phi->replaceAllUsesWith(Same);
207 removeMemoryAccess(Phi);
208 }
209
210 // We should only end up recursing in case we replaced something, in which
211 // case, we may have made other Phis trivial.
212 return recursePhi(Same);
213 }
214
insertUse(MemoryUse * MU)215 void MemorySSAUpdater::insertUse(MemoryUse *MU) {
216 InsertedPHIs.clear();
217 MU->setDefiningAccess(getPreviousDef(MU));
218 // Unlike for defs, there is no extra work to do. Because uses do not create
219 // new may-defs, there are only two cases:
220 //
221 // 1. There was a def already below us, and therefore, we should not have
222 // created a phi node because it was already needed for the def.
223 //
224 // 2. There is no def below us, and therefore, there is no extra renaming work
225 // to do.
226 }
227
228 // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
setMemoryPhiValueForBlock(MemoryPhi * MP,const BasicBlock * BB,MemoryAccess * NewDef)229 static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
230 MemoryAccess *NewDef) {
231 // Replace any operand with us an incoming block with the new defining
232 // access.
233 int i = MP->getBasicBlockIndex(BB);
234 assert(i != -1 && "Should have found the basic block in the phi");
235 // We can't just compare i against getNumOperands since one is signed and the
236 // other not. So use it to index into the block iterator.
237 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end();
238 ++BBIter) {
239 if (*BBIter != BB)
240 break;
241 MP->setIncomingValue(i, NewDef);
242 ++i;
243 }
244 }
245
246 // A brief description of the algorithm:
247 // First, we compute what should define the new def, using the SSA
248 // construction algorithm.
249 // Then, we update the defs below us (and any new phi nodes) in the graph to
250 // point to the correct new defs, to ensure we only have one variable, and no
251 // disconnected stores.
insertDef(MemoryDef * MD,bool RenameUses)252 void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
253 InsertedPHIs.clear();
254
255 // See if we had a local def, and if not, go hunting.
256 MemoryAccess *DefBefore = getPreviousDef(MD);
257 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock();
258
259 // There is a def before us, which means we can replace any store/phi uses
260 // of that thing with us, since we are in the way of whatever was there
261 // before.
262 // We now define that def's memorydefs and memoryphis
263 if (DefBeforeSameBlock) {
264 for (auto UI = DefBefore->use_begin(), UE = DefBefore->use_end();
265 UI != UE;) {
266 Use &U = *UI++;
267 // Leave the uses alone
268 if (isa<MemoryUse>(U.getUser()))
269 continue;
270 U.set(MD);
271 }
272 }
273
274 // and that def is now our defining access.
275 // We change them in this order otherwise we will appear in the use list
276 // above and reset ourselves.
277 MD->setDefiningAccess(DefBefore);
278
279 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
280 if (!DefBeforeSameBlock) {
281 // If there was a local def before us, we must have the same effect it
282 // did. Because every may-def is the same, any phis/etc we would create, it
283 // would also have created. If there was no local def before us, we
284 // performed a global update, and have to search all successors and make
285 // sure we update the first def in each of them (following all paths until
286 // we hit the first def along each path). This may also insert phi nodes.
287 // TODO: There are other cases we can skip this work, such as when we have a
288 // single successor, and only used a straight line of single pred blocks
289 // backwards to find the def. To make that work, we'd have to track whether
290 // getDefRecursive only ever used the single predecessor case. These types
291 // of paths also only exist in between CFG simplifications.
292 FixupList.push_back(MD);
293 }
294
295 while (!FixupList.empty()) {
296 unsigned StartingPHISize = InsertedPHIs.size();
297 fixupDefs(FixupList);
298 FixupList.clear();
299 // Put any new phis on the fixup list, and process them
300 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
301 }
302 // Now that all fixups are done, rename all uses if we are asked.
303 if (RenameUses) {
304 SmallPtrSet<BasicBlock *, 16> Visited;
305 BasicBlock *StartBlock = MD->getBlock();
306 // We are guaranteed there is a def in the block, because we just got it
307 // handed to us in this function.
308 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
309 // Convert to incoming value if it's a memorydef. A phi *is* already an
310 // incoming value.
311 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
312 FirstDef = MD->getDefiningAccess();
313
314 MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
315 // We just inserted a phi into this block, so the incoming value will become
316 // the phi anyway, so it does not matter what we pass.
317 for (auto &MP : InsertedPHIs) {
318 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
319 if (Phi)
320 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
321 }
322 }
323 }
324
fixupDefs(const SmallVectorImpl<WeakVH> & Vars)325 void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
326 SmallPtrSet<const BasicBlock *, 8> Seen;
327 SmallVector<const BasicBlock *, 16> Worklist;
328 for (auto &Var : Vars) {
329 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
330 if (!NewDef)
331 continue;
332 // First, see if there is a local def after the operand.
333 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
334 auto DefIter = NewDef->getDefsIterator();
335
336 // The temporary Phi is being fixed, unmark it for not to optimize.
337 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
338 NonOptPhis.erase(Phi);
339
340 // If there is a local def after us, we only have to rename that.
341 if (++DefIter != Defs->end()) {
342 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
343 continue;
344 }
345
346 // Otherwise, we need to search down through the CFG.
347 // For each of our successors, handle it directly if their is a phi, or
348 // place on the fixup worklist.
349 for (const auto *S : successors(NewDef->getBlock())) {
350 if (auto *MP = MSSA->getMemoryAccess(S))
351 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
352 else
353 Worklist.push_back(S);
354 }
355
356 while (!Worklist.empty()) {
357 const BasicBlock *FixupBlock = Worklist.back();
358 Worklist.pop_back();
359
360 // Get the first def in the block that isn't a phi node.
361 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
362 auto *FirstDef = &*Defs->begin();
363 // The loop above and below should have taken care of phi nodes
364 assert(!isa<MemoryPhi>(FirstDef) &&
365 "Should have already handled phi nodes!");
366 // We are now this def's defining access, make sure we actually dominate
367 // it
368 assert(MSSA->dominates(NewDef, FirstDef) &&
369 "Should have dominated the new access");
370
371 // This may insert new phi nodes, because we are not guaranteed the
372 // block we are processing has a single pred, and depending where the
373 // store was inserted, it may require phi nodes below it.
374 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
375 return;
376 }
377 // We didn't find a def, so we must continue.
378 for (const auto *S : successors(FixupBlock)) {
379 // If there is a phi node, handle it.
380 // Otherwise, put the block on the worklist
381 if (auto *MP = MSSA->getMemoryAccess(S))
382 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
383 else {
384 // If we cycle, we should have ended up at a phi node that we already
385 // processed. FIXME: Double check this
386 if (!Seen.insert(S).second)
387 continue;
388 Worklist.push_back(S);
389 }
390 }
391 }
392 }
393 }
394
395 // Move What before Where in the MemorySSA IR.
396 template <class WhereType>
moveTo(MemoryUseOrDef * What,BasicBlock * BB,WhereType Where)397 void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
398 WhereType Where) {
399 // Mark MemoryPhi users of What not to be optimized.
400 for (auto *U : What->users())
401 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
402 NonOptPhis.insert(PhiUser);
403
404 // Replace all our users with our defining access.
405 What->replaceAllUsesWith(What->getDefiningAccess());
406
407 // Let MemorySSA take care of moving it around in the lists.
408 MSSA->moveTo(What, BB, Where);
409
410 // Now reinsert it into the IR and do whatever fixups needed.
411 if (auto *MD = dyn_cast<MemoryDef>(What))
412 insertDef(MD);
413 else
414 insertUse(cast<MemoryUse>(What));
415
416 // Clear dangling pointers. We added all MemoryPhi users, but not all
417 // of them are removed by fixupDefs().
418 NonOptPhis.clear();
419 }
420
421 // Move What before Where in the MemorySSA IR.
moveBefore(MemoryUseOrDef * What,MemoryUseOrDef * Where)422 void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
423 moveTo(What, Where->getBlock(), Where->getIterator());
424 }
425
426 // Move What after Where in the MemorySSA IR.
moveAfter(MemoryUseOrDef * What,MemoryUseOrDef * Where)427 void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
428 moveTo(What, Where->getBlock(), ++Where->getIterator());
429 }
430
moveToPlace(MemoryUseOrDef * What,BasicBlock * BB,MemorySSA::InsertionPlace Where)431 void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
432 MemorySSA::InsertionPlace Where) {
433 return moveTo(What, BB, Where);
434 }
435
436 // All accesses in To used to be in From. Move to end and update access lists.
moveAllAccesses(BasicBlock * From,BasicBlock * To,Instruction * Start)437 void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
438 Instruction *Start) {
439
440 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
441 if (!Accs)
442 return;
443
444 MemoryAccess *FirstInNew = nullptr;
445 for (Instruction &I : make_range(Start->getIterator(), To->end()))
446 if ((FirstInNew = MSSA->getMemoryAccess(&I)))
447 break;
448 if (!FirstInNew)
449 return;
450
451 auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
452 do {
453 auto NextIt = ++MUD->getIterator();
454 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
455 ? nullptr
456 : cast<MemoryUseOrDef>(&*NextIt);
457 MSSA->moveTo(MUD, To, MemorySSA::End);
458 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
459 // retrieve it again.
460 Accs = MSSA->getWritableBlockAccesses(From);
461 MUD = NextMUD;
462 } while (MUD);
463 }
464
moveAllAfterSpliceBlocks(BasicBlock * From,BasicBlock * To,Instruction * Start)465 void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
466 BasicBlock *To,
467 Instruction *Start) {
468 assert(MSSA->getBlockAccesses(To) == nullptr &&
469 "To block is expected to be free of MemoryAccesses.");
470 moveAllAccesses(From, To, Start);
471 for (BasicBlock *Succ : successors(To))
472 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
473 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
474 }
475
moveAllAfterMergeBlocks(BasicBlock * From,BasicBlock * To,Instruction * Start)476 void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
477 Instruction *Start) {
478 assert(From->getSinglePredecessor() == To &&
479 "From block is expected to have a single predecessor (To).");
480 moveAllAccesses(From, To, Start);
481 for (BasicBlock *Succ : successors(From))
482 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
483 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
484 }
485
486 /// If all arguments of a MemoryPHI are defined by the same incoming
487 /// argument, return that argument.
onlySingleValue(MemoryPhi * MP)488 static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
489 MemoryAccess *MA = nullptr;
490
491 for (auto &Arg : MP->operands()) {
492 if (!MA)
493 MA = cast<MemoryAccess>(Arg);
494 else if (MA != Arg)
495 return nullptr;
496 }
497 return MA;
498 }
499
wireOldPredecessorsToNewImmediatePredecessor(BasicBlock * Old,BasicBlock * New,ArrayRef<BasicBlock * > Preds)500 void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
501 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds) {
502 assert(!MSSA->getWritableBlockAccesses(New) &&
503 "Access list should be null for a new block.");
504 MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
505 if (!Phi)
506 return;
507 if (pred_size(Old) == 1) {
508 assert(pred_size(New) == Preds.size() &&
509 "Should have moved all predecessors.");
510 MSSA->moveTo(Phi, New, MemorySSA::Beginning);
511 } else {
512 assert(!Preds.empty() && "Must be moving at least one predecessor to the "
513 "new immediate predecessor.");
514 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
515 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
516 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
517 if (PredsSet.count(B)) {
518 NewPhi->addIncoming(MA, B);
519 return true;
520 }
521 return false;
522 });
523 Phi->addIncoming(NewPhi, New);
524 if (onlySingleValue(NewPhi))
525 removeMemoryAccess(NewPhi);
526 }
527 }
528
removeMemoryAccess(MemoryAccess * MA)529 void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA) {
530 assert(!MSSA->isLiveOnEntryDef(MA) &&
531 "Trying to remove the live on entry def");
532 // We can only delete phi nodes if they have no uses, or we can replace all
533 // uses with a single definition.
534 MemoryAccess *NewDefTarget = nullptr;
535 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
536 // Note that it is sufficient to know that all edges of the phi node have
537 // the same argument. If they do, by the definition of dominance frontiers
538 // (which we used to place this phi), that argument must dominate this phi,
539 // and thus, must dominate the phi's uses, and so we will not hit the assert
540 // below.
541 NewDefTarget = onlySingleValue(MP);
542 assert((NewDefTarget || MP->use_empty()) &&
543 "We can't delete this memory phi");
544 } else {
545 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
546 }
547
548 // Re-point the uses at our defining access
549 if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
550 // Reset optimized on users of this store, and reset the uses.
551 // A few notes:
552 // 1. This is a slightly modified version of RAUW to avoid walking the
553 // uses twice here.
554 // 2. If we wanted to be complete, we would have to reset the optimized
555 // flags on users of phi nodes if doing the below makes a phi node have all
556 // the same arguments. Instead, we prefer users to removeMemoryAccess those
557 // phi nodes, because doing it here would be N^3.
558 if (MA->hasValueHandle())
559 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
560 // Note: We assume MemorySSA is not used in metadata since it's not really
561 // part of the IR.
562
563 while (!MA->use_empty()) {
564 Use &U = *MA->use_begin();
565 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
566 MUD->resetOptimized();
567 U.set(NewDefTarget);
568 }
569 }
570
571 // The call below to erase will destroy MA, so we can't change the order we
572 // are doing things here
573 MSSA->removeFromLookups(MA);
574 MSSA->removeFromLists(MA);
575 }
576
removeBlocks(const SmallPtrSetImpl<BasicBlock * > & DeadBlocks)577 void MemorySSAUpdater::removeBlocks(
578 const SmallPtrSetImpl<BasicBlock *> &DeadBlocks) {
579 // First delete all uses of BB in MemoryPhis.
580 for (BasicBlock *BB : DeadBlocks) {
581 TerminatorInst *TI = BB->getTerminator();
582 assert(TI && "Basic block expected to have a terminator instruction");
583 for (BasicBlock *Succ : TI->successors())
584 if (!DeadBlocks.count(Succ))
585 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
586 MP->unorderedDeleteIncomingBlock(BB);
587 if (MP->getNumIncomingValues() == 1)
588 removeMemoryAccess(MP);
589 }
590 // Drop all references of all accesses in BB
591 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
592 for (MemoryAccess &MA : *Acc)
593 MA.dropAllReferences();
594 }
595
596 // Next, delete all memory accesses in each block
597 for (BasicBlock *BB : DeadBlocks) {
598 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
599 if (!Acc)
600 continue;
601 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) {
602 MemoryAccess *MA = &*AB;
603 ++AB;
604 MSSA->removeFromLookups(MA);
605 MSSA->removeFromLists(MA);
606 }
607 }
608 }
609
createMemoryAccessInBB(Instruction * I,MemoryAccess * Definition,const BasicBlock * BB,MemorySSA::InsertionPlace Point)610 MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
611 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
612 MemorySSA::InsertionPlace Point) {
613 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
614 MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
615 return NewAccess;
616 }
617
createMemoryAccessBefore(Instruction * I,MemoryAccess * Definition,MemoryUseOrDef * InsertPt)618 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
619 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
620 assert(I->getParent() == InsertPt->getBlock() &&
621 "New and old access must be in the same block");
622 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
623 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
624 InsertPt->getIterator());
625 return NewAccess;
626 }
627
createMemoryAccessAfter(Instruction * I,MemoryAccess * Definition,MemoryAccess * InsertPt)628 MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
629 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
630 assert(I->getParent() == InsertPt->getBlock() &&
631 "New and old access must be in the same block");
632 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
633 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
634 ++InsertPt->getIterator());
635 return NewAccess;
636 }
637