56 #define DEBUG_TYPE "simple-loop-unswitch" 60 STATISTIC(NumBranches,
"Number of branches unswitched");
61 STATISTIC(NumSwitches,
"Number of switches unswitched");
62 STATISTIC(NumTrivial,
"Number of unswitches that are trivial");
66 cl::desc(
"Forcibly enables non-trivial loop unswitching rather than " 67 "following the configuration passed into the pass."));
71 cl::desc(
"The cost threshold for unswitching a loop."));
84 "Only need to walk the graph if root itself is not invariant.");
96 if (isa<Constant>(OpV))
101 Invariants.push_back(OpV);
111 if (Visited.
insert(OpI).second)
114 }
while (!Worklist.
empty());
121 assert(!isa<Constant>(Invariant) &&
"Why are we unswitching on a constant?");
124 for (
auto UI = Invariant->
use_begin(), UE = Invariant->
use_end(); UI != UE;) {
131 U->set(&Replacement);
162 for (
Value *Invariant :
165 Cond = IRB.
CreateOr(Cond, Invariant);
169 IRB.
CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
170 Direction ? &NormalSucc : &UnswitchedSucc);
187 for (
auto i : seq<int>(0, PN.getNumOperands())) {
188 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
189 "Found incoming block different from unique predecessor!");
190 PN.setIncomingBlock(i, &OldPH);
207 assert(&ExitBB != &UnswitchedBB &&
208 "Must have different loop exit and unswitched blocks!");
212 PN.getName() +
".split", InsertPt);
223 for (
int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
224 if (PN.getIncomingBlock(i) != &OldExitingBB)
227 Value *Incoming = PN.getIncomingValue(i);
230 PN.removeIncomingValue(i);
232 NewPN->addIncoming(Incoming, &OldPH);
238 NewPN->addIncoming(&PN, &ExitBB);
256 Loop *NewParentL =
nullptr;
257 for (
auto *ExitBB : Exits)
259 if (!NewParentL || NewParentL->
contains(ExitL))
262 if (NewParentL == OldParentL)
268 "Can only hoist this loop up the nest!");
273 "Parent loop of this loop should contain this loop's preheader!");
288 for (
Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
292 return BB == &Preheader || L.
contains(BB);
295 OldContainingL->getBlocksSet().erase(&Preheader);
297 OldContainingL->getBlocksSet().erase(BB);
302 formLCSSA(*OldContainingL, DT, &LI,
nullptr);
307 assert(OldContainingL->hasDedicatedExits() &&
308 "Unexpected predecessor of hoisted loop preheader!");
332 LLVM_DEBUG(
dbgs() <<
" Trying to unswitch branch: " << BI <<
"\n");
339 bool FullUnswitch =
false;
345 if (
auto *CondInst = dyn_cast<Instruction>(BI.
getCondition()))
347 if (Invariants.
empty())
353 bool ExitDirection =
true;
354 int LoopExitSuccIdx = 0;
357 ExitDirection =
false;
363 auto *ContinueBB = BI.
getSuccessor(1 - LoopExitSuccIdx);
375 if (cast<Instruction>(BI.
getCondition())->getOpcode() != Instruction::Or)
378 if (cast<Instruction>(BI.
getCondition())->getOpcode() != Instruction::And)
384 dbgs() <<
" unswitching trivial invariant conditions for: " << BI
386 for (
Value *Invariant : Invariants) {
387 dbgs() <<
" " << *Invariant <<
" == true";
388 if (Invariant != Invariants.back())
415 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
417 "A branch's parent isn't a predecessor!");
418 UnswitchedBB = LoopExitBB;
420 UnswitchedBB =
SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI);
445 "Must have an `or` of `i1`s for the condition!");
449 "Must have an `and` of `i1`s for the condition!");
451 *UnswitchedBB, *NewPH);
455 if (UnswitchedBB == LoopExitBB)
459 *ParentBB, *OldPH, FullUnswitch);
477 for (
Value *Invariant : Invariants)
518 LLVM_DEBUG(
dbgs() <<
" Trying to unswitch switch: " << SI <<
"\n");
528 for (
auto Case : SI.
cases()) {
529 auto *SuccBB = Case.getCaseSuccessor();
532 ExitCaseIndices.
push_back(Case.getCaseIndex());
539 else if (ExitCaseIndices.
empty())
554 if (!ExitL || ExitL->
contains(OuterL))
568 if (!ExitL || ExitL->
contains(OuterL))
571 ExitCases.
push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
589 return Case.getCaseSuccessor() ==
592 CommonSuccBB = SI.
case_begin()->getCaseSuccessor();
593 if (!DefaultExitBB) {
600 CommonSuccBB =
nullptr;
625 UnswitchedExitBBs.
insert(DefaultExitBB);
631 *DefaultExitBB, *SplitBB, *ParentBB, *OldPH,
true);
632 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
637 for (
auto &CasePair :
reverse(ExitCases)) {
645 if (UnswitchedExitBBs.insert(ExitBB).second)
652 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
657 *ExitBB, *SplitExitBB, *ParentBB, *OldPH,
true);
660 CasePair.second = SplitExitBB;
665 for (
auto CasePair :
reverse(ExitCases)) {
669 NewSI->addCase(CaseVal, UnswitchedBB);
675 NewSI->setDefaultDest(DefaultExitBB);
679 for (
auto Case : SI.
cases())
680 NewSI->addCase(Case.getCaseValue(), NewPH);
692 bool SkippedFirst = DefaultExitBB ==
nullptr;
693 for (
auto Case : SI.
cases()) {
694 assert(Case.getCaseSuccessor() == CommonSuccBB &&
695 "Non-common successor!");
707 }
else if (DefaultExitBB) {
709 "If we had no cases we'd have a common successor!");
714 auto LastCaseI = std::prev(SI.
case_end());
724 for (
auto *UnswitchedExitBB : UnswitchedExitBBs) {
728 for (
auto SplitUnswitchedPair : SplitExitBBMap) {
729 auto *UnswitchedBB = SplitUnswitchedPair.second;
759 bool Changed =
false;
774 Visited.
insert(CurrentBB);
785 if (
auto *
SI = dyn_cast<SwitchInst>(CurrentTerm)) {
789 if (isa<Constant>(
SI->getCondition()))
804 if (!BI || BI->isConditional())
807 CurrentBB = BI->getSuccessor(0);
819 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
833 if (BI->isConditional())
837 CurrentBB = BI->getSuccessor(0);
842 }
while (L.
contains(CurrentBB) && Visited.
insert(CurrentBB).second);
898 auto It = DominatingSucc.
find(BB);
899 return It != DominatingSucc.
end() && It->second != UnswitchedSuccBB;
903 auto *ClonedPH = CloneBlock(LoopPH);
906 for (
auto *LoopBB : L.
blocks())
907 if (!SkipBlock(LoopBB))
913 for (
auto *ExitBB : ExitBlocks) {
914 if (SkipBlock(ExitBB))
922 auto *MergeBB =
SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
928 ExitBB->setName(
Twine(MergeBB->getName()) +
".split");
931 auto *ClonedExitBB = CloneBlock(ExitBB);
932 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
933 "Exit block should have been split to have one successor!");
934 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
935 "Cloned exit block has the wrong successor!");
941 std::prev(ClonedExitBB->end())))) {
948 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
949 "Bad instruction in exit block!");
951 assert(VMap.
lookup(&I) == &ClonedI &&
"Mismatch in the value map!");
955 &*MergeBB->getFirstInsertionPt());
957 MergePN->addIncoming(&I, ExitBB);
958 MergePN->addIncoming(&ClonedI, ClonedExitBB);
967 for (
auto *ClonedBB : NewBlocks)
971 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
972 if (II->getIntrinsicID() == Intrinsic::assume)
978 for (
auto *LoopBB : L.
blocks())
979 if (SkipBlock(LoopBB))
981 if (
auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.
lookup(SuccBB)))
982 for (
PHINode &PN : ClonedSuccBB->phis())
983 PN.removeIncomingValue(LoopBB,
false);
987 auto *ClonedParentBB = cast<BasicBlock>(VMap.
lookup(ParentBB));
989 if (SuccBB == UnswitchedSuccBB)
992 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.
lookup(SuccBB));
996 ClonedSuccBB->removePredecessor(ClonedParentBB,
1002 auto *ClonedSuccBB = cast<BasicBlock>(VMap.
lookup(UnswitchedSuccBB));
1003 ClonedParentBB->getTerminator()->eraseFromParent();
1009 for (
PHINode &PN : ClonedSuccBB->phis()) {
1013 for (
int i = PN.getNumOperands() - 1; i >= 0; --i) {
1014 if (PN.getIncomingBlock(i) != ClonedParentBB)
1020 PN.removeIncomingValue(i,
false);
1026 for (
auto *ClonedBB : NewBlocks) {
1028 if (SuccSet.
insert(SuccBB).second)
1029 DTUpdates.
push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1044 auto AddClonedBlocksToLoop = [&](
Loop &OrigL,
Loop &ClonedL) {
1045 assert(ClonedL.getBlocks().empty() &&
"Must start with an empty loop!");
1047 for (
auto *BB : OrigL.
blocks()) {
1048 auto *ClonedBB = cast<BasicBlock>(VMap.
lookup(BB));
1049 ClonedL.addBlockEntry(ClonedBB);
1062 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1064 if (OrigRootL.
empty())
1074 LoopsToClone.
push_back({ClonedRootL, ChildL});
1076 Loop *ClonedParentL, *L;
1077 std::tie(ClonedParentL, L) = LoopsToClone.
pop_back_val();
1080 AddClonedBlocksToLoop(*L, *ClonedL);
1082 LoopsToClone.
push_back({ClonedL, ChildL});
1083 }
while (!LoopsToClone.
empty());
1104 Loop *ClonedL =
nullptr;
1109 auto *ClonedPH = cast<BasicBlock>(VMap.
lookup(OrigPH));
1110 auto *ClonedHeader = cast<BasicBlock>(VMap.
lookup(OrigHeader));
1116 Loop *ParentL =
nullptr;
1120 for (
auto *ExitBB : ExitBlocks)
1121 if (
auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.
lookup(ExitBB)))
1123 ExitLoopMap[ClonedExitBB] = ExitL;
1124 ClonedExitsInLoops.
push_back(ClonedExitBB);
1125 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1130 "The computed parent loop should always contain (or be) the parent of " 1131 "the original loop.");
1138 for (
auto *BB : OrigL.
blocks())
1139 if (
auto *ClonedBB = cast_or_null<BasicBlock>(VMap.
lookup(BB)))
1140 ClonedLoopBlocks.
insert(ClonedBB);
1151 if (Pred == ClonedPH)
1156 assert(ClonedLoopBlocks.count(Pred) &&
"Found a predecessor of the loop " 1157 "header other than the preheader " 1158 "that is not part of the loop!");
1163 if (BlocksInClonedLoop.
insert(Pred).second && Pred != ClonedHeader)
1170 if (!BlocksInClonedLoop.
empty()) {
1171 BlocksInClonedLoop.
insert(ClonedHeader);
1173 while (!Worklist.
empty()) {
1176 "Didn't put block into the loop set!");
1184 if (ClonedLoopBlocks.count(Pred) &&
1185 BlocksInClonedLoop.
insert(Pred).second)
1192 ParentL->addChildLoop(ClonedL);
1204 for (
auto *BB : OrigL.
blocks()) {
1205 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.
lookup(BB));
1206 if (!ClonedBB || !BlocksInClonedLoop.
count(ClonedBB))
1219 PL->addBlockEntry(ClonedBB);
1226 for (
Loop *ChildL : OrigL) {
1227 auto *ClonedChildHeader =
1228 cast_or_null<BasicBlock>(VMap.
lookup(ChildL->getHeader()));
1229 if (!ClonedChildHeader || !BlocksInClonedLoop.
count(ClonedChildHeader))
1235 for (
auto *ChildLoopBB : ChildL->blocks())
1237 cast<BasicBlock>(VMap.
lookup(ChildLoopBB))) &&
1238 "Child cloned loop has a header within the cloned outer " 1239 "loop but not all of its blocks!");
1254 if (BlocksInClonedLoop.
empty())
1255 UnloopedBlockSet.
insert(ClonedPH);
1256 for (
auto *ClonedBB : ClonedLoopBlocks)
1257 if (!BlocksInClonedLoop.
count(ClonedBB))
1258 UnloopedBlockSet.
insert(ClonedBB);
1264 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1265 llvm::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(),
1273 while (!UnloopedBlockSet.
empty() && !OrderedClonedExitsInLoops.empty()) {
1274 assert(Worklist.
empty() &&
"Didn't clear worklist!");
1276 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1291 if (!UnloopedBlockSet.
erase(PredBB)) {
1293 (BlocksInClonedLoop.
count(PredBB) || ExitLoopMap.
count(PredBB)) &&
1294 "Predecessor not mapped to a loop!");
1301 bool Inserted = ExitLoopMap.
insert({PredBB, ExitL}).
second;
1303 assert(Inserted &&
"Should only visit an unlooped block once!");
1308 }
while (!Worklist.
empty());
1317 for (
auto *BB : llvm::concat<BasicBlock *const>(
1318 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1320 OuterL->addBasicBlockToLoop(BB, LI);
1323 for (
auto &BBAndL : ExitLoopMap) {
1324 auto *BB = BBAndL.first;
1325 auto *OuterL = BBAndL.second;
1327 "Failed to put all blocks into outer loops!");
1334 for (
Loop *ChildL : OrigL) {
1335 auto *ClonedChildHeader =
1336 cast_or_null<BasicBlock>(VMap.
lookup(ChildL->getHeader()));
1337 if (!ClonedChildHeader || BlocksInClonedLoop.
count(ClonedChildHeader))
1341 for (
auto *ChildLoopBB : ChildL->blocks())
1343 "Cloned a child loop header but not all of that loops blocks!");
1347 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1353 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1357 for (
BasicBlock *BB : llvm::concat<BasicBlock *const>(L.
blocks(), ExitBlocks))
1358 for (
auto &VMap : VMaps)
1359 if (
BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1362 SuccBB->removePredecessor(ClonedBB);
1368 BB->dropAllReferences();
1371 BB->eraseFromParent();
1380 for (
BasicBlock *BB : llvm::concat<BasicBlock *const>(L.
blocks(), ExitBlocks))
1383 SuccBB->removePredecessor(BB);
1393 [&](
BasicBlock *BB) {
return DeadBlockSet.count(BB); });
1397 for (
auto *BB : DeadBlocks)
1398 ParentL->getBlocksSet().erase(BB);
1400 [&](
BasicBlock *BB) {
return DeadBlockSet.count(BB); });
1406 if (!DeadBlockSet.count(ChildL->getHeader()))
1411 return DeadBlockSet.count(ChildBB);
1413 "If the child loop header is dead all blocks in the child loop must " 1414 "be dead as well!");
1422 for (
auto *BB : DeadBlocks) {
1424 assert(!DT.
getNode(BB) &&
"Should already have cleared domtree!");
1431 for (
auto *BB : DeadBlocks)
1465 assert(L.
contains(Pred) &&
"Found a predecessor of the loop header other " 1466 "than the preheader that is not part of the " 1472 if (LoopBlockSet.
insert(Pred).second && Pred != Header)
1477 if (LoopBlockSet.
empty())
1478 return LoopBlockSet;
1481 while (!Worklist.
empty()) {
1483 assert(LoopBlockSet.
count(BB) &&
"Didn't put block into the loop set!");
1496 "Should not reach a loop *outside* this loop!");
1499 auto *InnerPH = InnerL->getLoopPreheader();
1500 assert(L.
contains(InnerPH) &&
"Cannot contain an inner loop block " 1501 "but not contain the inner loop " 1503 if (!LoopBlockSet.
insert(InnerPH).second)
1513 for (
auto *InnerBB : InnerL->blocks()) {
1514 if (InnerBB == BB) {
1516 "Block should already be in the set!");
1520 LoopBlockSet.
insert(InnerBB);
1536 assert(LoopBlockSet.
count(Header) &&
"Cannot fail to add the header!");
1540 return LoopBlockSet;
1564 Loop *ParentL =
nullptr;
1568 for (
auto *ExitBB : ExitBlocks)
1572 if (!ParentL || (ParentL != ExitL && ParentL->
contains(ExitL)))
1584 if (!LoopBlockSet.empty() && L.
getParentLoop() != ParentL) {
1588 IL->getBlocksSet().erase(PH);
1589 for (
auto *BB : L.
blocks())
1590 IL->getBlocksSet().erase(BB);
1607 LoopBlockSet.empty()
1609 : std::stable_partition(
1610 Blocks.begin(), Blocks.end(),
1611 [&](
BasicBlock *BB) {
return LoopBlockSet.count(BB); });
1615 if (LoopBlockSet.empty())
1616 UnloopedBlocks.
insert(PH);
1619 for (
auto *BB :
make_range(BlocksSplitI, Blocks.end()))
1621 Blocks.erase(BlocksSplitI, Blocks.end());
1625 std::stable_sort(ExitsInLoops.
begin(), ExitsInLoops.
end(),
1634 auto RemoveUnloopedBlocksFromLoop =
1636 for (
auto *BB : UnloopedBlocks)
1639 return UnloopedBlocks.count(BB);
1644 while (!UnloopedBlocks.empty() && !ExitsInLoops.
empty()) {
1645 assert(Worklist.
empty() &&
"Didn't clear worklist!");
1646 assert(NewExitLoopBlocks.empty() &&
"Didn't clear loop set!");
1651 assert(ExitL.
contains(&L) &&
"Exit loop must contain the inner loop!");
1657 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->
getParentLoop())
1658 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1672 if (!UnloopedBlocks.erase(PredBB)) {
1673 assert((NewExitLoopBlocks.count(PredBB) ||
1675 "Predecessor not in a nested loop (or already visited)!");
1682 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1684 assert(Inserted &&
"Should only visit an unlooped block once!");
1689 }
while (!Worklist.
empty());
1694 for (
auto *BB : NewExitLoopBlocks)
1701 NewExitLoopBlocks.clear();
1707 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1708 for (
auto *BB : UnloopedBlocks)
1717 auto SubLoopsSplitI =
1718 LoopBlockSet.empty()
1720 : std::stable_partition(
1721 SubLoops.begin(), SubLoops.end(), [&](
Loop *SubL) {
1722 return LoopBlockSet.count(SubL->getHeader());
1724 for (
auto *HoistedL :
make_range(SubLoopsSplitI, SubLoops.end())) {
1726 HoistedL->setParentLoop(
nullptr);
1736 if (
auto *NewParentL = LI.
getLoopFor(HoistedL->getLoopPreheader()))
1737 NewParentL->addChildLoop(HoistedL);
1741 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1744 if (Blocks.empty()) {
1745 assert(SubLoops.empty() &&
1746 "Failed to remove all subloops from the original loop!");
1761 template <
typename CallableT>
1779 "Cannot visit a node twice when walking a tree!");
1782 }
while (!DomWorklist.
empty());
1797 "Can only unswitch switches and conditional branch!");
1798 bool FullUnswitch = SI || BI->
getCondition() == Invariants[0];
1801 "Cannot have other invariants with full unswitching!");
1804 "Partial unswitching requires an instruction as the condition!");
1812 bool Direction =
true;
1814 if (!FullUnswitch) {
1815 if (cast<Instruction>(BI->
getCondition())->getOpcode() != Instruction::Or) {
1818 "Only `or` and `and` instructions can combine invariants being " 1826 BI ? BI->
getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1831 for (
auto Case : SI->cases())
1832 if (Case.getCaseSuccessor() != RetainedSuccBB)
1833 UnswitchedSuccBBs.
insert(Case.getCaseSuccessor());
1835 assert(!UnswitchedSuccBBs.
count(RetainedSuccBB) &&
1836 "Should not unswitch the same successor we are retaining!");
1851 for (
auto *ExitBB : ExitBlocks)
1852 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1861 Loop *OuterExitL = &L;
1862 for (
auto *ExitBB : ExitBlocks) {
1864 if (!NewOuterExitL) {
1866 OuterExitL =
nullptr;
1869 if (NewOuterExitL != OuterExitL && NewOuterExitL->
contains(OuterExitL))
1870 OuterExitL = NewOuterExitL;
1889 for (
auto *SuccBB : llvm::concat<BasicBlock *const>(
1891 if (SuccBB->getUniquePredecessor() ||
1893 return PredBB == ParentBB || DT.
dominates(SuccBB, PredBB);
1896 DominatingSucc[BB] = SuccBB;
1915 for (
auto *SuccBB : UnswitchedSuccBBs) {
1918 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
1919 DominatingSucc, *VMaps.
back(), DTUpdates, AC, DT, LI);
1932 assert(UnswitchedSuccBBs.size() == 1 &&
1933 "Only one possible unswitched block for a branch!");
1935 UnswitchedSuccBB->removePredecessor(ParentBB,
1945 assert(SI->getDefaultDest() == RetainedSuccBB &&
1946 "Not retaining default successor!");
1947 for (
auto &Case : SI->cases())
1948 Case.getCaseSuccessor()->removePredecessor(
1961 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
1970 assert(SI &&
"Must either be a branch or switch!");
1973 SI->setDefaultDest(LoopPH);
1974 for (
auto &Case : SI->cases())
1975 if (Case.getCaseSuccessor() == RetainedSuccBB)
1976 Case.setSuccessor(LoopPH);
1978 Case.setSuccessor(ClonedPHs.
find(Case.getCaseSuccessor())->
second);
1984 DTUpdates.push_back(
1992 assert(BI &&
"Only branches have partial unswitching.");
1993 assert(UnswitchedSuccBBs.size() == 1 &&
1994 "Only one possible unswitched block for a branch!");
1999 *ClonedPH, *LoopPH);
2016 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2038 assert(UnswitchedSuccBBs.size() == 1 &&
2039 "Only one possible unswitched block for a branch!");
2047 for (
Value *Invariant : Invariants)
2048 for (
auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2059 U->set(ContinueReplacement);
2061 U->set(UnswitchedReplacement);
2077 auto UpdateLoop = [&](
Loop &UpdateL) {
2079 UpdateL.verifyLoop();
2080 for (
Loop *ChildL : UpdateL) {
2081 ChildL->verifyLoop();
2082 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2083 "Perturbed a child loop's LCSSA form!");
2103 for (
Loop *UpdatedL :
2104 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2105 UpdateLoop(*UpdatedL);
2106 if (!UpdatedL->getParentLoop())
2107 OuterExitL =
nullptr;
2112 OuterExitL =
nullptr;
2117 if (OuterExitL != &L)
2118 for (
Loop *OuterL = ParentL; OuterL != OuterExitL;
2120 UpdateLoop(*OuterL);
2132 for (
Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2133 if (UpdatedL->getParentLoop() == ParentL)
2135 UnswitchCB(IsStillLoop, SibLoops);
2154 if (BBCostIt == BBCostMap.
end())
2158 auto DTCostIt = DTCostMap.
find(&N);
2159 if (DTCostIt != DTCostMap.
end())
2160 return DTCostIt->second;
2164 int Cost = std::accumulate(
2170 assert(Inserted &&
"Should not insert a node while visiting children!");
2183 for (
auto *BB : L.
blocks()) {
2187 if (
auto *
SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2190 if (!isa<Constant>(
SI->getCondition()) &&
2197 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2198 BI->getSuccessor(0) == BI->getSuccessor(1))
2202 UnswitchCandidates.
push_back({BI, {BI->getCondition()}});
2206 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2207 if (CondI.
getOpcode() != Instruction::And &&
2213 if (Invariants.
empty())
2216 UnswitchCandidates.
push_back({BI, std::move(Invariants)});
2220 if (UnswitchCandidates.
empty())
2231 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2235 dbgs() <<
"Considering " << UnswitchCandidates.
size()
2236 <<
" non-trivial loop invariant conditions for unswitching.\n");
2253 for (
auto *BB : L.
blocks()) {
2255 for (
auto &
I : *BB) {
2256 if (EphValues.count(&
I))
2259 if (
I.getType()->isTokenTy() &&
I.isUsedOutsideOfBlock(BB))
2262 if (CS.isConvergent() || CS.cannotDuplicate())
2267 assert(Cost >= 0 &&
"Must not have negative costs!");
2269 assert(LoopCost >= 0 &&
"Must not have negative loop costs!");
2270 BBCostMap[BB] = Cost;
2291 auto ComputeUnswitchedCost = [&](
TerminatorInst &TI,
bool FullUnswitch) {
2295 int Cost = LoopCost;
2298 if (!Visited.
insert(SuccBB).second)
2305 if (!FullUnswitch) {
2306 auto &BI = cast<BranchInst>(TI);
2307 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2309 if (SuccBB == BI.getSuccessor(1))
2312 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2314 "Only `and` and `or` conditions can result in a partial " 2316 if (SuccBB == BI.getSuccessor(0))
2325 if (SuccBB->getUniquePredecessor() ||
2327 return PredBB == &BB || DT.
dominates(SuccBB, PredBB);
2331 "Non-duplicated cost should never exceed total loop cost!");
2339 "Cannot unswitch a condition without multiple distinct successors!");
2340 return Cost * (Visited.
size() - 1);
2343 int BestUnswitchCost;
2345 for (
auto &TerminatorAndInvariants : UnswitchCandidates) {
2349 int CandidateCost = ComputeUnswitchedCost(
2350 TI, !BI || (Invariants.
size() == 1 &&
2353 <<
" for unswitch candidate: " << TI <<
"\n");
2354 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2355 BestUnswitchTI = &TI;
2356 BestUnswitchCost = CandidateCost;
2357 BestUnswitchInvariants = Invariants;
2363 << BestUnswitchCost <<
"\n");
2368 << BestUnswitchCost <<
") terminator: " << *BestUnswitchTI
2371 L, *BestUnswitchTI, BestUnswitchInvariants, DT, LI, AC, UnswitchCB, SE);
2400 "Loops must be in LCSSA form before unswitching.");
2401 bool Changed =
false;
2411 UnswitchCB(
true, {});
2447 std::string LoopName = L.
getName();
2449 auto UnswitchCB = [&L, &U, &LoopName](
bool CurrentLoopValid,
2452 if (!NewLoops.empty())
2453 U.addSiblingLoops(NewLoops);
2457 if (CurrentLoopValid)
2458 U.revisitCurrentLoop();
2460 U.markLoopAsDeleted(L, LoopName);
2475 class SimpleLoopUnswitchLegacyPass :
public LoopPass {
2481 explicit SimpleLoopUnswitchLegacyPass(
bool NonTrivial =
false)
2482 :
LoopPass(ID), NonTrivial(NonTrivial) {
2507 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2508 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2509 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2510 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2512 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2513 auto *SE = SEWP ? &SEWP->getSE() :
nullptr;
2515 auto UnswitchCB = [&L, &LPM](
bool CurrentLoopValid,
2518 for (
auto *NewL : NewLoops)
2524 if (CurrentLoopValid)
2530 bool Changed =
unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE);
2545 "Simple unswitch loops",
false,
false)
2555 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Pass interface - Implemented by all 'passes'.
const T & front() const
front - Get the first element.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
static cl::opt< int > UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, cl::desc("The cost threshold for unswitching a loop."))
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
This routine provides some synthesis utilities to produce sequences of values.
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.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
Compute iterated dominance frontiers using a linear time algorithm.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
size_type size() const
Determine the number of elements in the SetVector.
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
static void deleteDeadClonedBlocks(Loop &L, ArrayRef< BasicBlock *> ExitBlocks, ArrayRef< std::unique_ptr< ValueToValueMapTy >> VMaps, DominatorTree &DT)
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
An efficient, type-erasing, non-owning reference to a callable.
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, TargetTransformInfo &TTI, bool NonTrivial, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE)
Unswitch control flow predicated on loop invariant conditions.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
std::vector< LoopT * > & getSubLoopsVector()
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static int computeDomSubtreeCost(DomTreeNode &N, const SmallDenseMap< BasicBlock *, int, 4 > &BBCostMap, SmallDenseMap< DomTreeNode *, int, 4 > &DTCostMap)
Recursively compute the cost of a dominator subtree based on the per-block cost map provided...
Value * getCondition() const
This defines the Use class.
static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, BasicBlock &ExitBB)
Check that all the LCSSA PHI nodes in the loop exit block have trivial incoming values along this edg...
void reserve(size_type N)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void initializeSimpleLoopUnswitchLegacyPassPass(PassRegistry &)
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
SmallPtrSetImpl< const BlockT * > & getBlocksSet()
Return a direct, mutable handle to the blocks set so that we can mutate it efficiently.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void deleteSimpleAnalysisLoop(Loop *L)
Invoke deleteAnalysisLoop hook for all passes that implement simple analysis interface.
A Use represents the edge between a Value definition and its users.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
This header provides classes for managing per-loop analyses.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static SmallPtrSet< const BasicBlock *, 16 > recomputeLoopBlockSet(Loop &L, LoopInfo &LI)
Recompute the set of blocks in a loop after unswitching.
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
static bool unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, TargetTransformInfo &TTI, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE)
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
initializer< Ty > init(const Ty &Val)
static void buildClonedLoops(Loop &OrigL, ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, LoopInfo &LI, SmallVectorImpl< Loop *> &NonChildClonedLoops)
Build the cloned loops of an original loop from unswitching.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
static constexpr UpdateKind Insert
static TinyPtrVector< Value * > collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root, LoopInfo &LI)
Collect all of the loop invariant input values transitively used by the homogeneous instruction graph...
LLVM Basic Block Representation.
void push_back(EltTy NewVal)
Conditional or Unconditional Branch instruction.
size_t size() const
size - Get the array size.
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static void deleteDeadBlocksFromLoop(Loop &L, SmallVectorImpl< BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", "Simple unswitch loops", false, false) INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
BasicBlock * getDefaultDest() const
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
static Loop * cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, const ValueToValueMapTy &VMap, LoopInfo &LI)
Recursively clone the specified loop and all of its children.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool pred_empty(const BasicBlock *BB)
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
static bool unswitchNontrivialInvariants(Loop &L, TerminatorInst &TI, ArrayRef< Value *> Invariants, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE)
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&... args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Fast - This calling convention attempts to make calls as fast as possible (e.g.
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.
static void buildPartialUnswitchConditionalBranch(BasicBlock &BB, ArrayRef< Value *> Invariants, bool Direction, BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc)
Insert code to test a set of loop invariant values, and conditionally branch on them.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void sort(IteratorTy Start, IteratorTy End)
bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
static BasicBlock * buildClonedLoopBlocks(Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, ArrayRef< BasicBlock *> ExitBlocks, BasicBlock *ParentBB, BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, const SmallDenseMap< BasicBlock *, BasicBlock *, 16 > &DominatingSucc, ValueToValueMapTy &VMap, SmallVectorImpl< DominatorTree::UpdateType > &DTUpdates, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
Build the cloned blocks for an unswitched copy of the given loop.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static void replaceLoopInvariantUses(Loop &L, Value *Invariant, Constant &Replacement)
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
static cl::opt< bool > EnableNonTrivialUnswitch("enable-nontrivial-unswitch", cl::init(false), cl::Hidden, cl::desc("Forcibly enables non-trivial loop unswitching rather than " "following the configuration passed into the pass."))
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH)
Rewrite the PHI nodes in an unswitched loop exit basic block.
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
LoopT * AllocateLoop(ArgsTy &&... Args)
LLVM_NODISCARD T pop_back_val()
simple loop Simple unswitch loops
Pass * createSimpleLoopUnswitchLegacyPass(bool NonTrivial=false)
Create the legacy pass object for the simple loop unswitcher.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
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...
pred_range predecessors(BasicBlock *BB)
void markLoopAsDeleted(Loop &L)
static ConstantInt * getTrue(LLVMContext &Context)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader, DominatorTree &DT, LoopInfo &LI)
Hoist the current loop up to the innermost loop containing a remaining exit.
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
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
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...
void emplace_back(ArgTypes &&... Args)
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE)
Unswitch a trivial branch if the condition is loop invariant.
const Function * getParent() const
Return the enclosing method, or null if none.
static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE)
This routine scans the loop to find a branch or switch which occurs before any side effects occur...
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH, bool FullUnswitch)
Rewrite the PHI nodes in the loop exit basic block and the split off unswitched block.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
void setDefaultDest(BasicBlock *DefaultCase)
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
The legacy pass manager's analysis pass to compute loop information.
static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE)
Unswitch a trivial switch if the condition is loop invariant.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
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...
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
iterator_range< block_iterator > blocks() const
static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef< BasicBlock *> ExitBlocks, LoopInfo &LI, SmallVectorImpl< Loop *> &HoistedLoops)
Rebuild a loop after unswitching removes some subset of blocks and edges.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
const BasicBlock * getParent() const
void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable)
Helper to visit a dominator subtree, invoking a callable on each node.
void forgetTopmostLoop(const Loop *L)