44 #define DEBUG_TYPE "loop-rotate"
48 cl::desc(
"The default maximum header size for automatic loop rotation"));
50 STATISTIC(NumRotated,
"Number of loops rotated");
55 const unsigned MaxHeaderSize;
64 LoopRotate(
unsigned MaxHeaderSize,
LoopInfo *LI,
67 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
69 bool processLoop(
Loop *
L);
72 bool rotateLoop(
Loop *
L,
bool SimplifiedLatch);
73 bool simplifyLoopLatch(
Loop *
L);
93 for (I = OrigHeader->
begin(); I !=
E; ++
I) {
94 Value *OrigHeaderVal = &*
I;
101 Value *OrigPreHeaderVal = ValueMap.
lookup(OrigHeaderVal);
122 if (!isa<PHINode>(UserInst)) {
127 if (UserBB == OrigHeader)
132 if (UserBB == OrigPreheader) {
133 U = OrigPreHeaderVal;
147 for (
auto UI = MAV->use_begin(), E = MAV->use_end(); UI !=
E;) {
158 if (UserBB == OrigHeader)
166 if (UserBB == OrigPreheader)
167 NewVal = OrigPreHeaderVal;
185 for (
auto &
I : *OrigHeader) {
186 if (
auto DbgII = dyn_cast<DbgInfoIntrinsic>(&
I)) {
187 if (
auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
188 DbgValueMap.
insert({Loc, DbgII});
196 for (
auto PHI : InsertedPHIs) {
197 for (
auto VI : PHI->operand_values()) {
198 auto V = DbgValueMap.
find(
VI);
199 if (V != DbgValueMap.
end()) {
200 auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
203 NewDbgII->setOperand(0, PhiMAV);
221 bool LoopRotate::rotateLoop(
Loop *
L,
bool SimplifiedLatch) {
258 DEBUG(
dbgs() <<
"LoopRotation: NOT rotating - contains non-duplicatable"
259 <<
" instructions: ";
264 DEBUG(
dbgs() <<
"LoopRotation: NOT rotating - contains convergent "
269 if (Metrics.
NumInsts > MaxHeaderSize)
295 assert(NewHeader &&
"Unable to determine new loop header");
297 "Unable to determine loop header and exit blocks");
302 "New header doesn't have one pred!");
329 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
345 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
361 if (
auto *II = dyn_cast<IntrinsicInst>(C))
362 if (II->getIntrinsicID() == Intrinsic::assume)
363 AC->registerAssumption(II);
391 if (!InsertedPHIs.
empty())
396 assert(L->
getHeader() == NewHeader &&
"Latch block is our new header");
406 assert(PHBI->isConditional() &&
"Should be clone of BI condbr!");
407 if (!isa<ConstantInt>(PHBI->getCondition()) ||
408 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->
isZero()) !=
418 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
420 OrigHeaderNode->
end());
421 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
422 for (
unsigned I = 0,
E = HeaderChildren.size(); I !=
E; ++
I)
423 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
425 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
426 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
429 DT->changeImmediateDominator(OrigHeader, OrigLatch);
436 OrigPreheader, NewHeader,
445 bool SplitLatchEdge =
false;
448 Loop *PredLoop = LI->getLoopFor(ExitPred);
449 if (!PredLoop || PredLoop->
contains(Exit))
451 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
460 "Despite splitting all preds, failed to split latch exit?");
464 Exit->removePredecessor(OrigPreheader,
true );
467 PHBI->eraseFromParent();
472 DT->changeImmediateDominator(NewHeader, OrigPreheader);
473 DT->changeImmediateDominator(OrigHeader, OrigLatch);
478 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
480 OrigHeaderNode->
end());
484 for (
unsigned I = 0,
E = HeaderChildren.size(); I !=
E; ++
I) {
491 if (!DT->getNode(Pred))
499 NearestDom = DT->findNearestCommonDominator(NearestDom, Pred);
500 assert(NearestDom &&
"No NearestCommonDominator found");
503 assert(NearestDom &&
"Nearest dominator not found");
507 DT->changeImmediateDominator(BB, NearestDom);
539 bool seenIncrement =
false;
540 bool MultiExitLoop =
false;
543 MultiExitLoop =
true;
550 if (isa<DbgInfoIntrinsic>(I))
553 switch (I->getOpcode()) {
556 case Instruction::GetElementPtr:
558 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
563 case Instruction::Sub:
564 case Instruction::And:
565 case Instruction::Or:
566 case Instruction::Xor:
567 case Instruction::Shl:
568 case Instruction::LShr:
569 case Instruction::AShr: {
571 !isa<Constant>(I->getOperand(0))
573 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) :
nullptr;
581 auto *UserInst = cast<Instruction>(UseI);
589 seenIncrement =
true;
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
610 bool LoopRotate::simplifyLoopLatch(
Loop *L) {
631 << LastExit->
getName() <<
"\n");
637 unsigned FallThruPath = BI->
getSuccessor(0) == Latch ? 0 : 1;
647 assert(Latch->
empty() &&
"unable to evacuate Latch");
648 LI->removeBlock(Latch);
650 DT->eraseNode(Latch);
656 bool LoopRotate::processLoop(
Loop *L) {
663 bool SimplifiedLatch = simplifyLoopLatch(L);
665 bool MadeChange = rotateLoop(L, SimplifiedLatch);
667 "Loop latch should be exiting after loop-rotate.");
671 if ((MadeChange || SimplifiedLatch) && LoopMD)
678 : EnableHeaderDuplication(EnableHeaderDuplication) {}
686 LoopRotate LR(Threshold, &AR.
LI, &AR.
TTI, &AR.
AC, &AR.
DT, &AR.
SE,
689 bool Changed = LR.processLoop(&L);
698 class LoopRotateLegacyPass :
public LoopPass {
699 unsigned MaxHeaderSize;
703 LoopRotateLegacyPass(
int SpecifiedMaxHeaderSize = -1) :
LoopPass(
ID) {
705 if (SpecifiedMaxHeaderSize == -1)
708 MaxHeaderSize =
unsigned(SpecifiedMaxHeaderSize);
723 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
724 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
725 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
726 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
727 auto *DT = DTWP ? &DTWP->getDomTree() :
nullptr;
728 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
729 auto *SE = SEWP ? &SEWP->getSE() :
nullptr;
731 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
732 return LR.processLoop(L);
747 return new LoopRotateLegacyPass(MaxHeaderSize);
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
Helper class for SSA formation on a set of values defined in multiple blocks.
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...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
STATISTIC(NumFunctions,"Total number of functions")
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
This is the interface for a simple mod/ref and alias analysis over globals.
bool convergent
True if this function contains a call to a convergent function.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
The main scalar evolution driver.
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
void deleteValue()
Delete a pointer to a generic Value.
const Function * getParent() const
Return the enclosing method, or null if none.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
bool notDuplicatable
True if this function cannot be duplicated.
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
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.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isUnconditional() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
Option class for critical edge splitting.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
LLVM_NODISCARD bool empty() const
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
DomTreeNodeBase * getIDom() const
BasicBlock * getSuccessor(unsigned i) const
iterator find(const KeyT &Val)
Base class for the actual dominator tree node.
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, SmallVectorImpl< PHINode * > *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
use_iterator_impl< Use > use_iterator
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of to it...
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
initializer< Ty > init(const Ty &Val)
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
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 setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
static void insertDebugValues(BasicBlock *OrigHeader, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted Phis.
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...
INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass,"loop-rotate","Rotate Loops", false, false) INITIALIZE_PASS_END(LoopRotateLegacyPass
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Represent the analysis usage information of a pass.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Interval::pred_iterator pred_end(Interval *I)
self_iterator getIterator()
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void initializeLoopRotateLegacyPassPass(PassRegistry &)
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
TargetTransformInfo & TTI
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
Iterator for intrusive lists based on ilist_node.
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...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
This is the common base class for debug info intrinsics.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
pred_range predecessors(BasicBlock *BB)
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr)
Attempts to merge a block into its predecessor, if possible.
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.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
LoopRotatePass(bool EnableHeaderDuplication=true)
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &EphValues)
Add information about a block to the current state.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
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.
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...
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
unsigned NumInsts
Number of instructions in the analyzed blocks.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const BasicBlock * getParent() const
Pass * createLoopRotatePass(int MaxHeaderSize=-1)
static cl::opt< unsigned > DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden, cl::desc("The default maximum header size for automatic loop rotation"))