73 #define DEBUG_TYPE "loop-simplify"
75 STATISTIC(NumNested ,
"Number of nested loops split out");
85 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
86 if (&*BBI == SplitPreds[i])
97 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
100 FoundBB = SplitPreds[i];
109 FoundBB = SplitPreds[0];
144 DEBUG(
dbgs() <<
"LoopSimplify: Creating pre-header "
145 << PreheaderBB->
getName() <<
"\n");
158 std::set<BasicBlock*> &Blocks) {
163 if (Blocks.insert(BB).second && BB != StopBlock)
170 }
while (!Worklist.
empty());
227 assert(!Header->
isEHPad() &&
"Can't insert backedge to EH pad");
230 if (!PN)
return nullptr;
236 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
237 if (PN->getIncomingValue(i) != PN ||
238 !L->
contains(PN->getIncomingBlock(i))) {
240 if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
242 OuterLoopPreds.
push_back(PN->getIncomingBlock(i));
245 DEBUG(
dbgs() <<
"LoopSimplify: Splitting out a new outer loop\n");
254 DT, LI, PreserveLCSSA);
265 Parent->replaceChildLoopWith(L, NewOuter);
282 std::set<BasicBlock*> BlocksInL;
291 const std::vector<Loop*> &SubLoops = L->
getSubLoops();
292 for (
size_t I = 0;
I != SubLoops.size(); )
293 if (BlocksInL.count(SubLoops[
I]->getHeader()))
302 for (
unsigned i = 0; i != L->
getBlocks().size(); ++i) {
304 if (!BlocksInL.count(BB)) {
307 if ((*LI)[BB] == L) {
329 "LCSSA is broken after separating nested loops!");
354 assert(!Header->isEHPad() &&
"Can't insert backedge to EH pad");
357 std::vector<BasicBlock*> BackedgeBlocks;
365 if (P != Preheader) BackedgeBlocks.push_back(P);
370 Header->getName() +
".backedge",
F);
372 BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
374 DEBUG(
dbgs() <<
"LoopSimplify: Inserting unique backedge block "
375 << BEBlock->
getName() <<
"\n");
386 PN->
getName()+
".be", BETerminator);
390 unsigned PreheaderIdx = ~0U;
391 bool HasUniqueIncomingValue =
true;
392 Value *UniqueValue =
nullptr;
396 if (IBB == Preheader) {
399 NewPN->addIncoming(IV, IBB);
400 if (HasUniqueIncomingValue) {
403 else if (UniqueValue != IV)
404 HasUniqueIncomingValue =
false;
410 assert(PreheaderIdx != ~0U &&
"PHI has no preheader entry??");
411 if (PreheaderIdx != 0) {
425 if (HasUniqueIncomingValue) {
426 NewPN->replaceAllUsesWith(UniqueValue);
437 for (
unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
464 bool PreserveLCSSA) {
465 bool Changed =
false;
478 PE =
pred_end(*BB); PI != PE; ++PI) {
487 DEBUG(
dbgs() <<
"LoopSimplify: Deleting edge from dead predecessor "
488 <<
P->getName() <<
"\n");
502 for (
BasicBlock *ExitingBlock : ExitingBlocks)
503 if (
BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
504 if (BI->isConditional()) {
505 if (
UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
507 DEBUG(
dbgs() <<
"LoopSimplify: Resolving \"br i1 undef\" to exit in "
508 << ExitingBlock->getName() <<
"\n");
511 !L->
contains(BI->getSuccessor(0))));
592 auto HasUniqueExitBlock = [&]() {
594 for (
auto *ExitingBB : ExitingBlocks)
601 else if (UniqueExit != SuccBB)
607 if (HasUniqueExitBlock()) {
608 for (
unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
614 if (!CI || CI->
getParent() != ExitingBlock)
continue;
618 bool AllInvariant =
true;
619 bool AnyInvariant =
false;
623 if (isa<DbgInfoIntrinsic>(Inst))
630 AllInvariant =
false;
641 if (!AllInvariant)
continue;
651 DEBUG(
dbgs() <<
"LoopSimplify: Eliminating exiting block "
652 << ExitingBlock->
getName() <<
"\n");
666 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
668 while (!Children.empty()) {
675 ExitingBlock, PreserveLCSSA);
677 ExitingBlock, PreserveLCSSA);
687 bool PreserveLCSSA) {
688 bool Changed =
false;
694 assert(DT &&
"DT not available.");
695 assert(LI &&
"LI not available.");
697 "Requested to preserve LCSSA, but it's already broken.");
708 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
709 Loop *L2 = Worklist[Idx];
713 while (!Worklist.
empty())
727 bool runOnFunction(
Function &
F)
override;
750 void verifyAnalysis()
const override;
756 "Canonicalize natural loops",
false,
false)
770 bool LoopSimplify::runOnFunction(
Function &
F) {
771 bool Changed =
false;
772 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
773 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
774 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
777 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
779 bool PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
789 assert(InLCSSA &&
"LCSSA is broken after loop-simplify.");
797 bool Changed =
false;
825 static void verifyLoop(
Loop *
L) {
837 bool HasIndBrPred =
false;
840 if (isa<IndirectBrInst>((*PI)->getTerminator())) {
845 "LoopSimplify has no excuse for missing loop header info!");
851 bool HasIndBrExiting =
false;
854 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
855 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
856 HasIndBrExiting =
true;
862 "LoopSimplify has no excuse for missing exit block info!");
863 (void)HasIndBrExiting;
868 void LoopSimplify::verifyAnalysis()
const {
Legacy wrapper pass to provide the GlobalsAAResult object.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
loop Canonicalize natural loops
A parsed version of the target data layout string in and methods for querying it. ...
Pass * createLoopSimplifyPass()
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
AnalysisPass to compute dependence information in a function.
This is the interface for a simple mod/ref and alias analysis over globals.
Legacy pass manager pass to access dependence information.
The main scalar evolution driver.
An immutable pass that tracks lazily created AssumptionCache objects.
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
A cache of .assume calls within a function.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
bool isEHPad() const
Return true if this basic block is an exception handling block.
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Analysis pass which computes a DominatorTree.
static Loop * separateNestedLoop(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, bool PreserveLCSSA, AssumptionCache *AC)
If this loop has multiple backedges, try to pull one of them out into a nested loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
StringRef getName() const
Return a constant reference to the value's name.
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
const std::vector< DomTreeNodeBase * > & getChildren() const
static PHINode * findPHIToPartitionLoops(Loop *L, DominatorTree *DT, AssumptionCache *AC)
The first part of loop-nestification is to find a PHI node that tells us how to partition the loops...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static bool simplifyOneLoop(Loop *L, SmallVectorImpl< Loop * > &Worklist, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify one loop and queue further loops for simplification.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
'undef' values are things that do not have specified contents.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Analysis pass that exposes the LoopInfo for a function.
LLVM_NODISCARD bool empty() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
DomTreeNodeBase * getIDom() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
AnalysisUsage & addPreservedID(const void *ID)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static BasicBlock * insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI)
This method is called when the specified loop has more than one backedge in it.
bool FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
static void placeSplitBlockCarefully(BasicBlock *NewBB, SmallVectorImpl< BasicBlock * > &SplitPreds, Loop *L)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
char & BreakCriticalEdgesID
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
void splice(iterator where, iplist_impl &L2)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
const InstListType & getInstList() const
Return the underlying instruction list container.
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
Interval::pred_iterator pred_end(Interval *I)
Analysis pass providing a never-invalidated alias analysis result.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool isConditional() const
bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
A function analysis which provides an AssumptionCache.
Iterator for intrusive lists based on ilist_node.
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Legacy wrapper pass to provide the SCEVAAResult object.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
std::vector< BlockT * >::const_iterator block_iterator
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
loop Canonicalize natural false
Analysis pass that exposes the ScalarEvolution for a function.
block_iterator block_end() const
Analysis pass providing a never-invalidated alias analysis result.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Value * getCondition() const
INITIALIZE_PASS_BEGIN(LoopSimplify,"loop-simplify","Canonicalize natural loops", false, false) INITIALIZE_PASS_END(LoopSimplify
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...
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
Represents a single loop in the control flow graph.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
void initializeLoopSimplifyPass(PassRegistry &)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
block_iterator block_begin() const
The legacy pass manager's analysis pass to compute loop information.
This is the interface for LLVM's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
std::vector< LoopT * >::const_iterator iterator
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, std::set< BasicBlock * > &Blocks)
Add the specified block, and all of its predecessors, to the specified set, if it's not already in th...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
const BasicBlock * getParent() const
Legacy wrapper pass to provide the BasicAAResult object.