57#define DEBUG_TYPE "loop-interchange"
59STATISTIC(LoopsInterchanged,
"Number of loops interchanged");
73using CharMatrix = std::vector<std::vector<char>>;
85 if (!Set.insert(Rule).second)
94 for (
auto &Row : DepMatrix) {
107 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
108 "Expected Src and Dst to be different instructions in the same BB");
110 bool FoundSrc =
false;
125 CharMatrix &DepMatrix,
unsigned Level,
132 unsigned NumInsts = 0;
158 unsigned NumMemInstr = MemInstr.
size();
160 <<
" Loads and Stores to analyze\n");
161 if (
static_cast<uint64_t>(Opts.loop_interchange_max_mem_instr_ratio) *
163 static_cast<uint64_t>(NumMemInstr) * NumMemInstr) {
166 L->getStartLoc(), L->getHeader())
167 <<
"Number of loads/stores exceeded, the supported maximum can be "
168 "increased with option -loop-interchange-max-mem-instr-ratio.";
178 for (
I = MemInstr.
begin(), IE = MemInstr.
end();
I != IE; ++
I) {
179 for (J =
I, JE = MemInstr.
end(); J != JE; ++J) {
180 std::vector<char> Dep;
187 if (
auto D = DI->
depends(Src, Dst)) {
188 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
191 if (
D->normalize(SE))
194 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
195 dbgs() <<
"Found " << DepType
196 <<
" dependency between Src and Dst\n"
197 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
198 unsigned Levels =
D->getLevels();
200 for (
unsigned II = 1;
II <= Levels; ++
II) {
207 unsigned Dir =
D->getDirection(
II);
221 if (
D->isConfused()) {
222 assert(Dep.empty() &&
"Expected empty dependency vector");
223 Dep.assign(L->getLoopDepth() + Level - 1,
'*');
226 while (Dep.size() < L->getLoopDepth() + Level - 1) {
233 if (Dep.size() > Level)
234 Dep.erase(Dep.begin(), Dep.end() - Level);
241 L->getStartLoc(), L->getHeader())
242 <<
"All loops have dependencies in all directions.";
248 bool IsKnownForward =
true;
249 if (Src->getParent() != Dst->getParent()) {
253 IsKnownForward =
false;
259 "Unexpected instructions");
264 bool IsReversed =
D->getSrc() != Src;
266 IsKnownForward =
false;
282 DepMatrix.push_back(Dep);
289 DepMatrix[Ite->second].back() =
'*';
301 for (
auto &Row : DepMatrix)
310static std::optional<bool>
323 unsigned InnerLoopId,
324 unsigned OuterLoopId) {
325 unsigned NumRows = DepMatrix.size();
326 std::vector<char> Cur;
328 for (
unsigned Row = 0; Row < NumRows; ++Row) {
331 Cur = DepMatrix[Row];
344 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
353 << L.getHeader()->getParent()->getName() <<
" Loop: %"
354 << L.getHeader()->getName() <<
'\n');
355 assert(LoopList.
empty() &&
"LoopList should initially be empty!");
356 Loop *CurrentLoop = &L;
357 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
358 while (!Vec->empty()) {
362 if (Vec->size() != 1) {
368 CurrentLoop = Vec->front();
377 unsigned LoopNestDepth = LoopList.
size();
378 if (LoopNestDepth < Opts.loop_interchange_min_loop_nest_depth ||
379 LoopNestDepth > Opts.loop_interchange_max_loop_nest_depth) {
380 LLVM_DEBUG(
dbgs() <<
"Unsupported depth of loop nest " << LoopNestDepth
381 <<
", the supported range is ["
382 << Opts.loop_interchange_min_loop_nest_depth <<
", "
383 << Opts.loop_interchange_max_loop_nest_depth <<
"].\n");
389 <<
"Unsupported depth of loop nest, the supported range is ["
390 << std::to_string(Opts.loop_interchange_min_loop_nest_depth)
392 << std::to_string(Opts.loop_interchange_max_loop_nest_depth)
402 for (
Loop *L : LoopList) {
408 if (L->getNumBackEdges() != 1) {
412 if (!L->getExitingBlock()) {
423class LoopInterchangeLegality {
425 LoopInterchangeLegality(
const ScalarOptions &Opts,
Loop *Outer,
Loop *Inner,
426 ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,
428 : Opts(Opts), OuterLoop(
Outer), InnerLoop(Inner), SE(SE), DT(DT),
432 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
433 CharMatrix &DepMatrix);
437 bool isLoopStructureUnderstood();
439 bool currentLimitations();
441 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions()
const {
442 return OuterInnerReductions;
446 return InnerLoopInductions;
449 ArrayRef<Instruction *> getHasNoWrapReductions()
const {
450 return HasNoWrapReductions;
453 ArrayRef<Instruction *> getHasNoInfInsts()
const {
return HasNoInfInsts; }
459 struct InnerReduction {
467 StoreInst *LcssaStore;
474 return InnerReductions;
478 bool tightlyNested(
Loop *Outer,
Loop *Inner);
479 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
491 bool checkInductionsAndReductions(
Loop *OuterLoop);
503 bool isInnerReduction(
Loop *L, PHINode *Phi,
504 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
506 const ScalarOptions &Opts;
514 OptimizationRemarkEmitter *ORE;
518 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
526 SmallVector<Instruction *, 4> HasNoWrapReductions;
530 SmallVector<Instruction *, 4> HasNoInfInsts;
539class CacheCostManager {
541 LoopStandardAnalysisResults *AR;
546 std::optional<std::unique_ptr<CacheCost>> CC;
550 DenseMap<const Loop *, unsigned> CostMap;
552 void computeIfUnitinialized();
555 CacheCostManager(
Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
557 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
558 CacheCost *getCacheCost();
559 const DenseMap<const Loop *, unsigned> &getCostMap();
564class LoopInterchangeProfitability {
566 LoopInterchangeProfitability(
const ScalarOptions &Opts,
Loop *Outer,
567 Loop *Inner, ScalarEvolution *SE,
568 OptimizationRemarkEmitter *ORE)
569 : Opts(Opts), OuterLoop(
Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
573 unsigned InnerLoopId,
unsigned OuterLoopId,
574 CharMatrix &DepMatrix, CacheCostManager &CCM);
577 int getInstrOrderCost();
578 std::optional<bool> isProfitablePerLoopCacheAnalysis(
579 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC);
580 std::optional<bool> isProfitablePerInstrOrderCost();
581 std::optional<bool> isProfitableForVectorization(
unsigned InnerLoopId,
582 unsigned OuterLoopId,
583 CharMatrix &DepMatrix);
584 const ScalarOptions &Opts;
592 OptimizationRemarkEmitter *ORE;
596class LoopInterchangeTransform {
598 LoopInterchangeTransform(
Loop *Outer,
Loop *Inner, ScalarEvolution *SE,
599 LoopInfo *LI, DominatorTree *DT,
600 const LoopInterchangeLegality &LIL)
601 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
604 void transform(ArrayRef<Instruction *> DropNoWrapInsts,
605 ArrayRef<Instruction *> DropNoInfInsts);
606 void reduction2Memory();
607 void restructureLoops(
Loop *NewInner,
Loop *NewOuter,
608 BasicBlock *OrigInnerPreHeader,
609 BasicBlock *OrigOuterPreHeader);
610 void removeChildLoop(
Loop *OuterLoop,
Loop *InnerLoop);
613 void adjustLoopBranches();
624 const LoopInterchangeLegality &LIL;
627struct LoopInterchange {
628 const ScalarOptions &Opts;
629 ScalarEvolution *SE =
nullptr;
630 LoopInfo *LI =
nullptr;
631 DependenceInfo *DI =
nullptr;
632 DominatorTree *DT =
nullptr;
633 LoopStandardAnalysisResults *AR =
nullptr;
636 OptimizationRemarkEmitter *ORE;
638 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
639 DominatorTree *DT, LoopStandardAnalysisResults *AR,
640 OptimizationRemarkEmitter *ORE)
641 : Opts(ScalarOptions::
Global), SE(SE), LI(LI), DI(DI), DT(DT), AR(AR),
645 if (
L->getParentLoop())
647 SmallVector<Loop *, 8> LoopList;
649 return processLoopList(LoopList);
669 collectPerfectNests(LoopNest &LN) {
672 if (!
L->isInnermost())
675 SmallVector<Loop *, 8> LoopList;
684 std::reverse(LoopList.
begin(), LoopList.
end());
685 if (LoopList.
size() >= 2)
686 LoopLists.
push_back(std::move(LoopList));
691 bool run(LoopNest &LN) {
693 if (LoopLists.
empty()) {
694 LLVM_DEBUG(
dbgs() <<
"No Valid candidates for loop interchange.\n");
698 for (SmallVector<Loop *, 8> &LoopList : LoopLists) {
704 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
707 Changed |= processLoopList(LoopList);
715 return LoopList.
size() - 1;
718 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
723 "Unsupported depth of loop nest.");
725 unsigned LoopNestDepth = LoopList.
size();
728 dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
729 <<
" containing the following loops:\n";
730 for (
auto *L : LoopList) {
736 CharMatrix DependencyMatrix;
737 Loop *OuterMostLoop = *(LoopList.begin());
739 OuterMostLoop, DI, SE, ORE)) {
751 <<
"' needs an unique exit block");
755 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
756 CacheCostManager CCM(LoopList[0], AR, DI);
761 for (
unsigned j = SelecLoopId;
j > 0;
j--) {
762 bool ChangedPerIter =
false;
763 for (
unsigned i = SelecLoopId; i > SelecLoopId -
j; i--) {
765 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
766 ChangedPerIter |= Interchanged;
777 bool processLoop(SmallVectorImpl<Loop *> &LoopList,
unsigned InnerLoopId,
778 unsigned OuterLoopId,
779 std::vector<std::vector<char>> &DependencyMatrix,
780 CacheCostManager &CCM) {
781 Loop *OuterLoop = LoopList[OuterLoopId];
782 Loop *InnerLoop = LoopList[InnerLoopId];
784 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
785 LoopInterchangeLegality LIL(Opts, OuterLoop, InnerLoop, SE, ORE, DT);
786 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
787 LLVM_DEBUG(
dbgs() <<
"Cannot prove legality, not interchanging loops '"
788 << OuterLoop->
getName() <<
"' and '"
789 << InnerLoop->
getName() <<
"'\n");
794 <<
"' are legal to interchange\n");
795 LoopInterchangeProfitability LIP(Opts, OuterLoop, InnerLoop, SE, ORE);
796 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
797 DependencyMatrix, CCM)) {
799 <<
"' and '" << InnerLoop->
getName()
800 <<
"' not profitable.\n");
805 return OptimizationRemark(
DEBUG_TYPE,
"Interchanged",
808 <<
"Loop interchanged with enclosing loop.";
811 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
812 LIT.transform(LIL.getHasNoWrapReductions(), LIL.getHasNoInfInsts());
814 << OuterLoop->
getName() <<
"' and inner loop '"
815 << InnerLoop->
getName() <<
"'\n");
821 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
834bool LoopInterchangeLegality::containsUnsafeInstructions(
BasicBlock *BB,
836 return any_of(*BB, [Skip](
const Instruction &
I) {
839 return I.mayHaveSideEffects() ||
I.mayReadFromMemory();
868 auto IsDirectInnerLoopBlock = [InnerLoop](
BasicBlock *BB) {
871 [BB](
Loop *SubLoop) { return SubLoop->contains(BB); });
877 Worklist.
insert(Condition);
879 for (
PHINode *Induction : InnerLoopInductions) {
881 Induction->getIncomingValueForBlock(InnerLoop->
getLoopLatch()));
882 if (Incoming && !
is_contained(InnerLoopInductions, Incoming))
883 Worklist.
insert(Incoming);
886 for (
unsigned I = 0;
I < Worklist.
size(); ++
I) {
892 if (!OperandI || !IsDirectInnerLoopBlock(OperandI->getParent()) ||
895 Worklist.
insert(OperandI);
901bool LoopInterchangeLegality::tightlyNested(
Loop *OuterLoop,
Loop *InnerLoop) {
907 <<
"' and '" << InnerLoop->
getName()
908 <<
"' are tightly nested\n");
928 for (BasicBlock *Succ :
successors(OuterLoopHeader))
929 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->
getHeader())
932 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
938 assert(InnerReductions.size() <= 1 &&
939 "So far we only support at most one reduction.");
940 if (InnerReductions.size() == 1)
941 Skip = InnerReductions[0].LcssaStore;
945 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
946 containsUnsafeInstructions(OuterLoopLatch, Skip))
952 if (InnerLoopPreHeader != OuterLoopHeader &&
953 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
961 if (&SuccInner != OuterLoopLatch) {
963 <<
" does not lead to the outer loop latch.\n";);
969 if (containsUnsafeInstructions(InnerLoopExit, Skip))
977bool LoopInterchangeLegality::isLoopStructureUnderstood() {
979 for (PHINode *InnerInduction : InnerLoopInductions) {
980 unsigned Num = InnerInduction->getNumOperands();
981 for (
unsigned i = 0; i < Num; ++i) {
982 Value *Val = InnerInduction->getOperand(i);
992 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
993 InnerLoopPreheader &&
1007 CondBrInst *InnerLoopLatchBI =
1009 if (!InnerLoopLatchBI)
1028 std::function<bool(
Value *)> IsPathToInnerIndVar;
1029 IsPathToInnerIndVar = [
this, &IsPathToInnerIndVar](
const Value *
V) ->
bool {
1038 return IsPathToInnerIndVar(
I->getOperand(0));
1040 return IsPathToInnerIndVar(
I->getOperand(0)) &&
1041 IsPathToInnerIndVar(
I->getOperand(1));
1047 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
1055 }
else if (IsPathToInnerIndVar(Op1) && !
isa<Constant>(Op1)) {
1060 if (
Left ==
nullptr)
1077 if (
PHI->getNumIncomingValues() != 1)
1165 assert(
I->getOpcode() == OpCode &&
1166 "Expected the instruction to be the reduction operation");
1171 if (
I->hasNoSignedWrap() ||
I->hasNoUnsignedWrap())
1195 if (
PHI->getNumIncomingValues() == 1)
1208bool LoopInterchangeLegality::isInnerReduction(
1209 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1213 if (!
L->isInnermost()) {
1214 LLVM_DEBUG(
dbgs() <<
"Only supported when the loop is the innermost.\n");
1216 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1217 L->getStartLoc(),
L->getHeader())
1218 <<
"Only supported when the loop is the innermost.";
1223 if (
Phi->getNumIncomingValues() != 2)
1226 Value *Init =
Phi->getIncomingValueForBlock(
L->getLoopPreheader());
1227 Value *
Next =
Phi->getIncomingValueForBlock(
L->getLoopLatch());
1233 <<
"Only supported for the reduction with a constant initial value.\n");
1235 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1236 L->getStartLoc(),
L->getHeader())
1237 <<
"Only supported for the reduction with a constant initial "
1246 if (!
L->contains(BB))
1251 if (!
Phi->hasOneUser())
1263 PHINode *Lcssa = NULL;
1264 for (
auto *U :
Next->users()) {
1269 if (Lcssa == NULL &&
P->getParent() == ExitBlock &&
1270 P->getIncomingValueForBlock(
L->getLoopLatch()) ==
Next)
1281 LLVM_DEBUG(
dbgs() <<
"Only supported when the reduction is used once in "
1282 "the outer loop.\n");
1284 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1285 L->getStartLoc(),
L->getHeader())
1286 <<
"Only supported when the reduction is used once in the outer "
1292 StoreInst *LcssaStore =
1294 if (!LcssaStore || LcssaStore->
getParent() != ExitBlock)
1307 LLVM_DEBUG(
dbgs() <<
"Only supported when memory reference dominate "
1308 "the inner loop.\n");
1310 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1311 L->getStartLoc(),
L->getHeader())
1312 <<
"Only supported when memory reference dominate the inner "
1323 SR.LcssaPhi = Lcssa;
1324 SR.LcssaStore = LcssaStore;
1328 InnerReductions.push_back(SR);
1332bool LoopInterchangeLegality::checkInductionsAndReductions(
Loop *OuterLoop) {
1333 auto ChildLoop = [](
Loop *
L) {
1334 assert(
L->getSubLoops().size() <= 1 &&
1335 "Expect at most one child loop for now.");
1336 return L->getSubLoops().empty() ? nullptr :
L->getSubLoops().front();
1339 Loop *InnerLoop = ChildLoop(OuterLoop);
1340 for (
Loop *CurLoop = OuterLoop; CurLoop; CurLoop = ChildLoop(CurLoop)) {
1341 for (PHINode &
PHI : CurLoop->getHeader()->phis()) {
1342 InductionDescriptor
ID;
1344 if (CurLoop == InnerLoop) {
1345 const SCEV *Step =
ID.getStep();
1348 InnerLoopInductions.push_back(&
PHI);
1353 if (CurLoop == OuterLoop) {
1355 if (
PHI.getNumIncomingValues() != 2) {
1356 LLVM_DEBUG(
dbgs() <<
"Only PHI nodes in the outer loop header with 2 "
1357 "incoming values are supported.\n");
1365 InnerLoop, V, HasNoWrapReductions, HasNoInfInsts);
1385 [InnerRedPhi](User *U) { return U == InnerRedPhi; })) {
1388 <<
"Failed to recognize PHI as an induction or reduction.\n");
1390 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIOuter",
1393 <<
"Only outer loops with induction or reduction PHI nodes "
1394 "can be interchanged currently.";
1399 OuterInnerReductions.insert(&
PHI);
1400 OuterInnerReductions.insert(InnerRedPhi);
1402 if (OuterInnerReductions.count(&
PHI)) {
1403 LLVM_DEBUG(
dbgs() <<
"Found a reduction across the outer loop.\n");
1404 }
else if (Opts.loop_interchange_reduction_to_mem &&
1405 isInnerReduction(CurLoop, &
PHI, HasNoWrapReductions)) {
1410 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIInner",
1411 CurLoop->getStartLoc(),
1412 CurLoop->getHeader())
1413 <<
"Only inner loops with induction or reduction PHI nodes "
1414 "can be interchanged currently.";
1422 if (InnerReductions.size() > 1) {
1425 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1426 CurLoop->getStartLoc(),
1427 CurLoop->getHeader())
1428 <<
"Only supports at most one reduction.";
1434 return !InnerLoopInductions.empty();
1439bool LoopInterchangeLegality::currentLimitations() {
1449 dbgs() <<
"Loops where the latch is not the exiting block are not"
1450 <<
" supported currently.\n");
1452 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ExitingNotLatch",
1455 <<
"Loops where the latch is not the exiting block cannot be"
1456 " interchange currently.";
1462 if (!isLoopStructureUnderstood()) {
1465 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedStructureInner",
1468 <<
"Inner loop structure not understood currently.";
1475 for (
Loop *L : {OuterLoop, InnerLoop}) {
1478 if (
L->contains(Pred))
1482 dbgs() <<
"Indirect branch found in the loop predecessor.\n");
1484 return OptimizationRemarkMissed(
DEBUG_TYPE,
"IndirectBranchPreheader",
1485 L->getStartLoc(),
L->getHeader())
1486 <<
"Indirect branch found in the loop predecessor.";
1495 SmallPtrSet<BasicBlock *, 2> InnerLoopHeaderSuccs;
1497 if (!InnerLoopHeaderSuccs.
insert(Succ).second)
1520 if (
PHI.getNumIncomingValues() > 1)
1524 if (&
PHI == LcssaReduction)
1527 PHINode *PN = dyn_cast<PHINode>(U);
1530 if (Reductions.count(PN))
1532 BasicBlock *PB = PN->getParent();
1533 if (!OuterL->contains(PB))
1535 return PB != OuterL->getLoopLatch();
1552 for (
Value *Incoming :
PHI.incoming_values()) {
1593 for (
PHINode *InductionPHI : InductionPHIs) {
1595 InductionPHI->getIncomingValueForBlock(InnerLoopLatch)))
1597 Worklist.
insert(IncomingI);
1603 InductionPHIs.
end());
1604 for (
unsigned I = 0;
I < Worklist.
size(); ++
I) {
1616bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
1617 unsigned OuterLoopId,
1618 CharMatrix &DepMatrix) {
1620 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
1621 <<
" and OuterLoopId = " << OuterLoopId
1622 <<
" due to dependence\n");
1624 return OptimizationRemarkMissed(
DEBUG_TYPE,
"Dependence",
1627 <<
"Cannot interchange loops due to dependences.";
1632 for (
auto *BB : OuterLoop->
blocks())
1633 for (Instruction &
I : *BB) {
1640 if (!
I.mayHaveSideEffects() && !
I.mayReadFromMemory())
1645 <<
"Loops contain instructions that cannot be safely interchanged\n");
1647 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsafeInst",
1648 I.getDebugLoc(),
I.getParent())
1649 <<
"Cannot interchange loops due to instruction that is "
1650 "potentially unsafe to interchange.";
1656 if (!checkInductionsAndReductions(OuterLoop)) {
1657 LLVM_DEBUG(
dbgs() <<
"Failed to find inner loop inductions or found "
1658 "unsupported reductions.\n");
1663 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop latch.\n");
1665 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerLatchPHI",
1668 <<
"Cannot interchange loops because unsupported PHI nodes found "
1669 "in inner loop latch.";
1678 LLVM_DEBUG(
dbgs() <<
"Interchange would re-nest or duplicate freeze\n");
1680 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsafeInst",
1683 <<
"Cannot interchange loops because re-nesting or duplicating "
1684 "freeze may change its sampling behavior.";
1691 if (currentLimitations()) {
1692 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
1697 if (!tightlyNested(OuterLoop, InnerLoop)) {
1700 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotTightlyNested",
1703 <<
"Cannot interchange loops because they are not tightly "
1711 PHINode *LcssaReduction =
nullptr;
1712 assert(InnerReductions.size() <= 1 &&
1713 "So far we only support at most one reduction.");
1714 if (InnerReductions.size() == 1)
1715 LcssaReduction = InnerReductions[0].LcssaPhi;
1719 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop exit.\n");
1721 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1724 <<
"Found unsupported PHI node in loop exit.";
1730 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1732 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1735 <<
"Found unsupported PHI node in loop exit.";
1741 [](PHINode &
PHI) { return PHI.getNumIncomingValues() != 1; })) {
1742 LLVM_DEBUG(
dbgs() <<
"Only outer loop latch PHI nodes with one incoming "
1743 "value are supported.\n");
1745 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedLatchPHI",
1748 <<
"Only outer loop latch PHI nodes with one incoming value are "
1762 if (
any_of(
PHI.users(), [](
const User *U) { return !isa<PHINode>(U); })) {
1763 LLVM_DEBUG(
dbgs() <<
"Outer loop latch PHI has a non-PHI user.\n");
1765 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedLatchPHI",
1768 <<
"Cannot interchange loops because an outer loop latch PHI "
1769 "node has a non-PHI user.";
1777void CacheCostManager::computeIfUnitinialized() {
1792 for (
const auto &[Idx,
Cost] :
enumerate((*CC)->getLoopCosts()))
1796CacheCost *CacheCostManager::getCacheCost() {
1797 computeIfUnitinialized();
1801const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1802 computeIfUnitinialized();
1812static std::optional<const SCEV *>
1818 return std::nullopt;
1823 return std::nullopt;
1826 std::optional<const SCEV *> Coeff =
1828 if (!Coeff.has_value())
1829 return std::nullopt;
1832 assert(!*Coeff &&
"Found more than one addrec for the same loop");
1838int LoopInterchangeProfitability::getInstrOrderCost() {
1839 SmallPtrSet<const SCEV *, 4> GoodBasePtrs, BadBasePtrs;
1840 for (BasicBlock *BB : InnerLoop->
blocks()) {
1841 for (Instruction &Ins : *BB) {
1846 std::optional<const SCEV *> OuterCoeff =
1848 std::optional<const SCEV *> InnerCoeff =
1851 if (!OuterCoeff.has_value() || !*OuterCoeff || !InnerCoeff.has_value() ||
1861 const SCEV *OuterStep = SE->
getAbsExpr(*OuterCoeff,
false);
1862 const SCEV *InnerStep = SE->
getAbsExpr(*InnerCoeff,
false);
1882 GoodBasePtrs.
insert(BasePtr);
1884 BadBasePtrs.
insert(BasePtr);
1888 int GoodOrder = GoodBasePtrs.
size();
1889 int BadOrder = BadBasePtrs.
size();
1890 return GoodOrder - BadOrder;
1894LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1895 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC) {
1899 auto InnerLoopIt = CostMap.
find(InnerLoop);
1900 if (InnerLoopIt == CostMap.
end())
1901 return std::nullopt;
1902 auto OuterLoopIt = CostMap.
find(OuterLoop);
1903 if (OuterLoopIt == CostMap.
end())
1904 return std::nullopt;
1907 return std::nullopt;
1908 unsigned InnerIndex = InnerLoopIt->second;
1909 unsigned OuterIndex = OuterLoopIt->second;
1911 <<
", OuterIndex = " << OuterIndex <<
"\n");
1912 assert(InnerIndex != OuterIndex &&
"CostMap should assign unique "
1913 "numbers to each loop");
1914 return std::optional<bool>(InnerIndex < OuterIndex);
1918LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1922 int Cost = getInstrOrderCost();
1924 if (
Cost < 0 &&
Cost < Opts.loop_interchange_threshold)
1925 return std::optional<bool>(
true);
1927 return std::nullopt;
1932 for (
const auto &Dep : DepMatrix) {
1933 char Dir = Dep[LoopId];
1934 char DepType = Dep.back();
1935 assert((DepType ==
'<' || DepType ==
'*') &&
1936 "Unexpected element in dependency vector");
1939 if (Dir ==
'=' || Dir ==
'I')
1945 if (Dir ==
'<' && DepType ==
'<')
1954std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1955 unsigned InnerLoopId,
unsigned OuterLoopId, CharMatrix &DepMatrix) {
1971 return std::nullopt;
1974bool LoopInterchangeProfitability::isProfitable(
1975 const Loop *InnerLoop,
const Loop *OuterLoop,
unsigned InnerLoopId,
1976 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
1985 if (InnerBTC && InnerBTC->
isZero()) {
1986 LLVM_DEBUG(
dbgs() <<
"Inner loop back-edge isn't taken, rejecting "
1987 "single iteration loop\n");
1990 if (OuterBTC && OuterBTC->
isZero()) {
1991 LLVM_DEBUG(
dbgs() <<
"Outer loop back-edge isn't taken, rejecting "
1992 "single iteration loop\n");
1997 Opts.loop_interchange_profitabilities;
1998 if (Profitabilities.
empty())
2002 if (Profitabilities.
size() == 1 &&
2003 Profitabilities[0] == LoopInterchangeRule::Ignore)
2006 "Duplicate rules and option 'ignore' are not allowed");
2016 std::optional<bool> shouldInterchange;
2019 case LoopInterchangeRule::PerLoopCacheAnalysis: {
2020 CacheCost *CC = CCM.getCacheCost();
2021 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
2022 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
2025 case LoopInterchangeRule::PerInstrOrderCost:
2026 shouldInterchange = isProfitablePerInstrOrderCost();
2028 case LoopInterchangeRule::ForVectorization:
2030 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
2032 case LoopInterchangeRule::Ignore:
2039 if (shouldInterchange.has_value())
2043 if (!shouldInterchange.has_value()) {
2045 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
2048 <<
"Insufficient information to calculate the cost of loop for "
2052 }
else if (!shouldInterchange.value()) {
2054 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
2057 <<
"Interchanging loops is not considered to improve cache "
2058 "locality nor vectorization.";
2065void LoopInterchangeTransform::removeChildLoop(
Loop *OuterLoop,
2067 for (
Loop *L : *OuterLoop)
2068 if (L == InnerLoop) {
2069 OuterLoop->removeChildLoop(L);
2098void LoopInterchangeTransform::restructureLoops(
2099 Loop *NewInner,
Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
2100 BasicBlock *OrigOuterPreHeader) {
2101 Loop *OuterLoopParent = OuterLoop->getParentLoop();
2108 removeChildLoop(NewInner, NewOuter);
2117 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->
blocks());
2121 for (BasicBlock *BB : NewInner->
blocks())
2129 for (BasicBlock *BB : OrigInnerBBs) {
2134 if (BB == OuterHeader || BB == OuterLatch)
2172void LoopInterchangeTransform::reduction2Memory() {
2174 LIL.getInnerReductions();
2177 "So far we only support at most one reduction.");
2179 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
2185 PHINode *FirstIter =
2186 Builder.CreatePHI(Type::getInt1Ty(
Context), 2,
"first.iter");
2191 assert(FirstIter->
isComplete() &&
"The FirstIter PHI node is not complete.");
2196 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
2199 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem,
"new.var");
2210void LoopInterchangeTransform::transform(
2211 ArrayRef<Instruction *> DropNoWrapInsts,
2212 ArrayRef<Instruction *> DropNoInfInsts) {
2215 LIL.getInnerReductions();
2216 if (InnerReductions.
size() == 1)
2220 auto &InductionPHIs = LIL.getInnerLoopInductions();
2221 assert(!InductionPHIs.empty() &&
2222 "Expected at least one induction variable in the inner loop");
2224 SmallVector<Instruction *, 8> InnerIndexVarList;
2225 for (PHINode *CurInductionPHI : InductionPHIs) {
2227 CurInductionPHI->getIncomingValueForBlock(InnerLoop->
getLoopLatch()));
2229 "Incoming value from loop latch isn't an instruction");
2232 InnerIndexVarList.
push_back(IncomingValue);
2245 SmallSetVector<Instruction *, 4> WorkList;
2247 auto MoveInstructions = [&i, &WorkList,
this, &InductionPHIs, NewLatch]() {
2248 for (; i < WorkList.
size(); i++) {
2252 "MoveInstructions does not support PHI nodes");
2258 "Moving instructions with side-effects may change behavior of "
2269 for (
Value *
Op : WorkList[i]->operands()) {
2286 for (Instruction *InnerIndexVar : InnerIndexVarList)
2301 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2303 if (InnerLoopPreHeader != OuterLoopHeader) {
2307 "Expected equivalent incoming values in inner loop preheader");
2308 P.replaceAllUsesWith(
P.getIncomingValue(0));
2309 P.eraseFromParent();
2311 for (Instruction &
I :
2313 std::prev(InnerLoopPreHeader->
end()))))
2317 adjustLoopBranches();
2321 for (Instruction *
Reduction : DropNoWrapInsts) {
2325 for (Instruction *
I : DropNoInfInsts)
2326 I->setHasNoInfs(
false);
2345 I->removeFromParent();
2360 std::vector<DominatorTree::UpdateType> &DTUpdates,
2361 bool MustUpdateOnce =
true) {
2363 "BI must jump to OldBB exactly once.");
2365 for (
Use &
Op : Term->operands())
2372 DTUpdates.push_back(
2373 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2374 DTUpdates.push_back(
2375 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2394 assert(
P.getNumIncomingValues() == 1 &&
2395 "Only loops with a single exit are supported!");
2397 Value *IncomingValue =
P.getIncomingValueForBlock(InnerLatch);
2404 "Expected non-instruction incoming value to be loop invariant");
2405 P.replaceAllUsesWith(IncomingValue);
2406 P.eraseFromParent();
2417 if (!IncIInnerMost || (IncIInnerMost->getParent() != InnerLatch &&
2418 IncIInnerMost->
getParent() != InnerHeader))
2422 [OuterHeader, OuterExit, IncI, InnerHeader](
User *U) {
2423 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2424 IncI->getParent() == InnerHeader) ||
2425 cast<PHINode>(U)->getParent() == OuterExit;
2427 "Can only replace phis iff the uses are in the loop nest exit or "
2428 "the incoming value is defined in the inner header (it will "
2429 "dominate all loop blocks after interchanging)");
2430 P.replaceAllUsesWith(IncI);
2431 P.eraseFromParent();
2459 if (
P.getNumIncomingValues() != 1)
2473 if (Pred == OuterLatch)
2478 P.setIncomingValue(0, NewPhi);
2518 if (OuterLoopLatch == InnerLoopExit)
2525 assert(Phi->getNumIncomingValues() == 1 &&
"Single input phi expected");
2526 LLVM_DEBUG(
dbgs() <<
"Removing 1-input phi in non-exit block: " << *Phi
2528 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2529 Phi->eraseFromParent();
2533void LoopInterchangeTransform::adjustLoopBranches() {
2535 std::vector<DominatorTree::UpdateType> DTUpdates;
2537 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2540 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2541 InnerLoopPreHeader != InnerLoop->
getHeader() && OuterLoopPreHeader &&
2542 InnerLoopPreHeader &&
"Guaranteed by loop-simplify form");
2552 OuterLoopPreHeader =
2554 if (InnerLoopPreHeader == OuterLoop->getHeader())
2555 InnerLoopPreHeader =
2560 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2562 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2569 CondBrInst *OuterLoopLatchBI =
2571 CondBrInst *InnerLoopLatchBI =
2576 assert(OuterLoopPredecessor && InnerLoopLatchPredecessor &&
2577 "Failed to find a unique predecessor");
2578 assert(OuterLoopLatchBI && InnerLoopLatchBI &&
2579 "Failed to find a conditional branch");
2586 assert(InnerLoopHeaderSuccessor &&
2587 "Failed to find a unique successor for the inner loop header");
2594 InnerLoopPreHeader, DTUpdates,
false);
2604 InnerLoopHeaderSuccessor, DTUpdates,
2612 OuterLoopPreHeader, DTUpdates);
2615 if (InnerLoopLatchBI->
getSuccessor(0) == InnerLoopHeader)
2616 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(1);
2618 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(0);
2621 InnerLoopLatchSuccessor, DTUpdates);
2623 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
2624 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
2626 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
2629 OuterLoopLatchSuccessor, DTUpdates);
2630 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2634 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2635 OuterLoopPreHeader);
2637 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2638 OuterLoopHeader, OuterLoopLatch, InnerLoop->
getExitBlock(),
2644 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2647 for (PHINode &
PHI : InnerLoopHeader->
phis())
2648 if (OuterInnerReductions.contains(&
PHI))
2651 for (PHINode &
PHI : OuterLoopHeader->
phis())
2652 if (OuterInnerReductions.contains(&
PHI))
2658 for (PHINode *
PHI : OuterLoopPHIs) {
2661 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2663 for (PHINode *
PHI : InnerLoopPHIs) {
2666 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2685 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2686 for (Instruction &
I :
2692 "LoopInterchange handed dominance-broken IR to LCSSA rebuild");
2710 <<
"Computed dependence info, invoking the transform.";
2714 if (!LoopInterchange(&AR.
SE, &AR.
LI, &DI, &AR.
DT, &AR, &ORE).run(LN))
2716 U.markLoopNestChanged(
true);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file defines the interface for the loop cache analysis.
SmallVector< Loop *, 4 > LoopVector
Loop::LoopBounds::Direction Direction
constexpr LoopInterchangeRule DefaultProfitabilities[]
static FreezeInst * findFreezeInInnerLatchCloneSet(Loop *InnerLoop, ArrayRef< PHINode * > InnerLoopInductions)
static void updateSuccessor(Instruction *Term, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
static bool areInnerLoopLatchPHIsSupported(Loop *InnerLoop, ArrayRef< PHINode * > InductionPHIs)
The transform partially clones the inner loop's latch block, but PHI nodes cannot be cloned this way.
static bool isComputableLoopNest(ScalarEvolution *SE, ArrayRef< Loop * > LoopList)
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static FreezeInst * findFreezeInReNestedBlocks(Loop *OuterLoop, Loop *InnerLoop)
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop)
This deals with a corner case when a LCSSA phi node appears in a non-exit block: the outer loop latch...
static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, unsigned ToIndx)
static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, BasicBlock *InnerLatch, BasicBlock *OuterHeader, BasicBlock *OuterLatch, BasicBlock *OuterExit, Loop *InnerLoop, LoopInfo *LI)
static bool populateDependencyMatrix(const ScalarOptions &Opts, CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static bool hasSupportedLoopDepth(const ScalarOptions &Opts, ArrayRef< Loop * > LoopList, OptimizationRemarkEmitter &ORE)
static void printDepMatrix(CharMatrix &DepMatrix)
static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2)
Swap instructions between BB1 and BB2 but keep terminators intact.
static PHINode * findInnerReductionPhi(Loop *L, Value *V, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static bool areInnerLoopExitPHIsSupported(Loop *OuterL, Loop *InnerL, SmallPtrSetImpl< PHINode * > &Reductions, PHINode *LcssaReduction)
We currently only support LCSSA PHI nodes in the inner loop exit if their users are either of the fol...
static bool inThisOrder(const Instruction *Src, const Instruction *Dst)
Return true if Src appears before Dst in the same basic block.
static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId)
Return true if we can vectorize the loop specified by LoopId.
static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId, unsigned OuterLoopId)
static bool noDuplicateRulesAndIgnore(ArrayRef< LoopInterchangeRule > Rules)
static Value * followLCSSA(Value *SV)
static void populateWorklist(Loop &L, LoopVector &LoopList)
static std::optional< bool > isLexicographicallyPositive(ArrayRef< char > DV, unsigned Begin, unsigned End)
static bool checkReductionKind(Loop *L, PHINode *PHI, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static std::optional< const SCEV * > getAddRecCoefficient(ScalarEvolution &SE, const SCEV *S, const Loop *L)
If \S contains an affine addrec for L, return the step recurrence of it.
This file defines the interface for the loop nest analysis.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
loop Loop Strength Reduction
uint64_t IntrinsicInst * II
static bool processLoop(Loop &L, const AArch64Subtarget &ST, DataLayout DL)
SmallVector< Value *, 8 > ValueVector
This file defines the SmallSet class.
This file defines the SmallVector class.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
static LLVM_ABI std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
CacheCostTy getLoopCost(const Loop &L) const
Return the estimated cost of loop L if the given loop is part of the loop nest associated with this o...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
static LLVM_ABI bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
void replaceLoop(LoopT *Old, LoopT *New)
Replace a loop among its siblings (a parent loop's child list or the top-level list) with a new loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
This class represents a loop nest and can be used to query its properties.
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Represents a single loop in the control flow graph.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
StringRef getName() const
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
op_range incoming_values()
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
static unsigned getIncomingValueNumForOperand(unsigned i)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
unsigned getOpcode() const
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
RecurKind getRecurrenceKind() const
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Represent a constant reference to a string, i.e.
constexpr size_t size() const
Get the string size.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
@ End
Run the machine verifier once, at the end of the pipeline.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...