69 #define DEBUG_TYPE "loop-simplify"
71 STATISTIC(NumInserted,
"Number of pre-header or exit blocks inserted");
72 STATISTIC(NumNested ,
"Number of nested loops split out");
82 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
83 if (&*BBI == SplitPreds[i])
94 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
98 FoundBB = SplitPreds[i];
107 FoundBB = SplitPreds[0];
121 auto *DT = DTWP ? &DTWP->getDomTree() :
nullptr;
145 AA, DT, LI, PreserveLCSSA);
147 DEBUG(
dbgs() <<
"LoopSimplify: Creating pre-header "
148 << PreheaderBB->
getName() <<
"\n");
175 assert(!LoopBlocks.
empty() &&
"No edges coming in from outside the loop?");
183 DEBUG(
dbgs() <<
"LoopSimplify: Creating dedicated exit block "
184 << NewExitBB->getName() <<
"\n");
192 std::set<BasicBlock*> &Blocks) {
197 if (Blocks.insert(BB).second && BB != StopBlock)
204 }
while (!Worklist.
empty());
262 assert(!L->
getHeader()->isLandingPad() &&
263 "Can't insert backedge to landing pad");
266 if (!PN)
return nullptr;
272 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
273 if (PN->getIncomingValue(i) != PN ||
274 !L->
contains(PN->getIncomingBlock(i))) {
276 if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
278 OuterLoopPreds.
push_back(PN->getIncomingBlock(i));
281 DEBUG(
dbgs() <<
"LoopSimplify: Splitting out a new outer loop\n");
293 AA, DT, LI, PreserveLCSSA);
304 Parent->replaceChildLoopWith(L, NewOuter);
321 std::set<BasicBlock*> BlocksInL;
330 const std::vector<Loop*> &SubLoops = L->
getSubLoops();
331 for (
size_t I = 0;
I != SubLoops.size(); )
332 if (BlocksInL.count(SubLoops[
I]->getHeader()))
339 for (
unsigned i = 0; i != L->
getBlocks().size(); ++i) {
341 if (!BlocksInL.count(BB)) {
373 assert(!Header->isLandingPad() &&
"Can't insert backedge to landing pad");
376 std::vector<BasicBlock*> BackedgeBlocks;
384 if (P != Preheader) BackedgeBlocks.push_back(P);
389 Header->getName() +
".backedge",
F);
391 BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
393 DEBUG(
dbgs() <<
"LoopSimplify: Inserting unique backedge block "
394 << BEBlock->
getName() <<
"\n");
405 PN->
getName()+
".be", BETerminator);
409 unsigned PreheaderIdx = ~0U;
410 bool HasUniqueIncomingValue =
true;
411 Value *UniqueValue =
nullptr;
415 if (IBB == Preheader) {
418 NewPN->addIncoming(IV, IBB);
419 if (HasUniqueIncomingValue) {
422 else if (UniqueValue != IV)
423 HasUniqueIncomingValue =
false;
429 assert(PreheaderIdx != ~0U &&
"PHI has no preheader entry??");
430 if (PreheaderIdx != 0) {
444 if (HasUniqueIncomingValue) {
445 NewPN->replaceAllUsesWith(UniqueValue);
453 for (
unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
482 bool Changed =
false;
495 PE =
pred_end(*BB); PI != PE; ++PI) {
504 DEBUG(
dbgs() <<
"LoopSimplify: Deleting edge from dead predecessor "
505 <<
P->getName() <<
"\n");
509 (*SI)->removePredecessor(
P);
513 P->getTerminator()->eraseFromParent();
525 E = ExitingBlocks.
end();
I != E; ++
I)
526 if (
BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
527 if (BI->isConditional()) {
528 if (
UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
530 DEBUG(
dbgs() <<
"LoopSimplify: Resolving \"br i1 undef\" to exit in "
531 << (*I)->getName() <<
"\n");
534 !L->
contains(BI->getSuccessor(0))));
564 E = ExitBlockSet.end();
I != E; ++
I) {
636 bool UniqueExit =
true;
637 if (!ExitBlocks.
empty())
638 for (
unsigned i = 1, e = ExitBlocks.
size(); i != e; ++i)
639 if (ExitBlocks[i] != ExitBlocks[0]) {
644 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
650 if (!CI || CI->
getParent() != ExitingBlock)
continue;
654 bool AllInvariant =
true;
655 bool AnyInvariant =
false;
659 if (isa<DbgInfoIntrinsic>(Inst))
666 AllInvariant =
false;
677 if (!AllInvariant)
continue;
687 DEBUG(
dbgs() <<
"LoopSimplify: Eliminating exiting block "
688 << ExitingBlock->
getName() <<
"\n");
702 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
704 while (!Children.empty()) {
722 bool Changed =
false;
731 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
732 Loop *L2 = Worklist[Idx];
736 while (!Worklist.
empty())
758 bool runOnFunction(
Function &
F)
override;
777 void verifyAnalysis()
const override;
783 "Canonicalize natural loops",
false,
false)
797 bool LoopSimplify::runOnFunction(
Function &
F) {
798 bool Changed =
false;
799 AA = getAnalysisIfAvailable<AliasAnalysis>();
800 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
801 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
802 SE = getAnalysisIfAvailable<ScalarEvolution>();
803 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
815 static void verifyLoop(
Loop *L) {
827 bool HasIndBrPred =
false;
830 if (isa<IndirectBrInst>((*PI)->getTerminator())) {
834 assert(HasIndBrPred &&
835 "LoopSimplify has no excuse for missing loop header info!");
841 bool HasIndBrExiting =
false;
844 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
845 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
846 HasIndBrExiting =
true;
851 assert(HasIndBrExiting &&
852 "LoopSimplify has no excuse for missing exit block info!");
853 (void)HasIndBrExiting;
858 void LoopSimplify::verifyAnalysis()
const {
unsigned getNumBackEdges() const
getNumBackEdges - Calculate the number of back edges to the loop header
Pass interface - Implemented by all 'passes'.
iplist< Instruction >::iterator eraseFromParent()
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)
addIncoming - 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)
removeBlock - This method completely removes BB from all data structures, including all of the Loop o...
STATISTIC(NumFunctions,"Total number of functions")
DependenceAnalysis - This class is the main dependence-analysis driver.
ScalarEvolution - This class is the main scalar evolution driver.
static PHINode * findPHIToPartitionLoops(Loop *L, AliasAnalysis *AA, DominatorTree *DT, AssumptionCache *AC)
The first part of loop-nestification is to find a PHI node that tells us how to partition the loops...
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
void changeLoopFor(BlockT *BB, LoopT *L)
changeLoopFor - 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.
const std::vector< BlockT * > & getBlocks() const
getBlocks - Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
static BasicBlock * rewriteLoopExitBlock(Loop *L, BasicBlock *Exit, AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, Pass *PP)
Ensure that the loop preheader dominates all exit blocks.
LoopT * removeChildLoop(iterator I)
removeChildLoop - 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
getLoopLatch - If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
removeIncomingValue - Remove an incoming value.
BasicBlock * InsertPreheaderForLoop(Loop *L, Pass *P)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
UndefValue - 'undef' values are things that do not have specified contents.
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP, AliasAnalysis *AA=nullptr, ScalarEvolution *SE=nullptr, AssumptionCache *AC=nullptr)
Simplify each loop in a loop nest recursively.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool mustPreserveAnalysisID(char &AID) const
mustPreserveAnalysisID - This method serves the same function as getAnalysisIfAvailable, but works if you just have an AnalysisID.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
getExitingBlocks - Return all blocks inside the loop that have successors outside of the loop...
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
getExitBlocks - Return all of the successor blocks of this loop.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
addBasicBlockToLoop - This method is used by other analyses to update loop information.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
void addChildLoop(LoopT *NewChild)
addChildLoop - 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 setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
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.
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold=1)
FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch, and if a predecessor branc...
static void placeSplitBlockCarefully(BasicBlock *NewBB, SmallVectorImpl< BasicBlock * > &SplitPreds, Loop *L)
Subclasses of this class are all able to terminate a basic block.
BlockT * getLoopPreheader() const
getLoopPreheader - If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
BranchInst - Conditional or Unconditional Branch instruction.
char & BreakCriticalEdgesID
UnreachableInst - This function has undefined behavior.
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.
static BasicBlock * insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI)
This method is called when the specified loop has more than one backedge in it.
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...
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
bool contains(const LoopT *L) const
contains - Return true if the specified loop is contained within in this loop.
const InstListType & getInstList() const
Return the underlying instruction list container.
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const std::vector< DomTreeNodeBase< NodeT > * > & getChildren() const
void forgetValue(Value *V)
forgetValue - This method should be called by the client when it has changed a value in a way that ma...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void addBlockEntry(BlockT *BB)
addBlockEntry - This adds a basic block directly to the basic block list.
bool hasDedicatedExits() const
hasDedicatedExits - Return true if no exit block for the loop has a predecessor that is outside the l...
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
virtual void deleteValue(Value *V)
Methods that clients should call when they transform the program to allow alias analyses to update th...
iterator erase(iterator where)
void removeBlockFromLoop(BlockT *BB)
removeBlockFromLoop - 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
A SetVector that performs no allocations if smaller than a certain size.
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
DomTreeNodeBase< NodeT > * getIDom() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
makeLoopInvariant - If the given value is an instruction inside of the loop and it can be hoisted...
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.
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...
void splice(iterator where, iplist &L2)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool simplifyOneLoop(Loop *L, SmallVectorImpl< Loop * > &Worklist, AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, Pass *PP, AssumptionCache *AC)
Simplify one loop and queue further loops for simplification.
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
std::vector< BlockT * >::const_iterator block_iterator
static Loop * separateNestedLoop(Loop *L, BasicBlock *Preheader, AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, Pass *PP, AssumptionCache *AC)
If this loop has multiple backedges, try to pull one of them out into a nested loop.
loop Canonicalize natural false
block_iterator block_end() const
Value * getCondition() const
INITIALIZE_PASS_BEGIN(LoopSimplify,"loop-simplify","Canonicalize natural loops", false, false) INITIALIZE_PASS_END(LoopSimplify
void forgetLoop(const Loop *L)
forgetLoop - This method should be called by the client when it has changed a loop in a way that may ...
void moveToHeader(BlockT *BB)
moveToHeader - This method is used to move BB (which must be part of this loop) to be the loop header...
iplist< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void initializeLoopSimplifyPass(PassRegistry &)
LLVM Value Representation.
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
changeTopLevelLoop - Replace the specified loop in the top-level loops list with the indicated loop...
const std::vector< LoopT * > & getSubLoops() const
iterator/begin/end - Return the loops contained entirely within this loop.
block_iterator block_begin() const
The legacy pass manager's analysis pass to compute loop information.
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, AliasAnalysis *AA=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
SplitBlockPredecessors - This method introduces at least one new basic block into the function and mo...
Value * SimplifyInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
SimplifyInstruction - See if we can compute a simplified version of this instruction.
Legacy analysis pass which computes a DominatorTree.
std::vector< LoopT * >::const_iterator iterator
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void setIncomingValue(unsigned i, Value *V)
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...
const BasicBlock * getParent() const
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.