34#define DEBUG_TYPE "loop-delete"
38 "Number of loops for which we managed to break the backedge");
42 cl::desc(
"Break backedge through symbolic execution of 1st iteration "
43 "attempting to prove that the backedge is never taken"));
72 bool AllEntriesInvariant =
true;
73 bool AllOutgoingValuesSame =
true;
76 Value *incoming =
P.getIncomingValueForBlock(ExitingBlocks[0]);
82 AllOutgoingValuesSame =
84 return incoming ==
P.getIncomingValueForBlock(BB);
87 if (!AllOutgoingValuesSame)
93 AllEntriesInvariant =
false;
100 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
106 for (
const auto &
I : L->blocks())
108 return I.mayHaveSideEffects() && !
I.isDroppable();
116 if (L->getHeader()->getParent()->mustProgress())
122 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
127 while (!WorkList.
empty()) {
133 if (isa<SCEVCouldNotCompute>(S)) {
135 dbgs() <<
"Could not compute SCEV MaxBackedgeTakenCount and was "
136 "not required to make progress.\n");
148 using namespace PatternMatch;
150 auto *Preheader = L->getLoopPreheader();
153 assert(Preheader &&
"Needs preheader!");
155 if (Preheader->isEntryBlock())
162 if (!
match(Pred->getTerminator(),
165 if (!
Cond->getZExtValue())
167 if (Taken == Preheader)
171 "Preheader should have predecessors at this point!");
180 if (!isa<Instruction>(V))
183 auto Existing = FirstIterValue.
find(V);
184 if (Existing != FirstIterValue.
end())
185 return Existing->second;
186 Value *FirstIterV =
nullptr;
187 if (
auto *BO = dyn_cast<BinaryOperator>(V)) {
193 }
else if (
auto *Cmp = dyn_cast<ICmpInst>(V)) {
199 }
else if (
auto *
Select = dyn_cast<SelectInst>(V)) {
202 if (
auto *
C = dyn_cast<ConstantInt>(
Cond)) {
203 auto *Selected =
C->isAllOnesValue() ?
Select->getTrueValue()
204 :
Select->getFalseValue();
210 FirstIterValue[V] = FirstIterV;
222 BasicBlock *Predecessor = L->getLoopPredecessor();
225 if (!Predecessor || !Latch)
236 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
244 LiveBlocks.
insert(Header);
250 "Only canonical backedges are allowed. Irreducible CFG?");
252 "We already discarded this block as dead!");
257 auto MarkAllSuccessorsLive = [&](
BasicBlock *BB) {
259 MarkLiveEdge(BB, Succ);
265 auto GetSoleInputOnFirstIteration = [&](
PHINode & PN)->
Value * {
267 bool HasLivePreds =
false;
270 return PN.getIncomingValueForBlock(Predecessor);
271 Value *OnlyInput =
nullptr;
273 if (LiveEdges.
count({ Pred, BB })) {
281 if (OnlyInput && OnlyInput !=
Incoming)
286 assert(HasLivePreds &&
"No live predecessors?");
302 auto &
DL = Header->getDataLayout();
304 for (
auto *BB : RPOT) {
308 if (!LiveBlocks.count(BB))
312 if (LI.getLoopFor(BB) != L) {
313 MarkAllSuccessorsLive(BB);
318 for (
auto &PN : BB->phis()) {
319 if (!PN.getType()->isIntegerTy())
321 auto *
Incoming = GetSoleInputOnFirstIteration(PN);
325 FirstIterValue[&PN] = FirstIterV;
329 using namespace PatternMatch;
332 auto *
Term = BB->getTerminator();
335 auto *ICmp = dyn_cast<ICmpInst>(
Cond);
336 if (!ICmp || !ICmp->getType()->isIntegerTy()) {
337 MarkAllSuccessorsLive(BB);
343 if (KnownCondition == ICmp) {
345 MarkAllSuccessorsLive(BB);
348 if (isa<UndefValue>(KnownCondition)) {
360 if (
L->contains(IfTrue) &&
L->contains(IfFalse))
361 MarkLiveEdge(BB, IfTrue);
364 auto *ConstCondition = dyn_cast<ConstantInt>(KnownCondition);
365 if (!ConstCondition) {
367 MarkAllSuccessorsLive(BB);
370 if (ConstCondition->isAllOnesValue())
371 MarkLiveEdge(BB, IfTrue);
373 MarkLiveEdge(BB, IfFalse);
374 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
375 auto *SwitchValue =
SI->getCondition();
376 auto *SwitchValueOnFirstIter =
378 auto *ConstSwitchValue = dyn_cast<ConstantInt>(SwitchValueOnFirstIter);
379 if (!ConstSwitchValue) {
380 MarkAllSuccessorsLive(BB);
383 auto CaseIterator =
SI->findCaseValue(ConstSwitchValue);
384 MarkLiveEdge(BB, CaseIterator->getCaseSuccessor());
386 MarkAllSuccessorsLive(BB);
392 return !LiveEdges.count({ Latch, Header });
402 assert(L->isLCSSAForm(DT) &&
"Expected LCSSA!");
404 if (!L->getLoopLatch())
417 ++NumBackedgesBroken;
440 assert(L->isLCSSAForm(DT) &&
"Expected LCSSA!");
445 BasicBlock *Preheader = L->getLoopPreheader();
446 if (!Preheader || !L->hasDedicatedExits()) {
449 <<
"Deletion requires Loop with preheader and dedicated exits.\n");
453 BasicBlock *ExitBlock = L->getUniqueExitBlock();
457 if (ExitBlock && ExitBlock->
isEHPad()) {
463 LLVM_DEBUG(
dbgs() <<
"Loop is proven to never execute, delete it!\n");
470 std::fill(
P.incoming_values().begin(),
P.incoming_values().end(),
476 <<
"Loop deleted because it never executes";
486 L->getExitingBlocks(ExitingBlocks);
492 if (!ExitBlock && !L->hasNoExitBlocks()) {
493 LLVM_DEBUG(
dbgs() <<
"Deletion requires at most one exit block.\n");
498 bool Changed =
false;
499 if (!
isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader, LI)) {
509 <<
"Loop deleted because it is invariant";
523 std::string LoopName = std::string(L.getName());
533 if (Result != LoopDeletionResult::Deleted)
537 if (Result == LoopDeletionResult::Unmodified)
540 if (Result == LoopDeletionResult::Deleted)
amdgpu AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static LoopDeletionResult breakBackedgeIfNotTaken(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA, OptimizationRemarkEmitter &ORE)
If we can prove the backedge is untaken, remove it.
static Value * getValueOnFirstIteration(Value *V, DenseMap< Value *, Value * > &FirstIterValue, const SimplifyQuery &SQ)
static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA, OptimizationRemarkEmitter &ORE)
Remove a loop if it is dead.
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
static bool isLoopNeverExecuted(Loop *L)
This function returns true if there is no viable path from the entry block to the header of L.
static cl::opt< bool > EnableSymbolicExecution("loop-deletion-enable-symbolic-execution", cl::Hidden, cl::init(true), cl::desc("Break backedge through symbolic execution of 1st iteration " "attempting to prove that the backedge is never taken"))
static bool canProveExitOnFirstIteration(Loop *L, DominatorTree &DT, LoopInfo &LI)
static bool isLoopDead(Loop *L, ScalarEvolution &SE, SmallVectorImpl< BasicBlock * > &ExitingBlocks, BasicBlock *ExitBlock, bool &Changed, BasicBlock *Preheader, LoopInfo &LI)
Determines if a loop is dead.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A container for analyses that lazily runs them and caches their results.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isEHPad() const
Return true if this basic block is an exception handling block.
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...
This is the shared class of boolean and integer constants.
iterator find(const_arg_type_t< KeyT > Val)
Implements a dense probed hash-table based set.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
bool isLoopHeader(const BlockT *BB) const
Represents a single loop in the control flow graph.
An analysis that produces MemorySSA for a function.
Encapsulates MemorySSA, including all data associated with memory accesses.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents an analyzed expression in the program.
bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM Value Representation.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
@ C
The default llvm calling convention, compatible with C.
bool match(Val *V, const Pattern &P)
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto successors(const MachineBasicBlock *BB)
bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI, MemorySSA *MSSA=nullptr)
This function deletes dead loops.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
Value * simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
bool pred_empty(const BasicBlock *BB)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...