44 #define DEBUG_TYPE "loop-unroll"
47 STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
48 STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
52 cl::desc(
"Allow runtime unrolled loops to be unrolled "
53 "with epilog instead of prolog."));
57 cl::desc(
"Verify domtree after unrolling"),
76 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
77 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
80 PN->setIncomingBlock(i, cast<BasicBlock>(It->
second));
101 if (!OnlyPred)
return nullptr;
106 DEBUG(
dbgs() <<
"Merging: " << *BB <<
"into: " << *OnlyPred);
133 for (
auto *DI : Children)
142 if (ForgottenLoops.
insert(
L).second)
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");
203 NewLoop =
new Loop();
211 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
247 assert(PreHeader && Header);
296 bool AllowRuntime,
bool AllowExpensiveTripCount,
297 bool PreserveCondBr,
bool PreserveOnlyFirst,
298 unsigned TripMultiple,
unsigned PeelCount,
LoopInfo *LI,
301 bool PreserveLCSSA) {
305 DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
311 DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
317 DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
331 " Can't unroll; loop not terminated by a conditional branch.\n");
335 auto CheckSuccessors = [&](
unsigned S1,
unsigned S2) {
339 if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) {
340 DEBUG(
dbgs() <<
"Can't unroll; only loops with one conditional latch"
341 " exiting the loop can be unrolled\n");
348 " Won't unroll loop: address of header block is taken.\n");
353 DEBUG(
dbgs() <<
" Trip Count = " << TripCount <<
"\n");
354 if (TripMultiple != 1)
355 DEBUG(
dbgs() <<
" Trip Multiple = " << TripMultiple <<
"\n");
359 if (TripCount != 0 && Count > TripCount)
363 if (TripCount == 0 && Count < 2 && PeelCount == 0) {
364 DEBUG(
dbgs() <<
"Won't unroll; almost nothing to do\n");
370 assert(TripCount == 0 || TripCount % TripMultiple == 0);
373 bool CompletelyUnroll = Count == TripCount;
376 std::vector<BasicBlock*> OriginalLoopBlocks = L->
getBlocks();
384 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
386 return isa<PHINode>(BB->
begin());
392 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
394 assert((!RuntimeTripCount || !PeelCount) &&
395 "Did not expect runtime trip-count unrolling "
396 "and peeling for the same loop");
399 peelLoop(L, PeelCount, LI, SE, DT, AC, PreserveLCSSA);
405 bool HasConvergent =
false;
406 for (
auto &BB : L->
blocks())
409 HasConvergent |= CS.isConvergent();
410 assert((!HasConvergent || TripMultiple % Count == 0) &&
411 "Unroll count must divide trip multiple if loop contains a "
412 "convergent operation.");
415 bool EpilogProfitability =
419 if (RuntimeTripCount && TripMultiple % Count != 0 &&
421 EpilogProfitability, LI, SE, DT,
424 RuntimeTripCount =
false;
427 dbgs() <<
"Wont unroll; remainder loop could not be generated"
428 "when assuming runtime trip count\n");
439 unsigned BreakoutTrip = 0;
440 if (TripCount != 0) {
441 BreakoutTrip = TripCount % Count;
445 BreakoutTrip = TripMultiple =
451 if (CompletelyUnroll) {
453 <<
" with trip count " << TripCount <<
"!\n");
456 <<
"completely unrolled loop with "
457 <<
NV(
"UnrollCount", TripCount) <<
" iterations");
458 }
else if (PeelCount) {
460 <<
" with iteration count " << PeelCount <<
"!\n");
463 <<
" peeled loop by " <<
NV(
"PeelCount", PeelCount)
468 Diag <<
"unrolled loop by a factor of " <<
NV(
"UnrollCount", Count);
472 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
473 DEBUG(
dbgs() <<
" with a breakout at trip " << BreakoutTrip);
474 ORE->
emit(Diag <<
" with a breakout at trip "
475 <<
NV(
"BreakoutTrip", BreakoutTrip));
476 }
else if (TripMultiple != 1) {
477 DEBUG(
dbgs() <<
" with " << TripMultiple <<
" trips per branch");
478 ORE->
emit(Diag <<
" with " <<
NV(
"TripMultiple", TripMultiple)
479 <<
" trips per branch");
480 }
else if (RuntimeTripCount) {
481 DEBUG(
dbgs() <<
" with run-time trip count");
482 ORE->
emit(Diag <<
" with run-time trip count");
493 std::vector<PHINode*> OrigPHINode;
495 OrigPHINode.push_back(cast<PHINode>(
I));
498 std::vector<BasicBlock*> Headers;
499 std::vector<BasicBlock*> Latches;
500 Headers.push_back(Header);
501 Latches.push_back(LatchBlock);
513 std::vector<BasicBlock*> UnrolledLoopBlocks = L->
getBlocks();
520 for (
Loop *SubLoop : *L)
521 LoopsToSimplify.
insert(SubLoop);
527 I.setDebugLoc(DIL->cloneWithDuplicationFactor(Count));
529 for (
unsigned It = 1; It != Count; ++It) {
530 std::vector<BasicBlock*> NewBlocks;
540 "Header should not be in a sub-loop");
544 LoopsToSimplify.insert(NewLoops[OldLoop]);
554 for (
PHINode *OrigPHI : OrigPHINode) {
555 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
557 if (
Instruction *InValI = dyn_cast<Instruction>(InVal))
558 if (It > 1 && L->contains(InValI))
559 InVal = LastValueMap[InValI];
560 VMap[OrigPHI] = InVal;
565 LastValueMap[*BB] = New;
568 LastValueMap[
VI->first] =
VI->second;
572 if (L->contains(Succ))
578 if (It != LastValueMap.end())
586 Headers.push_back(New);
587 if (*BB == LatchBlock)
588 Latches.push_back(New);
590 NewBlocks.push_back(New);
591 UnrolledLoopBlocks.push_back(New);
601 auto BBDomNode = DT->
getNode(*BB);
602 auto BBIDom = BBDomNode->getIDom();
603 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
605 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
614 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
615 if (II->getIntrinsicID() == Intrinsic::assume)
622 for (
PHINode *PN : OrigPHINode) {
623 if (CompletelyUnroll) {
624 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
627 else if (Count > 1) {
628 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
631 if (
Instruction *InValI = dyn_cast<Instruction>(InVal)) {
632 if (L->contains(InValI))
633 InVal = LastValueMap[InVal];
635 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
636 PN->addIncoming(InVal, Latches.back());
642 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
644 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
647 unsigned j = (i + 1) % e;
649 bool NeedConditional =
true;
651 if (RuntimeTripCount && j != 0) {
652 NeedConditional =
false;
657 if (CompletelyUnroll) {
664 "NeedCondition cannot be modified by both complete "
665 "unrolling and runtime unrolling");
666 NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0));
667 }
else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
670 NeedConditional =
false;
673 if (NeedConditional) {
679 if (Dest != LoopExit) {
682 if (Succ == Headers[i])
700 if (DT && Count > 1) {
701 for (
auto *BB : OriginalLoopBlocks) {
702 auto *BBDomNode = DT->
getNode(BB);
704 for (
auto *ChildDomNode : BBDomNode->getChildren()) {
705 auto *ChildBB = ChildDomNode->getBlock();
706 if (!L->contains(ChildBB))
710 if (BB == LatchBlock) {
718 NewIDom = Latches.
back();
721 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
733 for (
auto *ChildBB : ChildrenToUpdate)
744 BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
750 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
751 UnrolledLoopBlocks.erase(
std::remove(UnrolledLoopBlocks.begin(),
752 UnrolledLoopBlocks.end(), Dest),
753 UnrolledLoopBlocks.end());
759 if (SE && !CompletelyUnroll && Count > 1) {
765 while (!DeadInsts.
empty())
767 dyn_cast_or_null<Instruction>(&*DeadInsts.
pop_back_val()))
775 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
784 BB->getInstList().erase(Inst);
793 NumCompletelyUnrolled += CompletelyUnroll;
798 if (CompletelyUnroll)
809 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
821 if (NeedToFixLCSSA) {
826 Loop *FixLCSSALoop = OuterL;
827 if (!FixLCSSALoop->
contains(LatchLoop))
832 }
else if (PreserveLCSSA) {
833 assert(OuterL->isLCSSAForm(*DT) &&
834 "Loops should be in LCSSA form after loop-unroll.");
842 for (
Loop *SubLoop : LoopsToSimplify)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
DiagnosticInfoOptimizationBase::Argument NV
const Instruction & back() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B)
Return the greatest common divisor of the values using Euclid's algorithm.
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
static void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
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...
The main scalar evolution driver.
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(true))
A cache of .assume calls within a function.
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.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
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.
bool UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool Force, bool AllowRuntime, bool AllowExpensiveTripCount, bool PreserveCondBr, bool PreserveOnlyFirst, unsigned TripMultiple, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA)
Unroll the given loop by Count.
StringRef getName() const
Return a constant reference to the value's name.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
bool isUnconditional() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
A Use represents the edge between a Value definition and its users.
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 ...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() 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 addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
iterator find(const KeyT &Val)
Base class for the actual dominator tree node.
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...
iterator_range< block_iterator > blocks() const
initializer< Ty > init(const Ty &Val)
Subclasses of this class are all able to terminate a basic block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
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 InstListType & getInstList() const
Return the underlying instruction list container.
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
Value * getOperand(unsigned i) const
void markAsRemoved(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
void verifyDomTree() const
Verify the correctness of the domtree by re-computing it.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
StringRef getString() const
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
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...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LLVM_NODISCARD T pop_back_val()
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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 ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
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...
bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, bool PreserveLCSSA)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void registerAssumption(CallInst *CI)
Add an .assume intrinsic to this function's cache.
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...
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."))
Represents a single loop in the control flow graph.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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)
StringRef - Represent a constant reference to a string, i.e.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
static BasicBlock * foldBlockIntoPredecessor(BasicBlock *BB, LoopInfo *LI, ScalarEvolution *SE, SmallPtrSetImpl< Loop * > &ForgottenLoops, DominatorTree *DT)
Folds a basic block into its predecessor if it only has one predecessor, and that predecessor only ha...
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...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
RPOIterator endRPO() const