Movatterモバイル変換


[0]ホーム

URL:


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

Generated on Thu Jul 17 2025 11:00:55 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp