Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
35294 views
//===- InductiveRangeCheckElimination.cpp - -------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// The InductiveRangeCheckElimination pass splits a loop's iteration space into9// three disjoint ranges. It does that in a way such that the loop running in10// the middle loop provably does not need range checks. As an example, it will11// convert12//13// len = < known positive >14// for (i = 0; i < n; i++) {15// if (0 <= i && i < len) {16// do_something();17// } else {18// throw_out_of_bounds();19// }20// }21//22// to23//24// len = < known positive >25// limit = smin(n, len)26// // no first segment27// for (i = 0; i < limit; i++) {28// if (0 <= i && i < len) { // this check is fully redundant29// do_something();30// } else {31// throw_out_of_bounds();32// }33// }34// for (i = limit; i < n; i++) {35// if (0 <= i && i < len) {36// do_something();37// } else {38// throw_out_of_bounds();39// }40// }41//42//===----------------------------------------------------------------------===//4344#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"45#include "llvm/ADT/APInt.h"46#include "llvm/ADT/ArrayRef.h"47#include "llvm/ADT/PriorityWorklist.h"48#include "llvm/ADT/SmallPtrSet.h"49#include "llvm/ADT/SmallVector.h"50#include "llvm/ADT/StringRef.h"51#include "llvm/ADT/Twine.h"52#include "llvm/Analysis/BlockFrequencyInfo.h"53#include "llvm/Analysis/BranchProbabilityInfo.h"54#include "llvm/Analysis/LoopAnalysisManager.h"55#include "llvm/Analysis/LoopInfo.h"56#include "llvm/Analysis/ScalarEvolution.h"57#include "llvm/Analysis/ScalarEvolutionExpressions.h"58#include "llvm/IR/BasicBlock.h"59#include "llvm/IR/CFG.h"60#include "llvm/IR/Constants.h"61#include "llvm/IR/DerivedTypes.h"62#include "llvm/IR/Dominators.h"63#include "llvm/IR/Function.h"64#include "llvm/IR/IRBuilder.h"65#include "llvm/IR/InstrTypes.h"66#include "llvm/IR/Instructions.h"67#include "llvm/IR/Metadata.h"68#include "llvm/IR/Module.h"69#include "llvm/IR/PatternMatch.h"70#include "llvm/IR/Type.h"71#include "llvm/IR/Use.h"72#include "llvm/IR/User.h"73#include "llvm/IR/Value.h"74#include "llvm/Support/BranchProbability.h"75#include "llvm/Support/Casting.h"76#include "llvm/Support/CommandLine.h"77#include "llvm/Support/Compiler.h"78#include "llvm/Support/Debug.h"79#include "llvm/Support/ErrorHandling.h"80#include "llvm/Support/raw_ostream.h"81#include "llvm/Transforms/Utils/BasicBlockUtils.h"82#include "llvm/Transforms/Utils/Cloning.h"83#include "llvm/Transforms/Utils/LoopConstrainer.h"84#include "llvm/Transforms/Utils/LoopSimplify.h"85#include "llvm/Transforms/Utils/LoopUtils.h"86#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"87#include "llvm/Transforms/Utils/ValueMapper.h"88#include <algorithm>89#include <cassert>90#include <iterator>91#include <optional>92#include <utility>9394using namespace llvm;95using namespace llvm::PatternMatch;9697static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,98cl::init(64));99100static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,101cl::init(false));102103static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,104cl::init(false));105106static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",107cl::Hidden, cl::init(false));108109static cl::opt<unsigned> MinRuntimeIterations("irce-min-runtime-iterations",110cl::Hidden, cl::init(10));111112static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",113cl::Hidden, cl::init(true));114115static cl::opt<bool> AllowNarrowLatchCondition(116"irce-allow-narrow-latch", cl::Hidden, cl::init(true),117cl::desc("If set to true, IRCE may eliminate wide range checks in loops "118"with narrow latch condition."));119120static cl::opt<unsigned> MaxTypeSizeForOverflowCheck(121"irce-max-type-size-for-overflow-check", cl::Hidden, cl::init(32),122cl::desc(123"Maximum size of range check type for which can be produced runtime "124"overflow check of its limit's computation"));125126static cl::opt<bool>127PrintScaledBoundaryRangeChecks("irce-print-scaled-boundary-range-checks",128cl::Hidden, cl::init(false));129130#define DEBUG_TYPE "irce"131132namespace {133134/// An inductive range check is conditional branch in a loop with135///136/// 1. a very cold successor (i.e. the branch jumps to that successor very137/// rarely)138///139/// and140///141/// 2. a condition that is provably true for some contiguous range of values142/// taken by the containing loop's induction variable.143///144class InductiveRangeCheck {145146const SCEV *Begin = nullptr;147const SCEV *Step = nullptr;148const SCEV *End = nullptr;149Use *CheckUse = nullptr;150151static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,152const SCEVAddRecExpr *&Index,153const SCEV *&End);154155static void156extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,157SmallVectorImpl<InductiveRangeCheck> &Checks,158SmallPtrSetImpl<Value *> &Visited);159160static bool parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,161ICmpInst::Predicate Pred, ScalarEvolution &SE,162const SCEVAddRecExpr *&Index,163const SCEV *&End);164165static bool reassociateSubLHS(Loop *L, Value *VariantLHS, Value *InvariantRHS,166ICmpInst::Predicate Pred, ScalarEvolution &SE,167const SCEVAddRecExpr *&Index, const SCEV *&End);168169public:170const SCEV *getBegin() const { return Begin; }171const SCEV *getStep() const { return Step; }172const SCEV *getEnd() const { return End; }173174void print(raw_ostream &OS) const {175OS << "InductiveRangeCheck:\n";176OS << " Begin: ";177Begin->print(OS);178OS << " Step: ";179Step->print(OS);180OS << " End: ";181End->print(OS);182OS << "\n CheckUse: ";183getCheckUse()->getUser()->print(OS);184OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";185}186187LLVM_DUMP_METHOD188void dump() {189print(dbgs());190}191192Use *getCheckUse() const { return CheckUse; }193194/// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If195/// R.getEnd() le R.getBegin(), then R denotes the empty range.196197class Range {198const SCEV *Begin;199const SCEV *End;200201public:202Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {203assert(Begin->getType() == End->getType() && "ill-typed range!");204}205206Type *getType() const { return Begin->getType(); }207const SCEV *getBegin() const { return Begin; }208const SCEV *getEnd() const { return End; }209bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {210if (Begin == End)211return true;212if (IsSigned)213return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);214else215return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);216}217};218219/// This is the value the condition of the branch needs to evaluate to for the220/// branch to take the hot successor (see (1) above).221bool getPassingDirection() { return true; }222223/// Computes a range for the induction variable (IndVar) in which the range224/// check is redundant and can be constant-folded away. The induction225/// variable is not required to be the canonical {0,+,1} induction variable.226std::optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,227const SCEVAddRecExpr *IndVar,228bool IsLatchSigned) const;229230/// Parse out a set of inductive range checks from \p BI and append them to \p231/// Checks.232///233/// NB! There may be conditions feeding into \p BI that aren't inductive range234/// checks, and hence don't end up in \p Checks.235static void extractRangeChecksFromBranch(236BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,237SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed);238};239240class InductiveRangeCheckElimination {241ScalarEvolution &SE;242BranchProbabilityInfo *BPI;243DominatorTree &DT;244LoopInfo &LI;245246using GetBFIFunc =247std::optional<llvm::function_ref<llvm::BlockFrequencyInfo &()>>;248GetBFIFunc GetBFI;249250// Returns true if it is profitable to do a transform basing on estimation of251// number of iterations.252bool isProfitableToTransform(const Loop &L, LoopStructure &LS);253254public:255InductiveRangeCheckElimination(ScalarEvolution &SE,256BranchProbabilityInfo *BPI, DominatorTree &DT,257LoopInfo &LI, GetBFIFunc GetBFI = std::nullopt)258: SE(SE), BPI(BPI), DT(DT), LI(LI), GetBFI(GetBFI) {}259260bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);261};262263} // end anonymous namespace264265/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot266/// be interpreted as a range check, return false. Otherwise set `Index` to the267/// SCEV being range checked, and set `End` to the upper or lower limit `Index`268/// is being range checked.269bool InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,270ScalarEvolution &SE,271const SCEVAddRecExpr *&Index,272const SCEV *&End) {273auto IsLoopInvariant = [&SE, L](Value *V) {274return SE.isLoopInvariant(SE.getSCEV(V), L);275};276277ICmpInst::Predicate Pred = ICI->getPredicate();278Value *LHS = ICI->getOperand(0);279Value *RHS = ICI->getOperand(1);280281if (!LHS->getType()->isIntegerTy())282return false;283284// Canonicalize to the `Index Pred Invariant` comparison285if (IsLoopInvariant(LHS)) {286std::swap(LHS, RHS);287Pred = CmpInst::getSwappedPredicate(Pred);288} else if (!IsLoopInvariant(RHS))289// Both LHS and RHS are loop variant290return false;291292if (parseIvAgaisntLimit(L, LHS, RHS, Pred, SE, Index, End))293return true;294295if (reassociateSubLHS(L, LHS, RHS, Pred, SE, Index, End))296return true;297298// TODO: support ReassociateAddLHS299return false;300}301302// Try to parse range check in the form of "IV vs Limit"303bool InductiveRangeCheck::parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,304ICmpInst::Predicate Pred,305ScalarEvolution &SE,306const SCEVAddRecExpr *&Index,307const SCEV *&End) {308309auto SIntMaxSCEV = [&](Type *T) {310unsigned BitWidth = cast<IntegerType>(T)->getBitWidth();311return SE.getConstant(APInt::getSignedMaxValue(BitWidth));312};313314const auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(LHS));315if (!AddRec)316return false;317318// We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".319// We can potentially do much better here.320// If we want to adjust upper bound for the unsigned range check as we do it321// for signed one, we will need to pick Unsigned max322switch (Pred) {323default:324return false;325326case ICmpInst::ICMP_SGE:327if (match(RHS, m_ConstantInt<0>())) {328Index = AddRec;329End = SIntMaxSCEV(Index->getType());330return true;331}332return false;333334case ICmpInst::ICMP_SGT:335if (match(RHS, m_ConstantInt<-1>())) {336Index = AddRec;337End = SIntMaxSCEV(Index->getType());338return true;339}340return false;341342case ICmpInst::ICMP_SLT:343case ICmpInst::ICMP_ULT:344Index = AddRec;345End = SE.getSCEV(RHS);346return true;347348case ICmpInst::ICMP_SLE:349case ICmpInst::ICMP_ULE:350const SCEV *One = SE.getOne(RHS->getType());351const SCEV *RHSS = SE.getSCEV(RHS);352bool Signed = Pred == ICmpInst::ICMP_SLE;353if (SE.willNotOverflow(Instruction::BinaryOps::Add, Signed, RHSS, One)) {354Index = AddRec;355End = SE.getAddExpr(RHSS, One);356return true;357}358return false;359}360361llvm_unreachable("default clause returns!");362}363364// Try to parse range check in the form of "IV - Offset vs Limit" or "Offset -365// IV vs Limit"366bool InductiveRangeCheck::reassociateSubLHS(367Loop *L, Value *VariantLHS, Value *InvariantRHS, ICmpInst::Predicate Pred,368ScalarEvolution &SE, const SCEVAddRecExpr *&Index, const SCEV *&End) {369Value *LHS, *RHS;370if (!match(VariantLHS, m_Sub(m_Value(LHS), m_Value(RHS))))371return false;372373const SCEV *IV = SE.getSCEV(LHS);374const SCEV *Offset = SE.getSCEV(RHS);375const SCEV *Limit = SE.getSCEV(InvariantRHS);376377bool OffsetSubtracted = false;378if (SE.isLoopInvariant(IV, L))379// "Offset - IV vs Limit"380std::swap(IV, Offset);381else if (SE.isLoopInvariant(Offset, L))382// "IV - Offset vs Limit"383OffsetSubtracted = true;384else385return false;386387const auto *AddRec = dyn_cast<SCEVAddRecExpr>(IV);388if (!AddRec)389return false;390391// In order to turn "IV - Offset < Limit" into "IV < Limit + Offset", we need392// to be able to freely move values from left side of inequality to right side393// (just as in normal linear arithmetics). Overflows make things much more394// complicated, so we want to avoid this.395//396// Let's prove that the initial subtraction doesn't overflow with all IV's397// values from the safe range constructed for that check.398//399// [Case 1] IV - Offset < Limit400// It doesn't overflow if:401// SINT_MIN <= IV - Offset <= SINT_MAX402// In terms of scaled SINT we need to prove:403// SINT_MIN + Offset <= IV <= SINT_MAX + Offset404// Safe range will be constructed:405// 0 <= IV < Limit + Offset406// It means that 'IV - Offset' doesn't underflow, because:407// SINT_MIN + Offset < 0 <= IV408// and doesn't overflow:409// IV < Limit + Offset <= SINT_MAX + Offset410//411// [Case 2] Offset - IV > Limit412// It doesn't overflow if:413// SINT_MIN <= Offset - IV <= SINT_MAX414// In terms of scaled SINT we need to prove:415// -SINT_MIN >= IV - Offset >= -SINT_MAX416// Offset - SINT_MIN >= IV >= Offset - SINT_MAX417// Safe range will be constructed:418// 0 <= IV < Offset - Limit419// It means that 'Offset - IV' doesn't underflow, because420// Offset - SINT_MAX < 0 <= IV421// and doesn't overflow:422// IV < Offset - Limit <= Offset - SINT_MIN423//424// For the computed upper boundary of the IV's range (Offset +/- Limit) we425// don't know exactly whether it overflows or not. So if we can't prove this426// fact at compile time, we scale boundary computations to a wider type with427// the intention to add runtime overflow check.428429auto getExprScaledIfOverflow = [&](Instruction::BinaryOps BinOp,430const SCEV *LHS,431const SCEV *RHS) -> const SCEV * {432const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,433SCEV::NoWrapFlags, unsigned);434switch (BinOp) {435default:436llvm_unreachable("Unsupported binary op");437case Instruction::Add:438Operation = &ScalarEvolution::getAddExpr;439break;440case Instruction::Sub:441Operation = &ScalarEvolution::getMinusSCEV;442break;443}444445if (SE.willNotOverflow(BinOp, ICmpInst::isSigned(Pred), LHS, RHS,446cast<Instruction>(VariantLHS)))447return (SE.*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0);448449// We couldn't prove that the expression does not overflow.450// Than scale it to a wider type to check overflow at runtime.451auto *Ty = cast<IntegerType>(LHS->getType());452if (Ty->getBitWidth() > MaxTypeSizeForOverflowCheck)453return nullptr;454455auto WideTy = IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);456return (SE.*Operation)(SE.getSignExtendExpr(LHS, WideTy),457SE.getSignExtendExpr(RHS, WideTy), SCEV::FlagAnyWrap,4580);459};460461if (OffsetSubtracted)462// "IV - Offset < Limit" -> "IV" < Offset + Limit463Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Offset, Limit);464else {465// "Offset - IV > Limit" -> "IV" < Offset - Limit466Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Sub, Offset, Limit);467Pred = ICmpInst::getSwappedPredicate(Pred);468}469470if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {471// "Expr <= Limit" -> "Expr < Limit + 1"472if (Pred == ICmpInst::ICMP_SLE && Limit)473Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Limit,474SE.getOne(Limit->getType()));475if (Limit) {476Index = AddRec;477End = Limit;478return true;479}480}481return false;482}483484void InductiveRangeCheck::extractRangeChecksFromCond(485Loop *L, ScalarEvolution &SE, Use &ConditionUse,486SmallVectorImpl<InductiveRangeCheck> &Checks,487SmallPtrSetImpl<Value *> &Visited) {488Value *Condition = ConditionUse.get();489if (!Visited.insert(Condition).second)490return;491492// TODO: Do the same for OR, XOR, NOT etc?493if (match(Condition, m_LogicalAnd(m_Value(), m_Value()))) {494extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),495Checks, Visited);496extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),497Checks, Visited);498return;499}500501ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);502if (!ICI)503return;504505const SCEV *End = nullptr;506const SCEVAddRecExpr *IndexAddRec = nullptr;507if (!parseRangeCheckICmp(L, ICI, SE, IndexAddRec, End))508return;509510assert(IndexAddRec && "IndexAddRec was not computed");511assert(End && "End was not computed");512513if ((IndexAddRec->getLoop() != L) || !IndexAddRec->isAffine())514return;515516InductiveRangeCheck IRC;517IRC.End = End;518IRC.Begin = IndexAddRec->getStart();519IRC.Step = IndexAddRec->getStepRecurrence(SE);520IRC.CheckUse = &ConditionUse;521Checks.push_back(IRC);522}523524void InductiveRangeCheck::extractRangeChecksFromBranch(525BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,526SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed) {527if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())528return;529530unsigned IndexLoopSucc = L->contains(BI->getSuccessor(0)) ? 0 : 1;531assert(L->contains(BI->getSuccessor(IndexLoopSucc)) &&532"No edges coming to loop?");533BranchProbability LikelyTaken(15, 16);534535if (!SkipProfitabilityChecks && BPI &&536BPI->getEdgeProbability(BI->getParent(), IndexLoopSucc) < LikelyTaken)537return;538539// IRCE expects branch's true edge comes to loop. Invert branch for opposite540// case.541if (IndexLoopSucc != 0) {542IRBuilder<> Builder(BI);543InvertBranch(BI, Builder);544if (BPI)545BPI->swapSuccEdgesProbabilities(BI->getParent());546Changed = true;547}548549SmallPtrSet<Value *, 8> Visited;550InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),551Checks, Visited);552}553554/// If the type of \p S matches with \p Ty, return \p S. Otherwise, return555/// signed or unsigned extension of \p S to type \p Ty.556static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,557bool Signed) {558return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty);559}560561// Compute a safe set of limits for the main loop to run in -- effectively the562// intersection of `Range' and the iteration space of the original loop.563// Return std::nullopt if unable to compute the set of subranges.564static std::optional<LoopConstrainer::SubRanges>565calculateSubRanges(ScalarEvolution &SE, const Loop &L,566InductiveRangeCheck::Range &Range,567const LoopStructure &MainLoopStructure) {568auto *RTy = cast<IntegerType>(Range.getType());569// We only support wide range checks and narrow latches.570if (!AllowNarrowLatchCondition && RTy != MainLoopStructure.ExitCountTy)571return std::nullopt;572if (RTy->getBitWidth() < MainLoopStructure.ExitCountTy->getBitWidth())573return std::nullopt;574575LoopConstrainer::SubRanges Result;576577bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;578// I think we can be more aggressive here and make this nuw / nsw if the579// addition that feeds into the icmp for the latch's terminating branch is nuw580// / nsw. In any case, a wrapping 2's complement addition is safe.581const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart),582RTy, SE, IsSignedPredicate);583const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,584SE, IsSignedPredicate);585586bool Increasing = MainLoopStructure.IndVarIncreasing;587588// We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or589// [Smallest, GreatestSeen] is the range of values the induction variable590// takes.591592const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;593594const SCEV *One = SE.getOne(RTy);595if (Increasing) {596Smallest = Start;597Greatest = End;598// No overflow, because the range [Smallest, GreatestSeen] is not empty.599GreatestSeen = SE.getMinusSCEV(End, One);600} else {601// These two computations may sign-overflow. Here is why that is okay:602//603// We know that the induction variable does not sign-overflow on any604// iteration except the last one, and it starts at `Start` and ends at605// `End`, decrementing by one every time.606//607// * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the608// induction variable is decreasing we know that the smallest value609// the loop body is actually executed with is `INT_SMIN` == `Smallest`.610//611// * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In612// that case, `Clamp` will always return `Smallest` and613// [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)614// will be an empty range. Returning an empty range is always safe.615616Smallest = SE.getAddExpr(End, One);617Greatest = SE.getAddExpr(Start, One);618GreatestSeen = Start;619}620621auto Clamp = [&SE, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {622return IsSignedPredicate623? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))624: SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));625};626627// In some cases we can prove that we don't need a pre or post loop.628ICmpInst::Predicate PredLE =629IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;630ICmpInst::Predicate PredLT =631IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;632633bool ProvablyNoPreloop =634SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);635if (!ProvablyNoPreloop)636Result.LowLimit = Clamp(Range.getBegin());637638bool ProvablyNoPostLoop =639SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());640if (!ProvablyNoPostLoop)641Result.HighLimit = Clamp(Range.getEnd());642643return Result;644}645646/// Computes and returns a range of values for the induction variable (IndVar)647/// in which the range check can be safely elided. If it cannot compute such a648/// range, returns std::nullopt.649std::optional<InductiveRangeCheck::Range>650InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,651const SCEVAddRecExpr *IndVar,652bool IsLatchSigned) const {653// We can deal when types of latch check and range checks don't match in case654// if latch check is more narrow.655auto *IVType = dyn_cast<IntegerType>(IndVar->getType());656auto *RCType = dyn_cast<IntegerType>(getBegin()->getType());657auto *EndType = dyn_cast<IntegerType>(getEnd()->getType());658// Do not work with pointer types.659if (!IVType || !RCType)660return std::nullopt;661if (IVType->getBitWidth() > RCType->getBitWidth())662return std::nullopt;663664// IndVar is of the form "A + B * I" (where "I" is the canonical induction665// variable, that may or may not exist as a real llvm::Value in the loop) and666// this inductive range check is a range check on the "C + D * I" ("C" is667// getBegin() and "D" is getStep()). We rewrite the value being range668// checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".669//670// The actual inequalities we solve are of the form671//672// 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)673//674// Here L stands for upper limit of the safe iteration space.675// The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid676// overflows when calculating (0 - M) and (L - M) we, depending on type of677// IV's iteration space, limit the calculations by borders of the iteration678// space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.679// If we figured out that "anything greater than (-M) is safe", we strengthen680// this to "everything greater than 0 is safe", assuming that values between681// -M and 0 just do not exist in unsigned iteration space, and we don't want682// to deal with overflown values.683684if (!IndVar->isAffine())685return std::nullopt;686687const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned);688const SCEVConstant *B = dyn_cast<SCEVConstant>(689NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned));690if (!B)691return std::nullopt;692assert(!B->isZero() && "Recurrence with zero step?");693694const SCEV *C = getBegin();695const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());696if (D != B)697return std::nullopt;698699assert(!D->getValue()->isZero() && "Recurrence with zero step?");700unsigned BitWidth = RCType->getBitWidth();701const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));702const SCEV *SIntMin = SE.getConstant(APInt::getSignedMinValue(BitWidth));703704// Subtract Y from X so that it does not go through border of the IV705// iteration space. Mathematically, it is equivalent to:706//707// ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]708//709// In [1], 'X - Y' is a mathematical subtraction (result is not bounded to710// any width of bit grid). But after we take min/max, the result is711// guaranteed to be within [INT_MIN, INT_MAX].712//713// In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min714// values, depending on type of latch condition that defines IV iteration715// space.716auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {717// FIXME: The current implementation assumes that X is in [0, SINT_MAX].718// This is required to ensure that SINT_MAX - X does not overflow signed and719// that X - Y does not overflow unsigned if Y is negative. Can we lift this720// restriction and make it work for negative X either?721if (IsLatchSigned) {722// X is a number from signed range, Y is interpreted as signed.723// Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only724// thing we should care about is that we didn't cross SINT_MAX.725// So, if Y is positive, we subtract Y safely.726// Rule 1: Y > 0 ---> Y.727// If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.728// Rule 2: Y >=s (X - SINT_MAX) ---> Y.729// If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).730// Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).731// It gives us smax(Y, X - SINT_MAX) to subtract in all cases.732const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);733return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),734SCEV::FlagNSW);735} else736// X is a number from unsigned range, Y is interpreted as signed.737// Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only738// thing we should care about is that we didn't cross zero.739// So, if Y is negative, we subtract Y safely.740// Rule 1: Y <s 0 ---> Y.741// If 0 <= Y <= X, we subtract Y safely.742// Rule 2: Y <=s X ---> Y.743// If 0 <= X < Y, we should stop at 0 and can only subtract X.744// Rule 3: Y >s X ---> X.745// It gives us smin(X, Y) to subtract in all cases.746return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);747};748const SCEV *M = SE.getMinusSCEV(C, A);749const SCEV *Zero = SE.getZero(M->getType());750751// This function returns SCEV equal to 1 if X is non-negative 0 otherwise.752auto SCEVCheckNonNegative = [&](const SCEV *X) {753const Loop *L = IndVar->getLoop();754const SCEV *Zero = SE.getZero(X->getType());755const SCEV *One = SE.getOne(X->getType());756// Can we trivially prove that X is a non-negative or negative value?757if (isKnownNonNegativeInLoop(X, L, SE))758return One;759else if (isKnownNegativeInLoop(X, L, SE))760return Zero;761// If not, we will have to figure it out during the execution.762// Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.763const SCEV *NegOne = SE.getNegativeSCEV(One);764return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);765};766767// This function returns SCEV equal to 1 if X will not overflow in terms of768// range check type, 0 otherwise.769auto SCEVCheckWillNotOverflow = [&](const SCEV *X) {770// X doesn't overflow if SINT_MAX >= X.771// Then if (SINT_MAX - X) >= 0, X doesn't overflow772const SCEV *SIntMaxExt = SE.getSignExtendExpr(SIntMax, X->getType());773const SCEV *OverflowCheck =774SCEVCheckNonNegative(SE.getMinusSCEV(SIntMaxExt, X));775776// X doesn't underflow if X >= SINT_MIN.777// Then if (X - SINT_MIN) >= 0, X doesn't underflow778const SCEV *SIntMinExt = SE.getSignExtendExpr(SIntMin, X->getType());779const SCEV *UnderflowCheck =780SCEVCheckNonNegative(SE.getMinusSCEV(X, SIntMinExt));781782return SE.getMulExpr(OverflowCheck, UnderflowCheck);783};784785// FIXME: Current implementation of ClampedSubtract implicitly assumes that786// X is non-negative (in sense of a signed value). We need to re-implement787// this function in a way that it will correctly handle negative X as well.788// We use it twice: for X = 0 everything is fine, but for X = getEnd() we can789// end up with a negative X and produce wrong results. So currently we ensure790// that if getEnd() is negative then both ends of the safe range are zero.791// Note that this may pessimize elimination of unsigned range checks against792// negative values.793const SCEV *REnd = getEnd();794const SCEV *EndWillNotOverflow = SE.getOne(RCType);795796auto PrintRangeCheck = [&](raw_ostream &OS) {797auto L = IndVar->getLoop();798OS << "irce: in function ";799OS << L->getHeader()->getParent()->getName();800OS << ", in ";801L->print(OS);802OS << "there is range check with scaled boundary:\n";803print(OS);804};805806if (EndType->getBitWidth() > RCType->getBitWidth()) {807assert(EndType->getBitWidth() == RCType->getBitWidth() * 2);808if (PrintScaledBoundaryRangeChecks)809PrintRangeCheck(errs());810// End is computed with extended type but will be truncated to a narrow one811// type of range check. Therefore we need a check that the result will not812// overflow in terms of narrow type.813EndWillNotOverflow =814SE.getTruncateExpr(SCEVCheckWillNotOverflow(REnd), RCType);815REnd = SE.getTruncateExpr(REnd, RCType);816}817818const SCEV *RuntimeChecks =819SE.getMulExpr(SCEVCheckNonNegative(REnd), EndWillNotOverflow);820const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), RuntimeChecks);821const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), RuntimeChecks);822823return InductiveRangeCheck::Range(Begin, End);824}825826static std::optional<InductiveRangeCheck::Range>827IntersectSignedRange(ScalarEvolution &SE,828const std::optional<InductiveRangeCheck::Range> &R1,829const InductiveRangeCheck::Range &R2) {830if (R2.isEmpty(SE, /* IsSigned */ true))831return std::nullopt;832if (!R1)833return R2;834auto &R1Value = *R1;835// We never return empty ranges from this function, and R1 is supposed to be836// a result of intersection. Thus, R1 is never empty.837assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&838"We should never have empty R1!");839840// TODO: we could widen the smaller range and have this work; but for now we841// bail out to keep things simple.842if (R1Value.getType() != R2.getType())843return std::nullopt;844845const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());846const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());847848// If the resulting range is empty, just return std::nullopt.849auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);850if (Ret.isEmpty(SE, /* IsSigned */ true))851return std::nullopt;852return Ret;853}854855static std::optional<InductiveRangeCheck::Range>856IntersectUnsignedRange(ScalarEvolution &SE,857const std::optional<InductiveRangeCheck::Range> &R1,858const InductiveRangeCheck::Range &R2) {859if (R2.isEmpty(SE, /* IsSigned */ false))860return std::nullopt;861if (!R1)862return R2;863auto &R1Value = *R1;864// We never return empty ranges from this function, and R1 is supposed to be865// a result of intersection. Thus, R1 is never empty.866assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&867"We should never have empty R1!");868869// TODO: we could widen the smaller range and have this work; but for now we870// bail out to keep things simple.871if (R1Value.getType() != R2.getType())872return std::nullopt;873874const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());875const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());876877// If the resulting range is empty, just return std::nullopt.878auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);879if (Ret.isEmpty(SE, /* IsSigned */ false))880return std::nullopt;881return Ret;882}883884PreservedAnalyses IRCEPass::run(Function &F, FunctionAnalysisManager &AM) {885auto &DT = AM.getResult<DominatorTreeAnalysis>(F);886LoopInfo &LI = AM.getResult<LoopAnalysis>(F);887// There are no loops in the function. Return before computing other expensive888// analyses.889if (LI.empty())890return PreservedAnalyses::all();891auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);892auto &BPI = AM.getResult<BranchProbabilityAnalysis>(F);893894// Get BFI analysis result on demand. Please note that modification of895// CFG invalidates this analysis and we should handle it.896auto getBFI = [&F, &AM ]()->BlockFrequencyInfo & {897return AM.getResult<BlockFrequencyAnalysis>(F);898};899InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI, { getBFI });900901bool Changed = false;902{903bool CFGChanged = false;904for (const auto &L : LI) {905CFGChanged |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr,906/*PreserveLCSSA=*/false);907Changed |= formLCSSARecursively(*L, DT, &LI, &SE);908}909Changed |= CFGChanged;910911if (CFGChanged && !SkipProfitabilityChecks) {912PreservedAnalyses PA = PreservedAnalyses::all();913PA.abandon<BlockFrequencyAnalysis>();914AM.invalidate(F, PA);915}916}917918SmallPriorityWorklist<Loop *, 4> Worklist;919appendLoopsToWorklist(LI, Worklist);920auto LPMAddNewLoop = [&Worklist](Loop *NL, bool IsSubloop) {921if (!IsSubloop)922appendLoopsToWorklist(*NL, Worklist);923};924925while (!Worklist.empty()) {926Loop *L = Worklist.pop_back_val();927if (IRCE.run(L, LPMAddNewLoop)) {928Changed = true;929if (!SkipProfitabilityChecks) {930PreservedAnalyses PA = PreservedAnalyses::all();931PA.abandon<BlockFrequencyAnalysis>();932AM.invalidate(F, PA);933}934}935}936937if (!Changed)938return PreservedAnalyses::all();939return getLoopPassPreservedAnalyses();940}941942bool943InductiveRangeCheckElimination::isProfitableToTransform(const Loop &L,944LoopStructure &LS) {945if (SkipProfitabilityChecks)946return true;947if (GetBFI) {948BlockFrequencyInfo &BFI = (*GetBFI)();949uint64_t hFreq = BFI.getBlockFreq(LS.Header).getFrequency();950uint64_t phFreq = BFI.getBlockFreq(L.getLoopPreheader()).getFrequency();951if (phFreq != 0 && hFreq != 0 && (hFreq / phFreq < MinRuntimeIterations)) {952LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "953<< "the estimated number of iterations basing on "954"frequency info is " << (hFreq / phFreq) << "\n";);955return false;956}957return true;958}959960if (!BPI)961return true;962BranchProbability ExitProbability =963BPI->getEdgeProbability(LS.Latch, LS.LatchBrExitIdx);964if (ExitProbability > BranchProbability(1, MinRuntimeIterations)) {965LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "966<< "the exit probability is too big " << ExitProbability967<< "\n";);968return false;969}970return true;971}972973bool InductiveRangeCheckElimination::run(974Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {975if (L->getBlocks().size() >= LoopSizeCutoff) {976LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");977return false;978}979980BasicBlock *Preheader = L->getLoopPreheader();981if (!Preheader) {982LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");983return false;984}985986LLVMContext &Context = Preheader->getContext();987SmallVector<InductiveRangeCheck, 16> RangeChecks;988bool Changed = false;989990for (auto *BBI : L->getBlocks())991if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))992InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,993RangeChecks, Changed);994995if (RangeChecks.empty())996return Changed;997998auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {999OS << "irce: looking at loop "; L->print(OS);1000OS << "irce: loop has " << RangeChecks.size()1001<< " inductive range checks: \n";1002for (InductiveRangeCheck &IRC : RangeChecks)1003IRC.print(OS);1004};10051006LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));10071008if (PrintRangeChecks)1009PrintRecognizedRangeChecks(errs());10101011const char *FailureReason = nullptr;1012std::optional<LoopStructure> MaybeLoopStructure =1013LoopStructure::parseLoopStructure(SE, *L, AllowUnsignedLatchCondition,1014FailureReason);1015if (!MaybeLoopStructure) {1016LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "1017<< FailureReason << "\n";);1018return Changed;1019}1020LoopStructure LS = *MaybeLoopStructure;1021if (!isProfitableToTransform(*L, LS))1022return Changed;1023const SCEVAddRecExpr *IndVar =1024cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));10251026std::optional<InductiveRangeCheck::Range> SafeIterRange;10271028SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;1029// Basing on the type of latch predicate, we interpret the IV iteration range1030// as signed or unsigned range. We use different min/max functions (signed or1031// unsigned) when intersecting this range with safe iteration ranges implied1032// by range checks.1033auto IntersectRange =1034LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;10351036for (InductiveRangeCheck &IRC : RangeChecks) {1037auto Result = IRC.computeSafeIterationSpace(SE, IndVar,1038LS.IsSignedPredicate);1039if (Result) {1040auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result);1041if (MaybeSafeIterRange) {1042assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) &&1043"We should never return empty ranges!");1044RangeChecksToEliminate.push_back(IRC);1045SafeIterRange = *MaybeSafeIterRange;1046}1047}1048}10491050if (!SafeIterRange)1051return Changed;10521053std::optional<LoopConstrainer::SubRanges> MaybeSR =1054calculateSubRanges(SE, *L, *SafeIterRange, LS);1055if (!MaybeSR) {1056LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");1057return false;1058}10591060LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,1061SafeIterRange->getBegin()->getType(), *MaybeSR);10621063if (LC.run()) {1064Changed = true;10651066auto PrintConstrainedLoopInfo = [L]() {1067dbgs() << "irce: in function ";1068dbgs() << L->getHeader()->getParent()->getName() << ": ";1069dbgs() << "constrained ";1070L->print(dbgs());1071};10721073LLVM_DEBUG(PrintConstrainedLoopInfo());10741075if (PrintChangedLoops)1076PrintConstrainedLoopInfo();10771078// Optimize away the now-redundant range checks.10791080for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {1081ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()1082? ConstantInt::getTrue(Context)1083: ConstantInt::getFalse(Context);1084IRC.getCheckUse()->set(FoldedRangeCheck);1085}1086}10871088return Changed;1089}109010911092