197 #define DEBUG_TYPE "loop-predication" 199 using namespace llvm;
217 cl::desc(
"scale factor for the latch probability. Value should be greater " 218 "than 1. Lower values are ignored"));
221 class LoopPredication {
230 : Pred(Pred), IV(IV), Limit(Limit) {}
233 dbgs() <<
"LoopICmp Pred = " << Pred <<
", IV = " << *IV
234 <<
", Limit = " << *Limit <<
"\n";
246 bool isSupportedStep(
const SCEV* Step);
256 bool CanExpand(
const SCEV* S);
277 bool isLoopProfitableToPredicate();
291 bool isSafeToTruncateWideIVType(
Type *RangeCheckType);
298 : SE(SE), BPI(BPI){};
299 bool runOnLoop(
Loop *L);
302 class LoopPredicationLegacyPass :
public LoopPass {
305 LoopPredicationLegacyPass() :
LoopPass(ID) {
317 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
319 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
320 LoopPredication LP(SE, &BPI);
321 return LP.runOnLoop(L);
329 "Loop predication",
false,
false)
336 return new LoopPredicationLegacyPass();
344 Function *
F = L.getHeader()->getParent();
346 LoopPredication LP(&AR.
SE, BPI);
347 if (!LP.runOnLoop(&L))
357 if (isa<SCEVCouldNotCompute>(LHSS))
360 if (isa<SCEVCouldNotCompute>(RHSS))
374 return LoopICmp(Pred, AR, RHSS);
384 assert(Ty == RHS->
getType() &&
"expandCheck operands have different types?");
395 LoopPredication::generateLoopLatchCheck(
Type *RangeCheckType) {
397 auto *LatchType = LatchCheck.IV->getType();
398 if (RangeCheckType == LatchType)
403 if (!isSafeToTruncateWideIVType(RangeCheckType))
407 LoopICmp NewLatchCheck;
408 NewLatchCheck.Pred = LatchCheck.Pred;
411 if (!NewLatchCheck.IV)
413 NewLatchCheck.Limit = SE->
getTruncateExpr(LatchCheck.Limit, RangeCheckType);
415 <<
"can be represented as range check type:" 416 << *RangeCheckType <<
"\n");
417 LLVM_DEBUG(
dbgs() <<
"LatchCheck.IV: " << *NewLatchCheck.IV <<
"\n");
418 LLVM_DEBUG(
dbgs() <<
"LatchCheck.Limit: " << *NewLatchCheck.Limit <<
"\n");
419 return NewLatchCheck;
422 bool LoopPredication::isSupportedStep(
const SCEV* Step) {
426 bool LoopPredication::CanExpand(
const SCEV* S) {
431 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
433 auto *Ty = RangeCheck.IV->getType();
440 const SCEV *GuardStart = RangeCheck.IV->getStart();
441 const SCEV *GuardLimit = RangeCheck.Limit;
442 const SCEV *LatchStart = LatchCheck.IV->getStart();
443 const SCEV *LatchLimit = LatchCheck.Limit;
449 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
450 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
454 auto LimitCheckPred =
463 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
464 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
465 GuardStart, GuardLimit, InsertAt);
466 return Builder.
CreateAnd(FirstIterationCheck, LimitCheck);
470 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
472 auto *Ty = RangeCheck.IV->getType();
473 const SCEV *GuardStart = RangeCheck.IV->getStart();
474 const SCEV *GuardLimit = RangeCheck.Limit;
475 const SCEV *LatchLimit = LatchCheck.Limit;
476 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
477 !CanExpand(LatchLimit)) {
483 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
484 if (RangeCheck.IV != PostDecLatchCheckIV) {
486 << *PostDecLatchCheckIV
487 <<
" and RangeCheckIV: " << *RangeCheck.IV <<
"\n");
496 auto LimitCheckPred =
499 GuardStart, GuardLimit, InsertAt);
500 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit,
501 SE->
getOne(Ty), InsertAt);
502 return Builder.
CreateAnd(FirstIterationCheck, LimitCheck);
518 auto RangeCheck = parseLoopICmp(ICI);
520 LLVM_DEBUG(
dbgs() <<
"Failed to parse the loop latch condition!\n");
527 << RangeCheck->Pred <<
")!\n");
530 auto *RangeCheckIV = RangeCheck->IV;
531 if (!RangeCheckIV->isAffine()) {
535 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
538 if (!isSupportedStep(Step)) {
539 LLVM_DEBUG(
dbgs() <<
"Range check and latch have IVs different steps!\n");
542 auto *Ty = RangeCheckIV->getType();
543 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
544 if (!CurrLatchCheckOpt) {
546 "corresponding to range type: " 551 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
555 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
556 "Range and latch steps should be of same type!");
557 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
558 LLVM_DEBUG(
dbgs() <<
"Range and latch have different step values!\n");
563 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
567 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
572 bool LoopPredication::widenGuardConditions(
IntrinsicInst *Guard,
589 unsigned NumWidened = 0;
591 Value *Condition = Worklist.pop_back_val();
592 if (!Visited.
insert(Condition).second)
598 Worklist.push_back(LHS);
599 Worklist.push_back(RHS);
603 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
604 if (
auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
605 Checks.
push_back(NewRangeCheck.getValue());
613 }
while (Worklist.size() != 0);
619 Builder.SetInsertPoint(Guard);
620 Value *LastCheck =
nullptr;
621 for (
auto *
Check : Checks)
625 LastCheck = Builder.CreateAnd(LastCheck,
Check);
652 "One of the latch's destinations must be the header");
656 auto Result = parseLoopICmp(Pred, LHS, RHS);
658 LLVM_DEBUG(
dbgs() <<
"Failed to parse the loop latch condition!\n");
664 if (!
Result->IV->isAffine()) {
669 auto *Step =
Result->IV->getStepRecurrence(*SE);
670 if (!isSupportedStep(Step)) {
671 LLVM_DEBUG(
dbgs() <<
"Unsupported loop stride(" << *Step <<
")!\n");
686 if (IsUnsupportedPredicate(Step,
Result->Pred)) {
695 bool LoopPredication::isSafeToTruncateWideIVType(
Type *RangeCheckType) {
700 "Expected latch check IV type to be larger than range check operand " 706 if (!Limit || !Start)
720 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
721 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
724 bool LoopPredication::isLoopProfitableToPredicate() {
732 if (ExitEdges.
size() == 1)
741 assert(LatchBlock &&
"Should have a single latch at this point!");
742 auto *LatchTerm = LatchBlock->getTerminator();
743 assert(LatchTerm->getNumSuccessors() == 2 &&
744 "expected to be an exiting block with 2 succs!");
745 unsigned LatchBrExitIdx =
746 LatchTerm->getSuccessor(0) == L->
getHeader() ? 1 : 0;
753 if (ScaleFactor < 1) {
756 <<
"Ignored user setting for loop-predication-latch-probability-scale: " 761 const auto LatchProbabilityThreshold =
762 LatchExitProbability * ScaleFactor;
764 for (
const auto &ExitEdge : ExitEdges) {
769 if (ExitingBlockProbability > LatchProbabilityThreshold)
778 bool LoopPredication::runOnLoop(
Loop *
Loop) {
789 if (!GuardDecl || GuardDecl->use_empty())
792 DL = &M->getDataLayout();
798 auto LatchCheckOpt = parseLoopLatchICmp();
801 LatchCheck = *LatchCheckOpt;
806 if (!isLoopProfitableToPredicate()) {
813 for (
const auto BB : L->
blocks())
815 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
816 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
824 bool Changed =
false;
825 for (
auto *Guard : Guards)
826 Changed |= widenGuardConditions(Guard, Expander);
Pass interface - Implemented by all 'passes'.
static bool Check(DecodeStatus &Out, DecodeStatus In)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
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.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred, bool &Increasing)
Return true if, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or...
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) INITIALIZE_PASS_END(LoopPredicationLegacyPass
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
static cl::opt< float > LatchExitProbabilityScale("loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), cl::desc("scale factor for the latch probability. Value should be greater " "than 1. Lower values are ignored"))
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
BlockT * getHeader() const
Analysis pass which computes BranchProbabilityInfo.
This node represents a polynomial recurrence on the trip count of the specified loop.
Legacy analysis pass which computes BranchProbabilityInfo.
Value * getOperand(unsigned i) const
Value * getOperand(unsigned i_nocapture) const
static cl::opt< bool > EnableIVTruncation("loop-predication-enable-iv-truncation", cl::Hidden, cl::init(true))
bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS. ...
initializer< Ty > init(const Ty &Val)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
ConstantInt * getTrue()
Get the constant value for i1 true.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
Represent the analysis usage information of a pass.
Pass * createLoopPredicationPass()
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
Type * getType() const
Return the LLVM type of this SCEV expression.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty)
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
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.
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
void setOperand(unsigned i_nocapture, Value *Val_nocapture)
static cl::opt< bool > EnableCountDownLoop("loop-predication-enable-count-down-loop", cl::Hidden, cl::init(true))
This class uses information about analyze scalars to rewrite expressions in canonical form...
iterator insert(iterator I, T &&Elt)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Predicate getPredicate() const
Return the predicate for this instruction.
Analysis providing branch probability information.
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
unsigned greater or equal
Represents a single loop in the control flow graph.
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)
static cl::opt< bool > SkipProfitabilityChecks("loop-predication-skip-profitability-checks", cl::Hidden, cl::init(false))
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void initializeLoopPredicationLegacyPassPass(PassRegistry &)
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
bool isOne() const
Return true if the expression is a constant one.
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
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...
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
iterator_range< block_iterator > blocks() const
A wrapper class for inspecting calls to intrinsic functions.
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)