121 cl::desc(
"If set to true, IRCE may eliminate wide range checks in loops " 122 "with narrow latch condition."));
126 #define DEBUG_TYPE "irce" 140 class InductiveRangeCheck {
142 const SCEV *Begin =
nullptr;
143 const SCEV *Step =
nullptr;
144 const SCEV *End =
nullptr;
145 Use *CheckUse =
nullptr;
146 bool IsSigned =
true;
158 const SCEV *getBegin()
const {
return Begin; }
159 const SCEV *getStep()
const {
return Step; }
160 const SCEV *getEnd()
const {
return End; }
161 bool isSigned()
const {
return IsSigned; }
164 OS <<
"InductiveRangeCheck:\n";
171 OS <<
"\n CheckUse: ";
172 getCheckUse()->getUser()->print(OS);
173 OS <<
" Operand: " << getCheckUse()->getOperandNo() <<
"\n";
181 Use *getCheckUse()
const {
return CheckUse; }
191 Range(
const SCEV *Begin,
const SCEV *End) : Begin(Begin), End(End) {
196 const SCEV *getBegin()
const {
return Begin; }
197 const SCEV *getEnd()
const {
return End; }
210 bool getPassingDirection() {
return true; }
217 bool IsLatchSigned)
const;
230 class InductiveRangeCheckElimination {
240 : SE(SE), BPI(BPI), DT(DT), LI(LI) {}
245 class IRCELegacyPass :
public LoopPass {
266 "Inductive range check elimination",
false,
false)
277 InductiveRangeCheck::parseRangeCheckICmp(
Loop *L,
ICmpInst *ICI,
279 Value *&Length,
bool &IsSigned) {
280 auto IsLoopInvariant = [&SE, L](
Value *V) {
281 return SE.isLoopInvariant(SE.getSCEV(V), L);
285 Value *LHS = ICI->getOperand(0);
286 Value *RHS = ICI->getOperand(1);
297 if (
match(RHS, m_ConstantInt<0>())) {
308 if (
match(RHS, m_ConstantInt<-1>())) {
313 if (IsLoopInvariant(LHS)) {
325 if (IsLoopInvariant(LHS)) {
336 void InductiveRangeCheck::extractRangeChecksFromCond(
340 Value *Condition = ConditionUse.
get();
341 if (!Visited.
insert(Condition).second)
346 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
348 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
359 if (!parseRangeCheckICmp(L, ICI, SE,
Index, Length, IsSigned))
364 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->
isAffine();
369 const SCEV *End =
nullptr;
378 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->
getBitWidth();
383 InductiveRangeCheck IRC;
385 IRC.Begin = IndexAddRec->getStart();
386 IRC.Step = IndexAddRec->getStepRecurrence(SE);
387 IRC.CheckUse = &ConditionUse;
388 IRC.IsSigned = IsSigned;
392 void InductiveRangeCheck::extractRangeChecksFromBranch(
405 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->
getOperandUse(0),
418 Context, {
MDString::get(Context,
"llvm.loop.unroll.disable")});
423 {
MDString::get(Context,
"llvm.loop.vectorize.enable"), FalseVal});
425 Context, {
MDString::get(Context,
"llvm.loop.licm_versioning.disable")});
428 {
MDString::get(Context,
"llvm.loop.distribute.enable"), FalseVal});
431 DisableLICMVersioning, DisableDistribution});
444 struct LoopStructure {
445 const char *Tag =
"";
465 Value *IndVarBase =
nullptr;
466 Value *IndVarStart =
nullptr;
467 Value *IndVarStep =
nullptr;
468 Value *LoopExitAt =
nullptr;
469 bool IndVarIncreasing =
false;
470 bool IsSignedPredicate =
true;
472 LoopStructure() =
default;
474 template <
typename M> LoopStructure map(M Map)
const {
475 LoopStructure Result;
477 Result.Header = cast<BasicBlock>(Map(Header));
478 Result.Latch = cast<BasicBlock>(Map(Latch));
479 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
480 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
481 Result.LatchBrExitIdx = LatchBrExitIdx;
482 Result.IndVarBase = Map(IndVarBase);
483 Result.IndVarStart = Map(IndVarStart);
484 Result.IndVarStep = Map(IndVarStep);
485 Result.LoopExitAt = Map(LoopExitAt);
486 Result.IndVarIncreasing = IndVarIncreasing;
487 Result.IsSignedPredicate = IsSignedPredicate;
493 Loop &,
const char *&);
504 class LoopConstrainer {
508 std::vector<BasicBlock *> Blocks;
514 LoopStructure Structure;
519 struct RewrittenRangeInfo {
522 std::vector<PHINode *> PHIValuesAtPseudoExit;
525 RewrittenRangeInfo() =
default;
549 void cloneLoop(ClonedLoop &CLResult,
const char *Tag)
const;
553 Loop *createClonedLoopStructure(
Loop *Original,
Loop *Parent,
578 changeIterationSpaceEnd(
const LoopStructure &
LS,
BasicBlock *Preheader,
585 const char *Tag)
const;
591 void rewriteIncomingValuesForPHIs(
592 LoopStructure &LS,
BasicBlock *ContinuationBlockAndPreheader,
593 const LoopConstrainer::RewrittenRangeInfo &RRI)
const;
612 const SCEV *LatchTakenCount =
nullptr;
620 InductiveRangeCheck::Range Range;
624 LoopStructure MainLoopStructure;
632 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
633 Range(R), MainLoopStructure(LS) {}
644 const SCEV *BoundSCEV,
const SCEV *Step,
646 unsigned LatchBrExitIdx,
663 LLVM_DEBUG(
dbgs() <<
"irce: LatchExitBrIdx: " << LatchBrExitIdx <<
"\n");
671 if (LatchBrExitIdx == 1)
674 assert(LatchBrExitIdx == 0 &&
675 "LatchBrExitIdx should be either 0 or 1");
683 const SCEV *MinusOne =
694 const SCEV *BoundSCEV,
const SCEV *Step,
696 unsigned LatchBrExitIdx,
711 LLVM_DEBUG(
dbgs() <<
"irce: LatchExitBrIdx: " << LatchBrExitIdx <<
"\n");
719 if (LatchBrExitIdx == 1)
722 assert(LatchBrExitIdx == 0 &&
"LatchBrExitIdx should be 0 or 1");
724 const SCEV *StepMinusOne =
739 const char *&FailureReason) {
741 FailureReason =
"loop not in LoopSimplify form";
746 assert(Latch &&
"Simplified loops only have one latch!");
749 FailureReason =
"loop has already been cloned";
754 FailureReason =
"no loop latch";
761 FailureReason =
"no preheader";
767 FailureReason =
"latch terminator not conditional branch";
771 unsigned LatchBrExitIdx = LatchBr->
getSuccessor(0) == Header ? 1 : 0;
779 FailureReason =
"short running loop, not profitable";
785 FailureReason =
"latch terminator branch not conditional on integral icmp";
790 if (isa<SCEVCouldNotCompute>(LatchCount)) {
791 FailureReason =
"could not compute latch count";
804 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
805 if (isa<SCEVAddRecExpr>(RightSCEV)) {
810 FailureReason =
"no add recurrences in the icmp";
819 IntegerType *Ty = cast<IntegerType>(AR->getType());
827 const SCEV *ExtendedStep =
830 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
831 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
844 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
846 FailureReason =
"LHS in icmp not induction variable";
850 if (!isa<SCEVConstant>(StepRec)) {
851 FailureReason =
"LHS in icmp not induction variable";
854 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
856 if (ICI->
isEquality() && !HasNoSignedWrap(IndVarBase)) {
857 FailureReason =
"LHS in icmp needs nsw for equality predicates";
863 bool IsSignedPredicate;
871 bool DecreasedRightValueByOne =
false;
872 if (StepCI->
isOne()) {
897 DecreasedRightValueByOne =
true;
902 DecreasedRightValueByOne =
true;
909 bool FoundExpectedPred =
910 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
912 if (!FoundExpectedPred) {
913 FailureReason =
"expected icmp slt semantically, found something else";
919 FailureReason =
"unsigned latch conditions are explicitly prohibited";
924 LatchBrExitIdx, &L, SE)) {
925 FailureReason =
"Unsafe loop bounds";
928 if (LatchBrExitIdx == 0) {
931 if (!DecreasedRightValueByOne) {
933 RightValue =
B.CreateAdd(RightValue, One);
936 assert(!DecreasedRightValueByOne &&
937 "Right value can be decreased only for LatchBrExitIdx == 0!");
940 bool IncreasedRightValueByOne =
false;
961 IncreasedRightValueByOne =
true;
965 IncreasedRightValueByOne =
true;
973 bool FoundExpectedPred =
974 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
976 if (!FoundExpectedPred) {
977 FailureReason =
"expected icmp sgt semantically, found something else";
985 FailureReason =
"unsigned latch conditions are explicitly prohibited";
990 LatchBrExitIdx, &L, SE)) {
991 FailureReason =
"Unsafe bounds";
995 if (LatchBrExitIdx == 0) {
998 if (!IncreasedRightValueByOne) {
1000 RightValue =
B.CreateSub(RightValue, One);
1003 assert(!IncreasedRightValueByOne &&
1004 "Right value can be increased only for LatchBrExitIdx == 0!");
1011 "loop variant exit count doesn't make sense!");
1015 Value *IndVarStartV =
1018 IndVarStartV->
setName(
"indvar.start");
1020 LoopStructure Result;
1022 Result.Tag =
"main";
1023 Result.Header = Header;
1024 Result.Latch = Latch;
1025 Result.LatchBr = LatchBr;
1026 Result.LatchExit = LatchExit;
1027 Result.LatchBrExitIdx = LatchBrExitIdx;
1028 Result.IndVarStart = IndVarStartV;
1029 Result.IndVarStep = StepCI;
1030 Result.IndVarBase = LeftValue;
1031 Result.IndVarIncreasing = IsIncreasing;
1032 Result.LoopExitAt = RightValue;
1033 Result.IsSignedPredicate = IsSignedPredicate;
1035 FailureReason =
nullptr;
1048 LoopConstrainer::calculateSubRanges(
bool IsSignedPredicate)
const {
1049 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1051 auto *RTy = cast<IntegerType>(Range.getType());
1059 LoopConstrainer::SubRanges Result;
1065 RTy, SE, IsSignedPredicate);
1066 const SCEV *End =
NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,
1067 SE, IsSignedPredicate);
1069 bool Increasing = MainLoopStructure.IndVarIncreasing;
1075 const SCEV *Smallest =
nullptr, *Greatest =
nullptr, *GreatestSeen =
nullptr;
1077 const SCEV *One = SE.getOne(RTy);
1082 GreatestSeen = SE.getMinusSCEV(End, One);
1099 Smallest = SE.getAddExpr(End, One);
1100 Greatest = SE.getAddExpr(Start, One);
1101 GreatestSeen = Start;
1104 auto Clamp = [
this, Smallest, Greatest, IsSignedPredicate](
const SCEV *S) {
1105 return IsSignedPredicate
1106 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1107 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
1116 bool ProvablyNoPreloop =
1117 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
1118 if (!ProvablyNoPreloop)
1119 Result.LowLimit = Clamp(Range.getBegin());
1121 bool ProvablyNoPostLoop =
1122 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
1123 if (!ProvablyNoPostLoop)
1124 Result.HighLimit = Clamp(Range.getEnd());
1129 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1130 const char *Tag)
const {
1131 for (
BasicBlock *BB : OriginalLoop.getBlocks()) {
1133 Result.Blocks.push_back(Clone);
1134 Result.Map[BB] = Clone;
1137 auto GetClonedValue = [&Result](
Value *V) {
1138 assert(V &&
"null values not in domain!");
1139 auto It = Result.Map.find(V);
1140 if (It == Result.Map.end())
1142 return static_cast<Value *
>(It->second);
1146 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1150 Result.Structure = MainLoopStructure.map(GetClonedValue);
1151 Result.Structure.Tag = Tag;
1153 for (
unsigned i = 0,
e = Result.Blocks.size(); i !=
e; ++i) {
1155 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1157 assert(Result.Map[OriginalBB] == ClonedBB &&
"invariant!");
1168 if (OriginalLoop.contains(
SBB))
1172 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
1173 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1179 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
1253 RewrittenRangeInfo RRI;
1255 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
1257 &
F, BBInsertLocation);
1262 bool Increasing = LS.IndVarIncreasing;
1263 bool IsSignedPredicate = LS.IsSignedPredicate;
1266 auto *RangeTy = Range.getBegin()->getType();
1267 auto NoopOrExt = [&](
Value *V) {
1268 if (V->getType() == RangeTy)
1270 return IsSignedPredicate ? B.
CreateSExt(V, RangeTy,
"wide." + V->getName())
1271 : B.
CreateZExt(V, RangeTy,
"wide." + V->getName());
1275 Value *EnterLoopCond =
nullptr;
1280 Value *IndVarStart = NoopOrExt(LS.IndVarStart);
1281 EnterLoopCond = B.
CreateICmp(Pred, IndVarStart, ExitSubloopAt);
1283 B.
CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1286 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1288 Value *IndVarBase = NoopOrExt(LS.IndVarBase);
1289 Value *TakeBackedgeLoopCond = B.
CreateICmp(Pred, IndVarBase, ExitSubloopAt);
1291 Value *CondForBranch = LS.LatchBrExitIdx == 1
1292 ? TakeBackedgeLoopCond
1295 LS.LatchBr->setCondition(CondForBranch);
1302 Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
1304 B.
CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1312 for (
PHINode &PN : LS.Header->phis()) {
1314 BranchToContinuation);
1316 NewPHI->
addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
1317 NewPHI->
addIncoming(PN.getIncomingValueForBlock(LS.Latch),
1319 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1323 BranchToContinuation);
1324 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
1325 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
1329 LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
1334 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1335 LoopStructure &LS,
BasicBlock *ContinuationBlock,
1336 const LoopConstrainer::RewrittenRangeInfo &RRI)
const {
1337 unsigned PHIIndex = 0;
1338 for (
PHINode &PN : LS.Header->phis())
1339 PN.setIncomingValueForBlock(ContinuationBlock,
1340 RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1342 LS.IndVarStart = RRI.IndVarEnd;
1345 BasicBlock *LoopConstrainer::createPreheader(
const LoopStructure &LS,
1347 const char *Tag)
const {
1351 LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
1365 Loop *LoopConstrainer::createClonedLoopStructure(
Loop *Original,
Loop *Parent,
1368 Loop &New = *LI.AllocateLoop();
1372 LI.addTopLevelLoop(&New);
1373 LPMAddNewLoop(&New, IsSubloop);
1376 for (
auto *BB : Original->
blocks())
1377 if (LI.getLoopFor(BB) == Original)
1381 for (
Loop *SubLoop : *Original)
1382 createClonedLoopStructure(SubLoop, &New, VM,
true);
1387 bool LoopConstrainer::run() {
1389 LatchTakenCount = SE.
getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1390 Preheader = OriginalLoop.getLoopPreheader();
1391 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader !=
nullptr &&
1394 OriginalPreheader = Preheader;
1395 MainLoopPreheader = Preheader;
1397 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1405 bool Increasing = MainLoopStructure.IndVarIncreasing;
1407 cast<IntegerType>(Range.getBegin()->getType());
1409 SCEVExpander Expander(SE,
F.getParent()->getDataLayout(),
"irce");
1410 Instruction *InsertPt = OriginalPreheader->getTerminator();
1415 ClonedLoop PreLoop, PostLoop;
1417 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1418 bool NeedsPostLoop =
1419 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1421 Value *ExitPreLoopAt =
nullptr;
1422 Value *ExitMainLoopAt =
nullptr;
1424 cast<SCEVConstant>(SE.
getConstant(IVTy, -1,
true ));
1427 const SCEV *ExitPreLoopAtSCEV =
nullptr;
1430 ExitPreLoopAtSCEV = *SR.LowLimit;
1433 ExitPreLoopAtSCEV = SE.
getAddExpr(*SR.HighLimit, MinusOneS);
1435 LLVM_DEBUG(
dbgs() <<
"irce: could not prove no-overflow when computing " 1436 <<
"preloop exit limit. HighLimit = " 1437 << *(*SR.HighLimit) <<
"\n");
1442 LLVM_DEBUG(
dbgs() <<
"irce: could not prove that it is safe to expand the" 1443 <<
" preloop exit limit " << *ExitPreLoopAtSCEV
1444 <<
" at block " << InsertPt->getParent()->getName()
1449 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1450 ExitPreLoopAt->
setName(
"exit.preloop.at");
1453 if (NeedsPostLoop) {
1454 const SCEV *ExitMainLoopAtSCEV =
nullptr;
1457 ExitMainLoopAtSCEV = *SR.HighLimit;
1460 ExitMainLoopAtSCEV = SE.
getAddExpr(*SR.LowLimit, MinusOneS);
1462 LLVM_DEBUG(
dbgs() <<
"irce: could not prove no-overflow when computing " 1463 <<
"mainloop exit limit. LowLimit = " 1464 << *(*SR.LowLimit) <<
"\n");
1469 LLVM_DEBUG(
dbgs() <<
"irce: could not prove that it is safe to expand the" 1470 <<
" main loop exit limit " << *ExitMainLoopAtSCEV
1471 <<
" at block " << InsertPt->getParent()->getName()
1476 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1477 ExitMainLoopAt->
setName(
"exit.mainloop.at");
1483 cloneLoop(PreLoop,
"preloop");
1485 cloneLoop(PostLoop,
"postloop");
1487 RewrittenRangeInfo PreLoopRRI;
1491 PreLoop.Structure.Header);
1494 createPreheader(MainLoopStructure, Preheader,
"mainloop");
1495 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1496 ExitPreLoopAt, MainLoopPreheader);
1497 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1502 RewrittenRangeInfo PostLoopRRI;
1504 if (NeedsPostLoop) {
1506 createPreheader(PostLoop.Structure, Preheader,
"postloop");
1507 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1508 ExitMainLoopAt, PostLoopPreheader);
1509 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1514 MainLoopPreheader != Preheader ? MainLoopPreheader :
nullptr;
1515 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1516 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1517 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1532 Loop *PreL =
nullptr, *PostL =
nullptr;
1533 if (!PreLoop.Blocks.empty()) {
1534 PreL = createClonedLoopStructure(&OriginalLoop,
1535 OriginalLoop.getParentLoop(), PreLoop.Map,
1539 if (!PostLoop.Blocks.empty()) {
1541 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
1542 PostLoop.Map,
false);
1546 auto CanonicalizeLoop = [&] (
Loop *L,
bool IsOriginalLoop) {
1548 simplifyLoop(L, &DT, &LI, &SE,
nullptr,
nullptr,
true);
1551 if (!IsOriginalLoop)
1555 CanonicalizeLoop(PreL,
false);
1557 CanonicalizeLoop(PostL,
false);
1558 CanonicalizeLoop(&OriginalLoop,
true);
1567 InductiveRangeCheck::computeSafeIterationSpace(
1569 bool IsLatchSigned)
const {
1572 auto *IVType = cast<IntegerType>(IndVar->
getType());
1573 auto *RCType = cast<IntegerType>(getBegin()->getType());
1574 if (IVType->getBitWidth() > RCType->getBitWidth())
1604 assert(!B->isZero() &&
"Recurrence with zero step?");
1606 const SCEV *
C = getBegin();
1607 const SCEVConstant *
D =
dyn_cast<SCEVConstant>(getStep());
1612 unsigned BitWidth = RCType->getBitWidth();
1627 auto ClampedSubtract = [&](
const SCEV *
X,
const SCEV *
Y) {
1632 if (IsLatchSigned) {
1643 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
1644 return SE.getMinusSCEV(X, SE.getSMaxExpr(
Y, XMinusSIntMax),
1659 const SCEV *M = SE.getMinusSCEV(C, A);
1663 auto SCEVCheckNonNegative = [&](
const SCEV *
X) {
1673 const SCEV *NegOne = SE.getNegativeSCEV(One);
1674 return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
1684 const SCEV *REnd = getEnd();
1685 const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
1687 const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
1688 const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
1689 return InductiveRangeCheck::Range(Begin, End);
1695 const InductiveRangeCheck::Range &
R2) {
1696 if (R2.isEmpty(SE,
true))
1703 assert(!R1Value.isEmpty(SE,
true) &&
1704 "We should never have empty R1!");
1708 if (R1Value.getType() != R2.getType())
1711 const SCEV *NewBegin = SE.
getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1715 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1716 if (
Ret.isEmpty(SE,
true))
1724 const InductiveRangeCheck::Range &
R2) {
1725 if (R2.isEmpty(SE,
false))
1732 assert(!R1Value.isEmpty(SE,
false) &&
1733 "We should never have empty R1!");
1737 if (R1Value.getType() != R2.getType())
1740 const SCEV *NewBegin = SE.
getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1744 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1745 if (
Ret.isEmpty(SE,
false))
1757 InductiveRangeCheckElimination IRCE(AR.
SE, BPI, AR.
DT, AR.
LI);
1758 auto LPMAddNewLoop = [&U](
Loop *NL,
bool IsSubloop) {
1762 bool Changed = IRCE.run(&L, LPMAddNewLoop);
1773 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1775 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1776 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1777 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1778 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
1779 auto LPMAddNewLoop = [&LPM](
Loop *NL,
bool ) {
1782 return IRCE.run(L, LPMAddNewLoop);
1785 bool InductiveRangeCheckElimination::run(
1788 LLVM_DEBUG(
dbgs() <<
"irce: giving up constraining loop, too large\n");
1802 if (
BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1803 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1806 if (RangeChecks.
empty())
1809 auto PrintRecognizedRangeChecks = [&](
raw_ostream &OS) {
1810 OS <<
"irce: looking at loop "; L->
print(OS);
1811 OS <<
"irce: loop has " << RangeChecks.
size()
1812 <<
" inductive range checks: \n";
1813 for (InductiveRangeCheck &IRC : RangeChecks)
1820 PrintRecognizedRangeChecks(
errs());
1822 const char *FailureReason =
nullptr;
1824 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1825 if (!MaybeLoopStructure.
hasValue()) {
1827 << FailureReason <<
"\n";);
1830 LoopStructure LS = MaybeLoopStructure.
getValue();
1842 auto IntersectRange =
1846 for (InductiveRangeCheck &IRC : RangeChecks) {
1847 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1848 LS.IsSignedPredicate);
1849 if (Result.hasValue()) {
1850 auto MaybeSafeIterRange =
1851 IntersectRange(SE, SafeIterRange, Result.
getValue());
1852 if (MaybeSafeIterRange.hasValue()) {
1854 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1855 "We should never return empty ranges!");
1857 SafeIterRange = MaybeSafeIterRange.
getValue();
1865 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1867 bool Changed = LC.run();
1870 auto PrintConstrainedLoopInfo = [L]() {
1871 dbgs() <<
"irce: in function ";
1873 dbgs() <<
"constrained ";
1880 PrintConstrainedLoopInfo();
1884 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1885 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1888 IRC.getCheckUse()->set(FoldedRangeCheck);
1896 return new IRCELegacyPass();
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static cl::opt< bool > AllowNarrowLatchCondition("irce-allow-narrow-latch", cl::Hidden, cl::init(true), cl::desc("If set to true, IRCE may eliminate wide range checks in loops " "with narrow latch condition."))
Pass interface - Implemented by all 'passes'.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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. ...
const_iterator end(StringRef path)
Get end iterator over path.
static ConstantInt * getFalse(LLVMContext &Context)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static IntegerType * getInt1Ty(LLVMContext &C)
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDString * get(LLVMContext &Context, StringRef Str)
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
void push_back(const T &Elt)
bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
The main scalar evolution driver.
bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L. ...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static cl::opt< bool > AllowUnsignedLatchCondition("irce-allow-unsigned-latch", cl::Hidden, cl::init(true))
static Optional< InductiveRangeCheck::Range > IntersectSignedRange(ScalarEvolution &SE, const Optional< InductiveRangeCheck::Range > &R1, const InductiveRangeCheck::Range &R2)
bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
An efficient, type-erasing, non-owning reference to a callable.
const Use & getOperandUse(unsigned i) const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This defines the Use class.
static cl::opt< bool > PrintRangeChecks("irce-print-range-checks", cl::Hidden, cl::init(false))
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always negative in loop L.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
Value * CreateNot(Value *V, const Twine &Name="")
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
The SCEV is loop-invariant.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
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)
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce", "Inductive range check elimination", false, false) INITIALIZE_PASS_END(IRCELegacyPass
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...
void setName(const Twine &Name)
Change the name of the value.
static cl::opt< int > MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", cl::Hidden, cl::init(10))
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
Analysis pass which computes BranchProbabilityInfo.
ConstantInt * getValue() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS...
static void DisableAllLoopOptsOnLoop(Loop &L)
Type * getType() const
All values are typed, get the type of this value.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
This node represents a polynomial recurrence on the trip count of the specified loop.
static const char * ClonedLoopTag
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
const T & getValue() const LLVM_LVALUE_FUNCTION
Inductive range check elimination
This header provides classes for managing per-loop analyses.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Legacy analysis pass which computes BranchProbabilityInfo.
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
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. ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
Conditional or Unconditional Branch instruction.
static StringRef getPredicateName(Predicate P)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
const SCEV * getSMaxExpr(const SCEV *LHS, const SCEV *RHS)
Represent the analysis usage information of a pass.
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.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
const SCEV * getStart() const
Class to represent integer types.
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
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.
void addSiblingLoops(ArrayRef< Loop *> NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an increasing induction variable, is it possible to safely calculate the bounds of ...
const SCEV * getSMinExpr(const SCEV *LHS, const SCEV *RHS)
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static cl::opt< bool > SkipProfitabilityChecks("irce-skip-profitability-checks", cl::Hidden, cl::init(false))
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
Align max(MaybeAlign Lhs, Align Rhs)
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.
static const SCEV * NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE, bool Signed)
If the type of S matches with Ty, return S.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
static ConstantInt * getTrue(LLVMContext &Context)
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.
Class for arbitrary precision integers.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
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...
This class uses information about analyze scalars to rewrite expressions in canonical form...
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
LoopT * getParentLoop() const
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
Analysis providing branch probability information.
This class represents an analyzed expression in the program.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LLVM_NODISCARD bool empty() const
unsigned greater or equal
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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< unsigned > LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, cl::init(64))
bool isUnconditional() const
static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an deccreasing induction variable, is it possible to safely calculate the bounds of...
void initializeIRCELegacyPassPass(PassRegistry &)
static Optional< InductiveRangeCheck::Range > IntersectUnsignedRange(ScalarEvolution &SE, const Optional< InductiveRangeCheck::Range > &R1, const InductiveRangeCheck::Range &R2)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
static cl::opt< bool > PrintChangedLoops("irce-print-changed-loops", cl::Hidden, cl::init(false))
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
succ_range successors(Instruction *I)
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
This class implements an extremely fast bulk output stream that can only output to a stream...
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.
static BranchProbability getZero()
bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
iterator_range< block_iterator > blocks() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
Pass * createInductiveRangeCheckEliminationPass()
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
This class represents a constant integer value.