121 #define DEBUG_TYPE "irce" 135 class InductiveRangeCheck {
137 enum RangeCheckKind :
unsigned {
139 RANGE_CHECK_LOWER = 1,
142 RANGE_CHECK_UPPER = 2,
146 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
152 static StringRef rangeCheckKindToStr(RangeCheckKind);
154 const SCEV *Begin =
nullptr;
155 const SCEV *Step =
nullptr;
156 const SCEV *End =
nullptr;
157 Use *CheckUse =
nullptr;
158 RangeCheckKind
Kind = RANGE_CHECK_UNKNOWN;
159 bool IsSigned =
true;
161 static RangeCheckKind parseRangeCheckICmp(
Loop *L,
ICmpInst *ICI,
163 Value *&Length,
bool &IsSigned);
171 const SCEV *getBegin()
const {
return Begin; }
172 const SCEV *getStep()
const {
return Step; }
173 const SCEV *getEnd()
const {
return End; }
174 bool isSigned()
const {
return IsSigned; }
177 OS <<
"InductiveRangeCheck:\n";
178 OS <<
" Kind: " << rangeCheckKindToStr(Kind) <<
"\n";
185 OS <<
"\n CheckUse: ";
186 getCheckUse()->getUser()->print(OS);
187 OS <<
" Operand: " << getCheckUse()->getOperandNo() <<
"\n";
195 Use *getCheckUse()
const {
return CheckUse; }
205 Range(
const SCEV *Begin,
const SCEV *End) : Begin(Begin), End(End) {
210 const SCEV *getBegin()
const {
return Begin; }
211 const SCEV *getEnd()
const {
return End; }
224 bool getPassingDirection() {
return true; }
231 bool IsLatchSigned)
const;
244 class InductiveRangeCheckElimination {
254 : SE(SE), BPI(BPI), DT(DT), LI(LI) {}
259 class IRCELegacyPass :
public LoopPass {
280 "Inductive range check elimination",
false,
false)
286 StringRef InductiveRangeCheck::rangeCheckKindToStr(
287 InductiveRangeCheck::RangeCheckKind RCK) {
289 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
290 return "RANGE_CHECK_UNKNOWN";
292 case InductiveRangeCheck::RANGE_CHECK_UPPER:
293 return "RANGE_CHECK_UPPER";
295 case InductiveRangeCheck::RANGE_CHECK_LOWER:
296 return "RANGE_CHECK_LOWER";
298 case InductiveRangeCheck::RANGE_CHECK_BOTH:
299 return "RANGE_CHECK_BOTH";
311 InductiveRangeCheck::RangeCheckKind
312 InductiveRangeCheck::parseRangeCheckICmp(
Loop *L,
ICmpInst *ICI,
314 Value *&Length,
bool &IsSigned) {
315 auto IsLoopInvariant = [&SE, L](
Value *V) {
325 return RANGE_CHECK_UNKNOWN;
332 if (
match(RHS, m_ConstantInt<0>())) {
334 return RANGE_CHECK_LOWER;
336 return RANGE_CHECK_UNKNOWN;
343 if (
match(RHS, m_ConstantInt<-1>())) {
345 return RANGE_CHECK_LOWER;
348 if (IsLoopInvariant(LHS)) {
351 return RANGE_CHECK_UPPER;
353 return RANGE_CHECK_UNKNOWN;
360 if (IsLoopInvariant(LHS)) {
363 return RANGE_CHECK_BOTH;
365 return RANGE_CHECK_UNKNOWN;
371 void InductiveRangeCheck::extractRangeChecksFromCond(
375 Value *Condition = ConditionUse.
get();
376 if (!Visited.
insert(Condition).second)
381 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
383 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
394 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
395 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
400 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->
isAffine();
405 const SCEV *End =
nullptr;
411 assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER &&
"invariant!");
415 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->
getBitWidth();
420 InductiveRangeCheck IRC;
422 IRC.Begin = IndexAddRec->getStart();
423 IRC.Step = IndexAddRec->getStepRecurrence(SE);
424 IRC.CheckUse = &ConditionUse;
426 IRC.IsSigned = IsSigned;
430 void InductiveRangeCheck::extractRangeChecksFromBranch(
443 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->
getOperandUse(0),
456 Context, {
MDString::get(Context,
"llvm.loop.unroll.disable")});
461 {
MDString::get(Context,
"llvm.loop.vectorize.enable"), FalseVal});
463 Context, {
MDString::get(Context,
"llvm.loop.licm_versioning.disable")});
466 {
MDString::get(Context,
"llvm.loop.distribute.enable"), FalseVal});
469 DisableLICMVersioning, DisableDistribution});
482 struct LoopStructure {
483 const char *Tag =
"";
503 Value *IndVarBase =
nullptr;
504 Value *IndVarStart =
nullptr;
505 Value *IndVarStep =
nullptr;
506 Value *LoopExitAt =
nullptr;
507 bool IndVarIncreasing =
false;
508 bool IsSignedPredicate =
true;
510 LoopStructure() =
default;
512 template <
typename M> LoopStructure map(M Map)
const {
515 Result.Header = cast<BasicBlock>(Map(Header));
516 Result.Latch = cast<BasicBlock>(Map(Latch));
517 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
518 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
519 Result.LatchBrExitIdx = LatchBrExitIdx;
520 Result.IndVarBase = Map(IndVarBase);
521 Result.IndVarStart = Map(IndVarStart);
522 Result.IndVarStep = Map(IndVarStep);
523 Result.LoopExitAt = Map(LoopExitAt);
524 Result.IndVarIncreasing = IndVarIncreasing;
525 Result.IsSignedPredicate = IsSignedPredicate;
531 Loop &,
const char *&);
542 class LoopConstrainer {
546 std::vector<BasicBlock *> Blocks;
552 LoopStructure Structure;
557 struct RewrittenRangeInfo {
560 std::vector<PHINode *> PHIValuesAtPseudoExit;
563 RewrittenRangeInfo() =
default;
593 void cloneLoop(ClonedLoop &CLResult,
const char *Tag)
const;
597 Loop *createClonedLoopStructure(
Loop *Original,
Loop *Parent,
622 changeIterationSpaceEnd(
const LoopStructure &
LS,
BasicBlock *Preheader,
629 const char *Tag)
const;
635 void rewriteIncomingValuesForPHIs(
636 LoopStructure &LS,
BasicBlock *ContinuationBlockAndPreheader,
637 const LoopConstrainer::RewrittenRangeInfo &RRI)
const;
656 const SCEV *LatchTakenCount =
nullptr;
664 InductiveRangeCheck::Range Range;
668 LoopStructure MainLoopStructure;
676 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
677 Range(R), MainLoopStructure(LS) {}
706 const SCEV *BoundSCEV,
const SCEV *Step,
708 unsigned LatchBrExitIdx,
725 LLVM_DEBUG(
dbgs() <<
"irce: LatchExitBrIdx: " << LatchBrExitIdx <<
"\n");
733 if (LatchBrExitIdx == 1)
736 assert(LatchBrExitIdx == 0 &&
737 "LatchBrExitIdx should be either 0 or 1");
745 const SCEV *MinusOne =
756 const SCEV *BoundSCEV,
const SCEV *Step,
758 unsigned LatchBrExitIdx,
773 LLVM_DEBUG(
dbgs() <<
"irce: LatchExitBrIdx: " << LatchBrExitIdx <<
"\n");
781 if (LatchBrExitIdx == 1)
784 assert(LatchBrExitIdx == 0 &&
"LatchBrExitIdx should be 0 or 1");
786 const SCEV *StepMinusOne =
826 const char *&FailureReason) {
828 FailureReason =
"loop not in LoopSimplify form";
833 assert(Latch &&
"Simplified loops only have one latch!");
836 FailureReason =
"loop has already been cloned";
841 FailureReason =
"no loop latch";
848 FailureReason =
"no preheader";
854 FailureReason =
"latch terminator not conditional branch";
858 unsigned LatchBrExitIdx = LatchBr->
getSuccessor(0) == Header ? 1 : 0;
866 FailureReason =
"short running loop, not profitable";
872 FailureReason =
"latch terminator branch not conditional on integral icmp";
877 if (isa<SCEVCouldNotCompute>(LatchCount)) {
878 FailureReason =
"could not compute latch count";
891 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
892 if (isa<SCEVAddRecExpr>(RightSCEV)) {
897 FailureReason =
"no add recurrences in the icmp";
906 IntegerType *Ty = cast<IntegerType>(AR->getType());
914 const SCEV *ExtendedStep =
917 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
918 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
931 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
933 FailureReason =
"LHS in icmp not induction variable";
937 if (!isa<SCEVConstant>(StepRec)) {
938 FailureReason =
"LHS in icmp not induction variable";
941 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
943 if (ICI->
isEquality() && !HasNoSignedWrap(IndVarBase)) {
944 FailureReason =
"LHS in icmp needs nsw for equality predicates";
958 bool DecreasedRightValueByOne =
false;
959 if (StepCI->
isOne()) {
984 DecreasedRightValueByOne =
true;
989 DecreasedRightValueByOne =
true;
996 bool FoundExpectedPred =
997 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
999 if (!FoundExpectedPred) {
1000 FailureReason =
"expected icmp slt semantically, found something else";
1006 FailureReason =
"unsigned latch conditions are explicitly prohibited";
1011 LatchBrExitIdx, &L, SE)) {
1012 FailureReason =
"Unsafe loop bounds";
1015 if (LatchBrExitIdx == 0) {
1018 if (!DecreasedRightValueByOne) {
1020 RightValue =
B.CreateAdd(RightValue, One);
1023 assert(!DecreasedRightValueByOne &&
1024 "Right value can be decreased only for LatchBrExitIdx == 0!");
1027 bool IncreasedRightValueByOne =
false;
1048 IncreasedRightValueByOne =
true;
1052 IncreasedRightValueByOne =
true;
1060 bool FoundExpectedPred =
1061 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
1063 if (!FoundExpectedPred) {
1064 FailureReason =
"expected icmp sgt semantically, found something else";
1072 FailureReason =
"unsigned latch conditions are explicitly prohibited";
1077 LatchBrExitIdx, &L, SE)) {
1078 FailureReason =
"Unsafe bounds";
1082 if (LatchBrExitIdx == 0) {
1085 if (!IncreasedRightValueByOne) {
1087 RightValue =
B.CreateSub(RightValue, One);
1090 assert(!IncreasedRightValueByOne &&
1091 "Right value can be increased only for LatchBrExitIdx == 0!");
1098 "loop variant exit count doesn't make sense!");
1102 Value *IndVarStartV =
1105 IndVarStartV->
setName(
"indvar.start");
1109 Result.Tag =
"main";
1110 Result.Header = Header;
1111 Result.Latch = Latch;
1112 Result.LatchBr = LatchBr;
1113 Result.LatchExit = LatchExit;
1114 Result.LatchBrExitIdx = LatchBrExitIdx;
1115 Result.IndVarStart = IndVarStartV;
1116 Result.IndVarStep = StepCI;
1117 Result.IndVarBase = LeftValue;
1118 Result.IndVarIncreasing = IsIncreasing;
1119 Result.LoopExitAt = RightValue;
1120 Result.IsSignedPredicate = IsSignedPredicate;
1122 FailureReason =
nullptr;
1128 LoopConstrainer::calculateSubRanges(
bool IsSignedPredicate)
const {
1129 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1131 if (Range.getType() != Ty)
1134 LoopConstrainer::SubRanges
Result;
1139 const SCEV *Start = SE.
getSCEV(MainLoopStructure.IndVarStart);
1140 const SCEV *End = SE.
getSCEV(MainLoopStructure.LoopExitAt);
1142 bool Increasing = MainLoopStructure.IndVarIncreasing;
1148 const SCEV *Smallest =
nullptr, *Greatest =
nullptr, *GreatestSeen =
nullptr;
1174 GreatestSeen = Start;
1177 auto Clamp = [
this, Smallest, Greatest, IsSignedPredicate](
const SCEV *S) {
1178 return IsSignedPredicate
1189 bool ProvablyNoPreloop =
1191 if (!ProvablyNoPreloop)
1192 Result.LowLimit = Clamp(Range.getBegin());
1194 bool ProvablyNoPostLoop =
1196 if (!ProvablyNoPostLoop)
1197 Result.HighLimit = Clamp(Range.getEnd());
1202 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &
Result,
1203 const char *Tag)
const {
1204 for (
BasicBlock *BB : OriginalLoop.getBlocks()) {
1206 Result.Blocks.push_back(Clone);
1207 Result.Map[BB] = Clone;
1210 auto GetClonedValue = [&Result](
Value *V) {
1211 assert(V &&
"null values not in domain!");
1212 auto It = Result.Map.find(V);
1213 if (It == Result.Map.end())
1215 return static_cast<Value *
>(It->second);
1219 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1223 Result.Structure = MainLoopStructure.map(GetClonedValue);
1224 Result.Structure.Tag = Tag;
1226 for (
unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1228 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1230 assert(Result.Map[OriginalBB] == ClonedBB &&
"invariant!");
1241 if (OriginalLoop.contains(
SBB))
1246 PN.
addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1252 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
1326 RewrittenRangeInfo RRI;
1328 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
1330 &
F, BBInsertLocation);
1335 bool Increasing = LS.IndVarIncreasing;
1336 bool IsSignedPredicate = LS.IsSignedPredicate;
1341 Value *EnterLoopCond =
nullptr;
1343 EnterLoopCond = IsSignedPredicate
1347 EnterLoopCond = IsSignedPredicate
1351 B.
CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1354 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1356 Value *TakeBackedgeLoopCond =
nullptr;
1358 TakeBackedgeLoopCond = IsSignedPredicate
1362 TakeBackedgeLoopCond = IsSignedPredicate
1365 Value *CondForBranch = LS.LatchBrExitIdx == 1
1366 ? TakeBackedgeLoopCond
1369 LS.LatchBr->setCondition(CondForBranch);
1376 Value *IterationsLeft =
nullptr;
1378 IterationsLeft = IsSignedPredicate
1382 IterationsLeft = IsSignedPredicate
1385 B.
CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1393 for (
PHINode &PN : LS.Header->phis()) {
1395 BranchToContinuation);
1400 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1403 RRI.IndVarEnd =
PHINode::Create(LS.IndVarBase->getType(), 2,
"indvar.end",
1404 BranchToContinuation);
1405 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1406 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
1410 for (
PHINode &PN : LS.LatchExit->phis())
1411 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector);
1416 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1417 LoopStructure &LS,
BasicBlock *ContinuationBlock,
1418 const LoopConstrainer::RewrittenRangeInfo &RRI)
const {
1419 unsigned PHIIndex = 0;
1420 for (
PHINode &PN : LS.Header->phis())
1425 LS.IndVarStart = RRI.IndVarEnd;
1428 BasicBlock *LoopConstrainer::createPreheader(
const LoopStructure &LS,
1430 const char *Tag)
const {
1434 for (
PHINode &PN : LS.Header->phis())
1436 replacePHIBlock(&PN, OldPreheader, Preheader);
1450 Loop *LoopConstrainer::createClonedLoopStructure(
Loop *Original,
Loop *Parent,
1453 Loop &New = *LI.AllocateLoop();
1457 LI.addTopLevelLoop(&New);
1458 LPMAddNewLoop(&New, IsSubloop);
1461 for (
auto *BB : Original->
blocks())
1462 if (LI.getLoopFor(BB) == Original)
1466 for (
Loop *SubLoop : *Original)
1467 createClonedLoopStructure(SubLoop, &New, VM,
true);
1472 bool LoopConstrainer::run() {
1474 LatchTakenCount = SE.
getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1475 Preheader = OriginalLoop.getLoopPreheader();
1476 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader !=
nullptr &&
1479 OriginalPreheader = Preheader;
1480 MainLoopPreheader = Preheader;
1482 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1490 bool Increasing = MainLoopStructure.IndVarIncreasing;
1492 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
1494 SCEVExpander Expander(SE,
F.getParent()->getDataLayout(),
"irce");
1495 Instruction *InsertPt = OriginalPreheader->getTerminator();
1500 ClonedLoop PreLoop, PostLoop;
1502 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1503 bool NeedsPostLoop =
1504 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1506 Value *ExitPreLoopAt =
nullptr;
1507 Value *ExitMainLoopAt =
nullptr;
1509 cast<SCEVConstant>(SE.
getConstant(IVTy, -1,
true ));
1512 const SCEV *ExitPreLoopAtSCEV =
nullptr;
1515 ExitPreLoopAtSCEV = *SR.LowLimit;
1519 ExitPreLoopAtSCEV = SE.
getAddExpr(*SR.HighLimit, MinusOneS);
1521 LLVM_DEBUG(
dbgs() <<
"irce: could not prove no-overflow when computing " 1522 <<
"preloop exit limit. HighLimit = " 1523 << *(*SR.HighLimit) <<
"\n");
1529 LLVM_DEBUG(
dbgs() <<
"irce: could not prove that it is safe to expand the" 1530 <<
" preloop exit limit " << *ExitPreLoopAtSCEV
1531 <<
" at block " << InsertPt->getParent()->getName()
1536 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1537 ExitPreLoopAt->
setName(
"exit.preloop.at");
1540 if (NeedsPostLoop) {
1541 const SCEV *ExitMainLoopAtSCEV =
nullptr;
1544 ExitMainLoopAtSCEV = *SR.HighLimit;
1548 ExitMainLoopAtSCEV = SE.
getAddExpr(*SR.LowLimit, MinusOneS);
1550 LLVM_DEBUG(
dbgs() <<
"irce: could not prove no-overflow when computing " 1551 <<
"mainloop exit limit. LowLimit = " 1552 << *(*SR.LowLimit) <<
"\n");
1558 LLVM_DEBUG(
dbgs() <<
"irce: could not prove that it is safe to expand the" 1559 <<
" main loop exit limit " << *ExitMainLoopAtSCEV
1560 <<
" at block " << InsertPt->getParent()->getName()
1565 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1566 ExitMainLoopAt->
setName(
"exit.mainloop.at");
1572 cloneLoop(PreLoop,
"preloop");
1574 cloneLoop(PostLoop,
"postloop");
1576 RewrittenRangeInfo PreLoopRRI;
1580 PreLoop.Structure.Header);
1583 createPreheader(MainLoopStructure, Preheader,
"mainloop");
1584 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1585 ExitPreLoopAt, MainLoopPreheader);
1586 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1591 RewrittenRangeInfo PostLoopRRI;
1593 if (NeedsPostLoop) {
1595 createPreheader(PostLoop.Structure, Preheader,
"postloop");
1596 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1597 ExitMainLoopAt, PostLoopPreheader);
1598 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1603 MainLoopPreheader != Preheader ? MainLoopPreheader :
nullptr;
1604 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1605 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1606 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1621 Loop *PreL =
nullptr, *PostL =
nullptr;
1622 if (!PreLoop.Blocks.empty()) {
1623 PreL = createClonedLoopStructure(&OriginalLoop,
1624 OriginalLoop.getParentLoop(), PreLoop.Map,
1628 if (!PostLoop.Blocks.empty()) {
1630 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
1631 PostLoop.Map,
false);
1635 auto CanonicalizeLoop = [&] (
Loop *L,
bool IsOriginalLoop) {
1640 if (!IsOriginalLoop)
1644 CanonicalizeLoop(PreL,
false);
1646 CanonicalizeLoop(PostL,
false);
1647 CanonicalizeLoop(&OriginalLoop,
true);
1656 InductiveRangeCheck::computeSafeIterationSpace(
1658 bool IsLatchSigned)
const {
1688 const SCEV *
C = getBegin();
1709 auto ClampedSubtract = [&](
const SCEV *
X,
const SCEV *
Y) {
1714 if (IsLatchSigned) {
1745 auto SCEVCheckNonNegative = [&](
const SCEV *
X) {
1766 const SCEV *REnd = getEnd();
1767 const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
1769 const SCEV *Begin = SE.
getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
1770 const SCEV *End = SE.
getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
1771 return InductiveRangeCheck::Range(Begin, End);
1777 const InductiveRangeCheck::Range &
R2) {
1778 if (R2.isEmpty(SE,
true))
1785 assert(!R1Value.isEmpty(SE,
true) &&
1786 "We should never have empty R1!");
1790 if (R1Value.getType() != R2.getType())
1793 const SCEV *NewBegin = SE.
getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1797 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1798 if (
Ret.isEmpty(SE,
true))
1806 const InductiveRangeCheck::Range &
R2) {
1807 if (R2.isEmpty(SE,
false))
1814 assert(!R1Value.isEmpty(SE,
false) &&
1815 "We should never have empty R1!");
1819 if (R1Value.getType() != R2.getType())
1822 const SCEV *NewBegin = SE.
getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1826 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1827 if (
Ret.isEmpty(SE,
false))
1839 InductiveRangeCheckElimination IRCE(AR.
SE, BPI, AR.
DT, AR.
LI);
1840 auto LPMAddNewLoop = [&U](
Loop *NL,
bool IsSubloop) {
1844 bool Changed = IRCE.run(&L, LPMAddNewLoop);
1855 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1857 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1858 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1859 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1860 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
1861 auto LPMAddNewLoop = [&LPM](
Loop *NL,
bool ) {
1864 return IRCE.run(L, LPMAddNewLoop);
1867 bool InductiveRangeCheckElimination::run(
1870 LLVM_DEBUG(
dbgs() <<
"irce: giving up constraining loop, too large\n");
1884 if (
BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1885 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1888 if (RangeChecks.
empty())
1891 auto PrintRecognizedRangeChecks = [&](
raw_ostream &OS) {
1892 OS <<
"irce: looking at loop "; L->
print(OS);
1893 OS <<
"irce: loop has " << RangeChecks.
size()
1894 <<
" inductive range checks: \n";
1895 for (InductiveRangeCheck &IRC : RangeChecks)
1902 PrintRecognizedRangeChecks(
errs());
1904 const char *FailureReason =
nullptr;
1906 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1907 if (!MaybeLoopStructure.
hasValue()) {
1909 << FailureReason <<
"\n";);
1912 LoopStructure LS = MaybeLoopStructure.
getValue();
1924 auto IntersectRange =
1928 for (InductiveRangeCheck &IRC : RangeChecks) {
1929 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1930 LS.IsSignedPredicate);
1931 if (Result.hasValue()) {
1932 auto MaybeSafeIterRange =
1933 IntersectRange(SE, SafeIterRange, Result.
getValue());
1934 if (MaybeSafeIterRange.hasValue()) {
1936 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1937 "We should never return empty ranges!");
1939 SafeIterRange = MaybeSafeIterRange.
getValue();
1947 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1949 bool Changed = LC.run();
1952 auto PrintConstrainedLoopInfo = [L]() {
1953 dbgs() <<
"irce: in function ";
1955 dbgs() <<
"constrained ";
1962 PrintConstrainedLoopInfo();
1966 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1967 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1970 IRC.getCheckUse()->set(FoldedRangeCheck);
1978 return new IRCELegacyPass();
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
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.
void push_back(const T &Elt)
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.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool CannotBeMinInLoop(const SCEV *BoundSCEV, Loop *L, ScalarEvolution &SE, bool Signed)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static IntegerType * getInt1Ty(LLVMContext &C)
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...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
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)
Compute iterated dominance frontiers using a linear time algorithm.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
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.
The main scalar evolution driver.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
bool isZero() const
Return true if the expression is a constant zero.
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
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Value * getCondition() const
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.
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="")
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
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...
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
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...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setName(const Twine &Name)
Change the name of the value.
Value * CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name="")
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 bool CannotBeMaxInLoop(const SCEV *BoundSCEV, Loop *L, ScalarEvolution &SE, bool Signed)
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
Value * CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name="")
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)...
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
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)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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 bool isKnownNegativeInLoop(const SCEV *BoundSCEV, const Loop *L, ScalarEvolution &SE)
static wasm::ValType getType(const TargetRegisterClass *RC)
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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.
void setIncomingBlock(unsigned i, BasicBlock *BB)
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 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)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
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.
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.
static bool isSigned(Value *V)
Can the given value generate sign bits.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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.
succ_range successors(BasicBlock *BB)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
This class implements an extremely fast bulk output stream that can only output to a stream...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
StringRef - Represent a constant reference to a string, i.e.
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 SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock)
Get the expression for the number of loop iterations for which this loop is guaranteed not to exit vi...
static BranchProbability getZero()
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...
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
void setIncomingValue(unsigned i, Value *V)
static bool isKnownNonNegativeInLoop(const SCEV *BoundSCEV, const Loop *L, ScalarEvolution &SE)
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.