81 using namespace jumpthreading;
83 #define DEBUG_TYPE "jump-threading" 85 STATISTIC(NumThreads,
"Number of jumps threaded");
86 STATISTIC(NumFolds,
"Number of terminators folded");
87 STATISTIC(NumDupes,
"Number of branch blocks duplicated to eliminate phi");
91 cl::desc(
"Max block size to duplicate for jump threading"),
96 "jump-threading-implication-search-threshold",
97 cl::desc(
"The number of predecessors to search for a stronger " 98 "condition to use to thread over a weaker condition"),
102 "print-lvi-after-jump-threading",
103 cl::desc(
"Print the LazyValueInfo cache after JumpThreading"),
cl::init(
false),
107 "jump-threading-across-loop-headers",
108 cl::desc(
"Allow JumpThreading to thread across loop headers, for testing"),
159 "Jump Threading",
false,
false)
169 return new JumpThreading(Threshold);
217 uint64_t TrueWeight, FalseWeight;
223 auto GetPredOutEdge =
225 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
226 auto *PredBB = IncomingBB;
227 auto *SuccBB = PhiBB;
232 return {PredBB, SuccBB};
234 auto *SinglePredBB = PredBB->getSinglePredecessor();
236 return {
nullptr,
nullptr};
240 if (Visited.
count(SinglePredBB))
241 return {
nullptr,
nullptr};
244 PredBB = SinglePredBB;
256 TrueWeight, TrueWeight + FalseWeight)
258 FalseWeight, TrueWeight + FalseWeight));
261 if (!PredOutEdge.first)
269 uint64_t PredTrueWeight, PredFalseWeight;
292 .createBranchWeights(Weights));
300 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
303 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
304 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
305 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
307 std::unique_ptr<BlockFrequencyInfo>
BFI;
308 std::unique_ptr<BranchProbabilityInfo> BPI;
316 std::move(BFI), std::move(BPI));
318 dbgs() <<
"LVI for function '" << F.
getName() <<
"':\n";
319 LVI->printLVI(F, *DT,
dbgs());
334 std::unique_ptr<BlockFrequencyInfo>
BFI;
335 std::unique_ptr<BranchProbabilityInfo> BPI;
343 std::move(BFI), std::move(BPI));
357 std::unique_ptr<BlockFrequencyInfo> BFI_,
358 std::unique_ptr<BranchProbabilityInfo> BPI_) {
368 HasProfileData = HasProfileData_;
371 HasGuards = GuardDecl && !GuardDecl->
use_empty();
372 if (HasProfileData) {
373 BPI = std::move(BPI_);
374 BFI = std::move(BFI_);
380 assert(DTU &&
"DTU isn't passed into JumpThreading before using it.");
381 assert(DTU->hasDomTree() &&
"JumpThreading relies on DomTree to proceed.");
384 if (!DT.isReachableFromEntry(&BB))
390 bool EverChanged =
false;
395 if (Unreachable.
count(&BB))
402 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
409 <<
"' with terminator: " << *BB.getTerminator()
411 LoopHeaders.erase(&BB);
412 LVI->eraseBlock(&BB);
421 if (BI && BI->isUnconditional() &&
423 BB.getFirstNonPHIOrDbg()->isTerminator() &&
426 !LoopHeaders.count(&BB) && !LoopHeaders.count(BI->getSuccessor(0)) &&
430 LVI->eraseBlock(&BB);
434 EverChanged |= Changed;
467 I.replaceUsesOfWith(Cond, ToVal);
479 assert(StopAt->
getParent() == BB &&
"Not an instruction from proper BB?");
491 if (isa<SwitchInst>(StopAt))
495 if (isa<IndirectBrInst>(StopAt))
506 for (; &*
I != StopAt; ++
I) {
509 if (Size > Threshold)
513 if (isa<DbgInfoIntrinsic>(
I))
continue;
516 if (isa<BitCastInst>(
I) &&
I->getType()->isPointerTy())
521 if (
I->getType()->isTokenTy() &&
I->isUsedOutsideOfBlock(BB))
531 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
532 if (CI->cannotDuplicate() || CI->isConvergent())
536 else if (!isa<IntrinsicInst>(CI))
538 else if (!CI->getType()->isVectorTy())
543 return Size > Bonus ? Size - Bonus : 0;
564 for (
const auto &Edge : Edges)
565 LoopHeaders.insert(Edge.second);
578 if (
UndefValue *U = dyn_cast<UndefValue>(Val))
596 DenseSet<std::pair<Value *, BasicBlock *>> &RecursionSet,
602 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
608 Result.
push_back(std::make_pair(KC, Pred));
610 return !Result.
empty();
631 if (DTU->hasPendingDomTreeUpdates())
638 Constant *PredCst = LVI->getConstantOnEdge(V,
P, BB, CxtI);
643 return !Result.
empty();
647 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
648 if (DTU->hasPendingDomTreeUpdates())
652 for (
unsigned i = 0,
e = PN->getNumIncomingValues(); i !=
e; ++i) {
653 Value *InVal = PN->getIncomingValue(i);
655 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
657 Constant *CI = LVI->getConstantOnEdge(InVal,
658 PN->getIncomingBlock(i),
661 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
665 return !Result.
empty();
670 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
672 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
674 ComputeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
680 for (
auto &R : Result)
695 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, LHSVals,
697 ComputeValueKnownInPredecessorsImpl(I->
getOperand(1), BB, RHSVals,
700 if (LHSVals.empty() && RHSVals.empty())
713 for (
const auto &LHSVal : LHSVals)
714 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
716 LHSKnownBBs.insert(LHSVal.second);
718 for (
const auto &RHSVal : RHSVals)
719 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
722 if (!LHSKnownBBs.count(RHSVal.second))
726 return !Result.
empty();
730 if (I->
getOpcode() == Instruction::Xor &&
732 cast<ConstantInt>(I->
getOperand(1))->isOne()) {
733 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, Result,
739 for (
auto &R : Result)
748 &&
"A binary operator creating a block address?");
749 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
751 ComputeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
755 for (
const auto &LHSVal : LHSVals) {
760 Result.
push_back(std::make_pair(KC, LHSVal.second));
764 return !Result.
empty();
768 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
770 Type *CmpType = Cmp->getType();
771 Value *CmpLHS = Cmp->getOperand(0);
772 Value *CmpRHS = Cmp->getOperand(1);
782 if (DTU->hasPendingDomTreeUpdates())
798 if (!isa<Constant>(RHS))
803 if (LHSInst && LHSInst->getParent() == BB)
807 ResT = LVI->getPredicateOnEdge(Pred, LHS,
808 cast<Constant>(RHS), PredBB, BB,
816 Result.
push_back(std::make_pair(KC, PredBB));
819 return !Result.
empty();
824 if (isa<Constant>(CmpRHS) && !CmpType->
isVectorTy()) {
825 Constant *CmpConst = cast<Constant>(CmpRHS);
827 if (!isa<Instruction>(CmpLHS) ||
828 cast<Instruction>(CmpLHS)->
getParent() != BB) {
829 if (DTU->hasPendingDomTreeUpdates())
837 LVI->getPredicateOnEdge(Pred, CmpLHS,
838 CmpConst,
P, BB, CxtI ? CxtI : Cmp);
846 return !Result.
empty();
857 if (isa<ConstantInt>(CmpConst) &&
859 if (!isa<Instruction>(AddLHS) ||
860 cast<Instruction>(AddLHS)->
getParent() != BB) {
861 if (DTU->hasPendingDomTreeUpdates())
870 AddLHS,
P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
876 Pred, cast<ConstantInt>(CmpConst)->getValue());
889 return !Result.
empty();
897 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, LHSVals,
900 for (
const auto &LHSVal : LHSVals) {
904 Result.
push_back(std::make_pair(KC, LHSVal.second));
907 return !Result.
empty();
917 if ((TrueVal || FalseVal) &&
918 ComputeValueKnownInPredecessorsImpl(
SI->getCondition(), BB, Conds,
920 for (
auto &
C : Conds) {
925 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
927 KnownCond = CI->isOne();
929 assert(isa<UndefValue>(Cond) &&
"Unexpected condition value");
933 KnownCond = (TrueVal !=
nullptr);
937 if (
Constant *Val = KnownCond ? TrueVal : FalseVal)
938 Result.
push_back(std::make_pair(Val,
C.second));
941 return !Result.
empty();
946 if (DTU->hasPendingDomTreeUpdates())
950 Constant *CI = LVI->getConstant(V, BB, CxtI);
953 Result.
push_back(std::make_pair(KC, Pred));
956 return !Result.
empty();
966 unsigned MinSucc = 0;
969 unsigned MinNumPreds =
pred_size(TestBB);
973 if (NumPreds < MinNumPreds) {
975 MinNumPreds = NumPreds;
997 if (DTU->isBBPendingDeletion(BB) ||
1005 if (MaybeMergeBasicBlockIntoOnlyPred(BB))
1008 if (TryToUnfoldSelectInCurrBB(BB))
1012 if (HasGuards && ProcessGuards(BB))
1022 if (
BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1024 if (BI->isUnconditional())
return false;
1025 Condition = BI->getCondition();
1026 }
else if (
SwitchInst *
SI = dyn_cast<SwitchInst>(Terminator)) {
1027 Condition =
SI->getCondition();
1028 }
else if (
IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1030 if (IB->getNumSuccessors() == 0)
return false;
1039 if (
Instruction *
I = dyn_cast<Instruction>(Condition)) {
1043 I->replaceAllUsesWith(SimpleVal);
1045 I->eraseFromParent();
1046 Condition = SimpleVal;
1052 if (isa<UndefValue>(Condition)) {
1054 std::vector<DominatorTree::UpdateType> Updates;
1060 if (i == BestSucc)
continue;
1067 <<
"' folding undef terminator: " << *BBTerm <<
'\n');
1070 DTU->applyUpdatesPermissive(Updates);
1091 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
1096 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
1103 if (CondBr && CondConst) {
1109 if (DTU->hasPendingDomTreeUpdates())
1114 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1125 if (CondCmp->use_empty())
1126 CondCmp->eraseFromParent();
1134 else if (CondCmp->getParent() == BB) {
1140 DTU->applyUpdatesPermissive(
1147 if (TryToUnfoldSelect(CondCmp, BB))
1153 if (TryToUnfoldSelect(
SI, BB))
1160 Value *SimplifyValue = CondInst;
1161 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1162 if (isa<Constant>(CondCmp->getOperand(1)))
1163 SimplifyValue = CondCmp->getOperand(0);
1167 if (
LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1168 if (SimplifyPartiallyRedundantLoad(LoadI))
1172 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1173 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1179 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1184 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1185 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1186 return ProcessBranchOnPHI(PN);
1189 if (CondInst->
getOpcode() == Instruction::Xor &&
1191 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1195 if (ProcessImpliedCondition(BB))
1203 if (!BI || !BI->isConditional())
1206 Value *Cond = BI->getCondition();
1215 if (!PBI || !PBI->isConditional())
1217 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1224 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1225 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1229 BI->eraseFromParent();
1233 CurrentBB = CurrentPred;
1242 if (
Instruction *OpInst = dyn_cast<Instruction>(Op))
1243 if (OpInst->getParent() == BB)
1285 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1291 if (AvailableVal == LoadI)
1293 if (AvailableVal->getType() != LoadI->
getType())
1295 AvailableVal, LoadI->
getType(),
"", LoadI);
1304 if (BBIt != LoadBB->
begin())
1316 AvailablePredsTy AvailablePreds;
1324 if (!PredsScanned.
insert(PredBB).second)
1327 BBIt = PredBB->
end();
1328 unsigned NumScanedInst = 0;
1329 Value *PredAvailable =
nullptr;
1333 "Attempting to CSE volatile or atomic loads");
1344 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1348 BBIt = SinglePredBB->
end();
1351 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1356 if (!PredAvailable) {
1357 OneUnavailablePred = PredBB;
1362 CSELoads.
push_back(cast<LoadInst>(PredAvailable));
1366 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1371 if (AvailablePreds.empty())
return false;
1388 if (PredsScanned.
size() != AvailablePreds.size() &&
1390 for (
auto I = LoadBB->
begin(); &*
I != LoadI; ++
I)
1397 if (PredsScanned.
size() == AvailablePreds.size()+1 &&
1399 UnavailablePred = OneUnavailablePred;
1400 }
else if (PredsScanned.
size() != AvailablePreds.size()) {
1406 for (
const auto &AvailablePred : AvailablePreds)
1407 AvailablePredSet.
insert(AvailablePred.first);
1413 if (isa<IndirectBrInst>(
P->getTerminator()) ||
1414 isa<CallBrInst>(
P->getTerminator()))
1417 if (!AvailablePredSet.
count(
P))
1422 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit,
"thread-pre-split");
1428 if (UnavailablePred) {
1430 "Can't handle critical edge here!");
1438 NewVal->setAAMetadata(AATags);
1440 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1458 AvailablePredsTy::iterator
I =
1461 assert(I != AvailablePreds.end() && I->first == P &&
1462 "Didn't find entry for predecessor!");
1468 Value *&PredV = I->second;
1469 if (PredV->getType() != LoadI->
getType())
1476 for (
LoadInst *PredLoadI : CSELoads) {
1493 assert(!PredToDestList.empty());
1500 for (
const auto &PredToDest : PredToDestList)
1501 if (PredToDest.second)
1502 DestPopularity[PredToDest.second]++;
1504 if (DestPopularity.empty())
1510 unsigned Popularity = DPI->second;
1513 for (++DPI; DPI != DestPopularity.
end(); ++DPI) {
1516 if (DPI->second < Popularity)
1518 else if (DPI->second == Popularity) {
1523 SamePopularity.
clear();
1524 MostPopularDest = DPI->first;
1525 Popularity = DPI->second;
1533 if (!SamePopularity.
empty()) {
1534 SamePopularity.
push_back(MostPopularDest);
1536 for (
unsigned i = 0; ; ++i) {
1548 return MostPopularDest;
1556 if (LoopHeaders.count(BB))
1560 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1564 "ComputeValueKnownInPredecessors returned true with no values");
1567 for (
const auto &PredValue : PredValues) {
1569 <<
"': FOUND condition = " << *PredValue.first
1570 <<
" for pred '" << PredValue.second->getName() <<
"'.\n";
1585 for (
const auto &PredValue : PredValues) {
1587 if (!SeenPreds.insert(Pred).second)
1593 if (isa<UndefValue>(Val))
1596 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1597 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->
isZero());
1599 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1600 DestBB =
SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1603 &&
"Unexpected terminator");
1604 assert(isa<BlockAddress>(Val) &&
"Expecting a constant blockaddress");
1605 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1609 if (PredToDestList.
empty()) {
1613 if (OnlyDest != DestBB)
1614 OnlyDest = MultipleDestSentinel;
1618 OnlyVal = MultipleVal;
1627 PredToDestList.
push_back(std::make_pair(Pred, DestBB));
1631 if (PredToDestList.
empty())
1637 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1639 bool SeenFirstBranchToOnlyDest =
false;
1640 std::vector <DominatorTree::UpdateType> Updates;
1643 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1644 SeenFirstBranchToOnlyDest =
true;
1646 SuccBB->removePredecessor(BB,
true);
1655 DTU->applyUpdatesPermissive(Updates);
1659 if (
auto *CondInst = dyn_cast<Instruction>(Cond)) {
1660 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1661 CondInst->eraseFromParent();
1669 else if (OnlyVal && OnlyVal != MultipleVal &&
1670 CondInst->getParent() == BB)
1683 if (MostPopularDest == MultipleDestSentinel) {
1688 [&](
const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1689 return LoopHeaders.count(PredToDest.second) != 0;
1692 if (PredToDestList.
empty())
1701 for (
const auto &PredToDest : PredToDestList)
1702 if (PredToDest.second == MostPopularDest) {
1715 if (!MostPopularDest)
1720 return TryThreadEdge(BB, PredsToFactor, MostPopularDest);
1741 if (PredBr->isUnconditional()) {
1742 PredBBs[0] = PredBB;
1744 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1766 if (!isa<PHINode>(BB->
front()))
1793 if (!ComputeValueKnownInPredecessors(BO->
getOperand(0), BB, XorOpValues,
1795 assert(XorOpValues.empty());
1796 if (!ComputeValueKnownInPredecessors(BO->
getOperand(1), BB, XorOpValues,
1802 assert(!XorOpValues.empty() &&
1803 "ComputeValueKnownInPredecessors returned true with no values");
1807 unsigned NumTrue = 0, NumFalse = 0;
1808 for (
const auto &XorOpValue : XorOpValues) {
1809 if (isa<UndefValue>(XorOpValue.first))
1812 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1820 if (NumTrue > NumFalse)
1822 else if (NumTrue != 0 || NumFalse != 0)
1828 for (
const auto &XorOpValue : XorOpValues) {
1829 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1832 BlocksToFoldInto.
push_back(XorOpValue.second);
1837 if (BlocksToFoldInto.size() ==
1838 cast<PHINode>(BB->
front()).getNumIncomingValues()) {
1843 }
else if (SplitVal->
isZero()) {
1856 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1869 Value *IV = PN.getIncomingValueForBlock(OldPred);
1872 if (
Instruction *Inst = dyn_cast<Instruction>(IV)) {
1874 if (I != ValueMap.
end())
1878 PN.addIncoming(IV, NewPred);
1894 if (LoopHeaders.erase(SinglePred))
1895 LoopHeaders.insert(BB);
1897 LVI->eraseBlock(SinglePred);
1928 LVI->eraseBlock(BB);
1947 for (
Use &U :
I.uses()) {
1949 if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
1950 if (UserPN->getIncomingBlock(U) == BB)
1959 if (UsesToRename.
empty())
1961 LLVM_DEBUG(
dbgs() <<
"JT: Renaming non-local uses of: " <<
I <<
"\n");
1970 while (!UsesToRename.
empty())
1994 ValueMapping[PN] = NewPN;
2000 for (; BI != BE; ++BI) {
2004 ValueMapping[&*BI] = New;
2010 if (I != ValueMapping.
end())
2015 return ValueMapping;
2025 <<
"' - would thread to self!\n");
2031 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2033 bool BBIsHeader = LoopHeaders.count(BB);
2034 bool SuccIsHeader = LoopHeaders.count(SuccBB);
2035 dbgs() <<
" Not threading across " 2036 << (BBIsHeader ?
"loop header BB '" :
"block BB '") << BB->
getName()
2037 <<
"' to dest " << (SuccIsHeader ?
"loop header BB '" :
"block BB '")
2038 << SuccBB->
getName() <<
"' - it might create an irreducible loop!\n";
2043 unsigned JumpThreadCost =
2045 if (JumpThreadCost > BBDupThreshold) {
2047 <<
"' - Cost is too high: " << JumpThreadCost <<
"\n");
2051 ThreadEdge(BB, PredBBs, SuccBB);
2061 assert(SuccBB != BB &&
"Don't create an infinite loop");
2063 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
2064 "Don't thread across loop headers");
2068 if (PredBBs.
size() == 1)
2069 PredBB = PredBBs[0];
2072 <<
" common predecessors.\n");
2073 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
2077 LLVM_DEBUG(
dbgs() <<
" Threading edge from '" << PredBB->getName()
2078 <<
"' to '" << SuccBB->
getName()
2079 <<
", across block:\n " << *BB <<
"\n");
2081 if (DTU->hasPendingDomTreeUpdates())
2085 LVI->threadEdge(PredBB, BB, SuccBB);
2093 if (HasProfileData) {
2095 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2096 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2101 CloneInstructions(BB->
begin(), std::prev(BB->
end()), NewBB, PredBB);
2127 UpdateSSA(BB, NewBB, ValueMapping);
2135 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2146 const char *Suffix) {
2153 for (
auto Pred : Preds)
2154 FreqMap.
insert(std::make_pair(
2155 Pred,
BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2160 std::string NewName = std::string(Suffix) +
".split-lp";
2166 std::vector<DominatorTree::UpdateType> Updates;
2167 Updates.reserve((2 * Preds.size()) + NewBBs.
size());
2168 for (
auto NewBB : NewBBs) {
2175 NewBBFreq += FreqMap.
lookup(Pred);
2181 DTU->applyUpdatesPermissive(Updates);
2185 bool JumpThreadingPass::doesBlockHaveProfileData(
BasicBlock *BB) {
2193 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2194 if (MDName->
getString() !=
"branch_weights")
2205 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(
BasicBlock *PredBB,
2209 if (!HasProfileData)
2212 assert(
BFI && BPI &&
"BFI & BPI should have been created here");
2216 auto BBOrigFreq =
BFI->getBlockFreq(BB);
2217 auto NewBBFreq =
BFI->getBlockFreq(NewBB);
2218 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2219 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2220 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2226 auto SuccFreq = (Succ == SuccBB)
2227 ? BB2SuccBBFreq - NewBBFreq
2228 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2229 BBSuccFreq.
push_back(SuccFreq.getFrequency());
2232 uint64_t MaxBBSuccFreq =
2233 *std::max_element(BBSuccFreq.
begin(), BBSuccFreq.
end());
2236 if (MaxBBSuccFreq == 0)
2238 {1,
static_cast<unsigned>(BBSuccFreq.
size())});
2240 for (uint64_t Freq : BBSuccFreq)
2241 BBSuccProbs.push_back(
2249 for (
int I = 0,
E = BBSuccProbs.size();
I <
E;
I++)
2250 BPI->setEdgeProbability(BB,
I, BBSuccProbs[
I]);
2286 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2288 for (
auto Prob : BBSuccProbs)
2293 LLVMContext::MD_prof,
2294 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2305 assert(!PredBBs.
empty() &&
"Can't handle an empty set");
2310 if (LoopHeaders.count(BB)) {
2312 <<
"' into predecessor block '" << PredBBs[0]->getName()
2313 <<
"' - it might create an irreducible loop!\n");
2317 unsigned DuplicationCost =
2319 if (DuplicationCost > BBDupThreshold) {
2321 <<
"' - Cost is too high: " << DuplicationCost <<
"\n");
2326 std::vector<DominatorTree::UpdateType> Updates;
2328 if (PredBBs.
size() == 1)
2329 PredBB = PredBBs[0];
2332 <<
" common predecessors.\n");
2333 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
2340 <<
"' into end of '" << PredBB->
getName()
2341 <<
"' to eliminate branch on phi. Cost: " 2342 << DuplicationCost <<
" block is:" << *BB <<
"\n");
2348 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2366 for (; BI != BB->
end(); ++BI) {
2373 if (I != ValueMapping.end())
2383 ValueMapping[&*BI] = IV;
2389 ValueMapping[&*BI] = New;
2410 UpdateSSA(BB, PredBB, ValueMapping);
2417 OldPredBranch->eraseFromParent();
2418 DTU->applyUpdatesPermissive(Updates);
2446 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2467 if (!CondPHI || CondPHI->
getParent() != BB)
2484 UnfoldSelectInstr(Pred, BB, PredSI, CondPHI,
I);
2508 CondLHS->getParent() != BB)
2511 for (
unsigned I = 0,
E = CondLHS->getNumIncomingValues();
I !=
E; ++
I) {
2527 if (DTU->hasPendingDomTreeUpdates())
2533 CondRHS, Pred, BB, CondCmp);
2536 CondRHS, Pred, BB, CondCmp);
2539 LHSFolds != RHSFolds) {
2540 UnfoldSelectInstr(Pred, BB, SI, CondLHS,
I);
2570 if (LoopHeaders.count(BB))
2577 [](
Value *V) {
return !isa<ConstantInt>(V); }))
2590 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2593 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2594 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2595 if (
SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2596 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2600 }
else if (
SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2602 if (isUnfoldCandidate(SelectI, U.get())) {
2622 std::vector<DominatorTree::UpdateType> Updates;
2623 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2632 DTU->applyUpdatesPermissive(Updates);
2680 if (
auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2682 if (
isGuard(&
I) && ThreadGuard(BB, cast<IntrinsicInst>(&
I), BI))
2701 bool TrueDestIsSafe =
false;
2702 bool FalseDestIsSafe =
false;
2707 TrueDestIsSafe =
true;
2712 FalseDestIsSafe =
true;
2715 if (!TrueDestIsSafe && !FalseDestIsSafe)
2718 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2719 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2724 if (Cost > BBDupThreshold)
2729 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
2730 assert(GuardedBlock &&
"Could not create the guarded block?");
2735 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
2736 assert(UnguardedBlock &&
"Could not create the unguarded block?");
2738 << GuardedBlock->
getName() <<
"\n");
2743 for (
auto BI = BB->
begin(); &*BI != AfterGuard; ++BI)
2744 if (!isa<PHINode>(&*BI))
2748 assert(InsertionPoint &&
"Empty block?");
2750 for (
auto *Inst :
reverse(ToRemove)) {
2751 if (!Inst->use_empty()) {
2753 NewPN->
addIncoming(UnguardedMapping[Inst], UnguardedBlock);
2754 NewPN->
addIncoming(GuardedMapping[Inst], GuardedBlock);
2756 Inst->replaceAllUsesWith(NewPN);
2758 Inst->eraseFromParent();
Legacy wrapper pass to provide the GlobalsAAResult object.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
reference emplace_back(ArgTypes &&... Args)
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
Helper class for SSA formation on a set of values defined in multiple blocks.
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BranchProbability getCompl() const
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Wrapper around LazyValueInfo.
This is the interface for a simple mod/ref and alias analysis over globals.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
void initializeJumpThreadingPass(PassRegistry &)
Implements a dense probed hash-table based set.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
This class represents a function call, abstracting a target machine's calling convention.
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
Value * getCondition() const
const Value * getTrueValue() const
void ThreadEdge(BasicBlock *BB, const SmallVectorImpl< BasicBlock *> &PredBBs, BasicBlock *SuccBB)
ThreadEdge - We have decided that it is safe and profitable to factor the blocks in PredBBs to one pr...
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
LLVMContext & getContext() const
All values hold a context through their type.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
void deleteValue()
Delete a pointer to a generic Value.
static cl::opt< unsigned > ImplicationSearchThreshold("jump-threading-implication-search-threshold", cl::desc("The number of predecessors to search for a stronger " "condition to use to thread over a weaker condition"), cl::init(3), cl::Hidden)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Value * FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy, bool AtLeastAtomic, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, AliasAnalysis *AA, bool *IsLoad, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
static BasicBlock * FindMostPopularDest(BasicBlock *BB, const SmallVectorImpl< std::pair< BasicBlock *, BasicBlock *>> &PredToDestList)
FindMostPopularDest - The specified list contains multiple possible threadable destinations.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
bool isVectorTy() const
True if this is an instance of VectorType.
This defines the Use class.
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
LLVMContext & getContext() const
Get the context in which this basic block lives.
FunctionPass * createJumpThreadingPass(int Threshold=-1)
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool runImpl(Function &F, TargetLibraryInfo *TLI_, LazyValueInfo *LVI_, AliasAnalysis *AA_, DomTreeUpdater *DTU_, bool HasProfileData_, std::unique_ptr< BlockFrequencyInfo > BFI_, std::unique_ptr< BranchProbabilityInfo > BPI_)
The address of a basic block.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!)...
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static constexpr UpdateKind Delete
This is the base class for all instructions that perform data casts.
static cl::opt< unsigned > BBDuplicateThreshold("jump-threading-threshold", cl::desc("Max block size to duplicate for jump threading"), cl::init(6), cl::Hidden)
'undef' values are things that do not have specified contents.
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AliasAnalysis *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
unsigned getNumSuccessors() const
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool MaybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB)
Merge basic block BB into its sole predecessor if possible.
void setName(const Twine &Name)
Change the name of the value.
void UpdateSSA(BasicBlock *BB, BasicBlock *NewBB, DenseMap< Instruction *, Value *> &ValueMapping)
Update the SSA form.
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
bool TryToUnfoldSelectInCurrBB(BasicBlock *BB)
TryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the same BB in the form bb: p = ...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
void assign(size_type NumElts, const T &Elt)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool ComputeValueKnownInPredecessorsImpl(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, DenseSet< std::pair< Value *, BasicBlock *>> &RecursionSet, Instruction *CxtI=nullptr)
ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see if we can infer that the ...
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
Type * getType() const
All values are typed, get the type of this value.
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
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.
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
void takeName(Value *V)
Transfer the name from V to this value.
static Constant * getKnownConstant(Value *Val, ConstantPreference Preference)
getKnownConstant - Helper method to determine if we can thread over a terminator with the given value...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
iterator find(const_arg_type_t< KeyT > Val)
StringRef getString() const
const BasicBlock & getEntryBlock() const
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static bool runOnFunction(Function &F, bool PostInlining)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
DenseMap< Instruction *, Value * > CloneInstructions(BasicBlock::iterator BI, BasicBlock::iterator BE, BasicBlock *NewBB, BasicBlock *PredBB)
Clone instructions in range [BI, BE) to NewBB.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB)
Return true if Op is an instruction defined in the given block.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Indirect Branch Instruction.
A manager for alias analyses.
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.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
JumpThreadingPass(int T=-1)
FunctionPass class - This class is used to implement most global optimizations.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
bool pred_empty(const BasicBlock *BB)
static Constant * getNot(Constant *C)
void FindLoopHeaders(Function &F)
FindLoopHeaders - We do not want jump threading to turn proper loop structures into irreducible loops...
const Value * getCondition() const
static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool isExceptionalTerminator() const
static cl::opt< bool > ThreadAcrossLoopHeaders("jump-threading-across-loop-headers", cl::desc("Allow JumpThreading to thread across loop headers, for testing"), cl::init(false), cl::Hidden)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB)
GetBestDestForBranchOnUndef - If we determine that the specified block ends in an undefined jump...
Tristate
This is used to return true/false/dunno results.
bool ProcessBranchOnPHI(PHINode *PN)
ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on a PHI node in the curren...
bool isLandingPad() const
Return true if this basic block is a landing pad.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
static cl::opt< bool > PrintLVIAfterJumpThreading("print-lvi-after-jump-threading", cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false), cl::Hidden)
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
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.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
This class represents a range of values.
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool SimplifyPartiallyRedundantLoad(LoadInst *LI)
SimplifyPartiallyRedundantLoad - If LoadI is an obviously partially redundant load instruction...
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)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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...
bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental.guard intrinsic.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static unsigned getJumpThreadDuplicationCost(BasicBlock *BB, Instruction *StopAt, unsigned Threshold)
Return the cost of duplicating a piece of this block from first non-phi and before StopAt instruction...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
void push_back(pointer val)
InstListType::iterator iterator
Instruction iterators...
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
const Value * getFalseValue() const
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Analysis providing branch probability information.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM_NODISCARD bool empty() const
void UnfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, SelectInst *SI, PHINode *SIUse, unsigned Idx)
bool ProcessBranchOnXOR(BinaryOperator *BO)
ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on a xor instruction in the...
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool ProcessImpliedCondition(BasicBlock *BB)
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static void ReplaceFoldableUses(Instruction *Cond, Value *ToVal)
void preserve()
Mark an analysis as preserved.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isUnconditional() const
static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, BasicBlock *OldPred, BasicBlock *NewPred, DenseMap< Instruction *, Value *> &ValueMap)
AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new predecessor to the PHIBB 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...
bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB, jumpthreading::ConstantPreference Preference, Instruction *CxtI=nullptr)
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock *> > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them...
Analysis pass providing the TargetLibraryInfo.
Helper struct that represents how a value is mapped through different register banks.
This pass computes, caches, and vends lazy value constraint information.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
See the comments on JumpThreadingPass.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isEHPad() const
Return true if this basic block is an exception handling block.
bool ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard, BranchInst *BI)
Try to propagate the guard from BB which is the lower block of a diamond to one of its branches...
bool ProcessGuards(BasicBlock *BB)
Try to propagate a guard from the current BB into one of its predecessors in case if another branch o...
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(Instruction *I)
bool ProcessBlock(BasicBlock *BB)
ProcessBlock - If there are any predecessors whose control can be threaded through to a successor...
static const Function * getParent(const Value *V)
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", "Jump Threading", false, false) INITIALIZE_PASS_END(JumpThreading
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
op_range incoming_values()
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
bool TryThreadEdge(BasicBlock *BB, const SmallVectorImpl< BasicBlock *> &PredBBs, BasicBlock *SuccBB)
TryThreadEdge - Thread an edge if it's safe and profitable to do so.
bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, const SmallVectorImpl< BasicBlock *> &PredBBs)
DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch to BB which contains an i1...
static bool hasAddressTakenAndUsed(BasicBlock *BB)
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
uint32_t getNumerator() const
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Analysis to compute lazy value information.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB)
TryToUnfoldSelect - Look for blocks of the form bb1: a = select br bb2.
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.