43 #define DEBUG_TYPE "loop-unroll" 46 STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
47 STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
51 cl::desc(
"Allow runtime unrolled loops to be unrolled " 52 "with epilog instead of prolog."));
56 cl::desc(
"Verify domtree after unrolling"),
72 if (
auto *V = dyn_cast<MetadataAsValue>(Op))
73 if (
auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) {
74 Op = Unwrapped->getValue();
88 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
89 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
92 PN->setIncomingBlock(i, cast<BasicBlock>(It->
second));
107 if (!OnlyPred)
return nullptr;
113 << OnlyPred->
getName() <<
"\n");
140 for (
auto *DI : Children)
172 for (
Use &U :
I.operands()) {
173 if (
auto Def = dyn_cast<Instruction>(U)) {
195 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
197 Loop *&NewLoop = NewLoops[OldLoop];
201 "Header should be first in RPO");
211 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
247 assert(PreHeader && Header);
249 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
262 if (SE && SimplifyIVs) {
268 while (!DeadInsts.
empty())
270 dyn_cast_or_null<Instruction>(&*DeadInsts.
pop_back_val()))
278 const std::vector<BasicBlock *> &NewLoopBlocks = L->
getBlocks();
287 BB->getInstList().erase(Inst);
334 Loop *L,
unsigned Count,
unsigned TripCount,
bool Force,
bool AllowRuntime,
335 bool AllowExpensiveTripCount,
bool PreserveCondBr,
bool PreserveOnlyFirst,
336 unsigned TripMultiple,
unsigned PeelCount,
bool UnrollRemainder,
342 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
348 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
354 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
369 <<
" Can't unroll; loop not terminated by a conditional branch.\n");
373 auto CheckSuccessors = [&](
unsigned S1,
unsigned S2) {
377 if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) {
378 LLVM_DEBUG(
dbgs() <<
"Can't unroll; only loops with one conditional latch" 379 " exiting the loop can be unrolled\n");
386 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
392 if (TripMultiple != 1)
393 LLVM_DEBUG(
dbgs() <<
" Trip Multiple = " << TripMultiple <<
"\n");
397 if (TripCount != 0 && Count > TripCount)
401 if (TripCount == 0 && Count < 2 && PeelCount == 0) {
408 assert(TripCount == 0 || TripCount % TripMultiple == 0);
411 bool CompletelyUnroll = Count == TripCount;
414 std::vector<BasicBlock*> OriginalLoopBlocks = L->
getBlocks();
422 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
424 return isa<PHINode>(BB->
begin());
430 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
432 assert((!RuntimeTripCount || !PeelCount) &&
433 "Did not expect runtime trip-count unrolling " 434 "and peeling for the same loop");
438 Peeled =
peelLoop(L, PeelCount, LI, SE, DT, AC, PreserveLCSSA);
444 assert(ExitingBlock &&
"Loop without exiting block?");
455 bool HasConvergent =
false;
456 for (
auto &BB : L->
blocks())
459 HasConvergent |= CS.isConvergent();
460 assert((!HasConvergent || TripMultiple % Count == 0) &&
461 "Unroll count must divide trip multiple if loop contains a " 462 "convergent operation.");
465 bool EpilogProfitability =
469 if (RuntimeTripCount && TripMultiple % Count != 0 &&
471 EpilogProfitability, UnrollRemainder, LI, SE,
472 DT, AC, PreserveLCSSA)) {
474 RuntimeTripCount =
false;
477 "generated when assuming runtime trip count\n");
483 unsigned BreakoutTrip = 0;
484 if (TripCount != 0) {
485 BreakoutTrip = TripCount % Count;
489 BreakoutTrip = TripMultiple =
495 if (CompletelyUnroll) {
497 <<
" with trip count " << TripCount <<
"!\n");
502 <<
"completely unrolled loop with " 503 <<
NV(
"UnrollCount", TripCount) <<
" iterations";
505 }
else if (PeelCount) {
507 <<
" with iteration count " << PeelCount <<
"!\n");
512 <<
" peeled loop by " <<
NV(
"PeelCount", PeelCount)
516 auto DiagBuilder = [&]() {
519 return Diag <<
"unrolled loop by a factor of " 520 <<
NV(
"UnrollCount", Count);
525 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
526 LLVM_DEBUG(
dbgs() <<
" with a breakout at trip " << BreakoutTrip);
529 return DiagBuilder() <<
" with a breakout at trip " 530 <<
NV(
"BreakoutTrip", BreakoutTrip);
532 }
else if (TripMultiple != 1) {
533 LLVM_DEBUG(
dbgs() <<
" with " << TripMultiple <<
" trips per branch");
536 return DiagBuilder() <<
" with " <<
NV(
"TripMultiple", TripMultiple)
537 <<
" trips per branch";
539 }
else if (RuntimeTripCount) {
543 [&]() {
return DiagBuilder() <<
" with run-time trip count"; });
565 std::vector<PHINode*> OrigPHINode;
567 OrigPHINode.push_back(cast<PHINode>(
I));
570 std::vector<BasicBlock*> Headers;
571 std::vector<BasicBlock*> Latches;
572 Headers.push_back(Header);
573 Latches.push_back(LatchBlock);
585 std::vector<BasicBlock*> UnrolledLoopBlocks = L->
getBlocks();
592 for (
Loop *SubLoop : *L)
593 LoopsToSimplify.
insert(SubLoop);
598 if (!isa<DbgInfoIntrinsic>(&
I))
600 I.setDebugLoc(DIL->cloneWithDuplicationFactor(Count));
602 for (
unsigned It = 1; It != Count; ++It) {
603 std::vector<BasicBlock*> NewBlocks;
613 "Header should not be in a sub-loop");
617 LoopsToSimplify.
insert(NewLoops[OldLoop]);
622 for (
PHINode *OrigPHI : OrigPHINode) {
623 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
625 if (
Instruction *InValI = dyn_cast<Instruction>(InVal))
626 if (It > 1 && L->contains(InValI))
627 InVal = LastValueMap[InValI];
628 VMap[OrigPHI] = InVal;
633 LastValueMap[*BB] = New;
636 LastValueMap[
VI->first] =
VI->second;
640 if (L->contains(Succ))
642 for (
PHINode &PHI : Succ->phis()) {
643 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
645 if (It != LastValueMap.
end())
647 PHI.addIncoming(Incoming, New);
653 Headers.push_back(New);
654 if (*BB == LatchBlock)
655 Latches.push_back(New);
657 NewBlocks.push_back(New);
658 UnrolledLoopBlocks.push_back(New);
668 auto BBDomNode = DT->
getNode(*BB);
669 auto BBIDom = BBDomNode->
getIDom();
670 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
672 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
681 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
682 if (II->getIntrinsicID() == Intrinsic::assume)
689 for (
PHINode *PN : OrigPHINode) {
690 if (CompletelyUnroll) {
691 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
694 else if (Count > 1) {
695 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
698 if (
Instruction *InValI = dyn_cast<Instruction>(InVal)) {
699 if (L->contains(InValI))
700 InVal = LastValueMap[InVal];
702 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
703 PN->addIncoming(InVal, Latches.back());
709 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
711 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
714 unsigned j = (i + 1) % e;
716 bool NeedConditional =
true;
718 if (RuntimeTripCount && j != 0) {
719 NeedConditional =
false;
724 if (CompletelyUnroll) {
731 "NeedCondition cannot be modified by both complete " 732 "unrolling and runtime unrolling");
733 NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0));
734 }
else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
737 NeedConditional =
false;
740 if (NeedConditional) {
746 if (Dest != LoopExit) {
749 if (Succ == Headers[i])
751 for (
PHINode &Phi : Succ->phis())
752 Phi.removeIncomingValue(BB,
false);
765 if (DT && Count > 1) {
766 for (
auto *BB : OriginalLoopBlocks) {
767 auto *BBDomNode = DT->
getNode(BB);
769 for (
auto *ChildDomNode : BBDomNode->getChildren()) {
770 auto *ChildBB = ChildDomNode->getBlock();
771 if (!L->contains(ChildBB))
775 if (BB == LatchBlock) {
783 NewIDom = Latches.
back();
786 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
798 for (
auto *ChildBB : ChildrenToUpdate)
808 BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
813 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
814 UnrolledLoopBlocks.erase(
std::remove(UnrolledLoopBlocks.begin(),
815 UnrolledLoopBlocks.end(), Dest),
816 UnrolledLoopBlocks.end());
826 NumCompletelyUnrolled += CompletelyUnroll;
831 if (CompletelyUnroll)
842 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
854 if (NeedToFixLCSSA) {
859 Loop *FixLCSSALoop = OuterL;
860 if (!FixLCSSALoop->
contains(LatchLoop))
865 }
else if (PreserveLCSSA) {
867 "Loops should be in LCSSA form after loop-unroll.");
875 for (
Loop *SubLoop : LoopsToSimplify)
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getSmallConstantTripMultiple(const Loop *L)
Returns the largest constant divisor of the trip count of the loop if it is a single-exit loop and we...
DiagnosticInfoOptimizationBase::Argument NV
uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B)
Return the greatest common divisor of the values using Euclid's algorithm.
iterator erase(iterator where)
static bool needToInsertPhisForLCSSA(Loop *L, std::vector< BasicBlock *> Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form...
Compute iterated dominance frontiers using a linear time algorithm.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
The main scalar evolution driver.
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(true))
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
A cache of @llvm.assume calls within a function.
BasicBlock * foldBlockIntoPredecessor(BasicBlock *BB, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT)
Folds a basic block into its predecessor if it only has one predecessor, and that predecessor only ha...
LLVMContext & getContext() const
All values hold a context through their type.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
const MDOperand & getOperand(unsigned I) const
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
iterator begin()
Instruction iterator methods.
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
A Use represents the edge between a Value definition and its users.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
void setName(const Twine &Name)
Change the name of the value.
RPOIterator endRPO() const
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
iterator find(const KeyT &Val)
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale. ...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
StringRef getString() const
The loop was fully unrolled into straight-line code.
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
initializer< Ty > init(const Ty &Val)
Subclasses of this class are all able to terminate a basic block.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA)
Peel off the first PeelCount iterations of loop L.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & back() const
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LoopT * AllocateLoop(ArgsTy &&... Args)
LLVM_NODISCARD T pop_back_val()
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
Store the result of a depth first search within basic blocks contained by a single loop...
void push_back(pointer val)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
LoopT * getParentLoop() const
LLVMAttributeRef wrap(Attribute Attr)
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
bool isUnconditional() const
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...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
The loop was not modified.
StringRef - Represent a constant reference to a string, i.e.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
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...
unsigned getNumOperands() const
Return number of MDNode operands.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
iterator_range< block_iterator > blocks() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
LoopUnrollResult UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool Force, bool AllowRuntime, bool AllowExpensiveTripCount, bool PreserveCondBr, bool PreserveOnlyFirst, unsigned TripMultiple, unsigned PeelCount, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA)
Unroll the given loop by Count.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
void forgetTopmostLoop(const Loop *L)
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC)
Perform some cleanup and simplifications on loops after unrolling.