79 using namespace jumpthreading;
81 #define DEBUG_TYPE "jump-threading" 83 STATISTIC(NumThreads,
"Number of jumps threaded");
84 STATISTIC(NumFolds,
"Number of terminators folded");
85 STATISTIC(NumDupes,
"Number of branch blocks duplicated to eliminate phi");
89 cl::desc(
"Max block size to duplicate for jump threading"),
94 "jump-threading-implication-search-threshold",
95 cl::desc(
"The number of predecessors to search for a stronger " 96 "condition to use to thread over a weaker condition"),
100 "print-lvi-after-jump-threading",
101 cl::desc(
"Print the LazyValueInfo cache after JumpThreading"),
cl::init(
false),
151 "Jump Threading",
false,
false)
161 return new JumpThreading(Threshold);
209 uint64_t TrueWeight, FalseWeight;
215 auto GetPredOutEdge =
217 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
218 auto *PredBB = IncomingBB;
219 auto *SuccBB = PhiBB;
223 return {PredBB, SuccBB};
224 auto *SinglePredBB = PredBB->getSinglePredecessor();
226 return {
nullptr,
nullptr};
228 PredBB = SinglePredBB;
240 TrueWeight, TrueWeight + FalseWeight)
242 FalseWeight, TrueWeight + FalseWeight));
245 if (!PredOutEdge.first)
251 uint64_t PredTrueWeight, PredFalseWeight;
274 .createBranchWeights(Weights));
282 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
285 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
286 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
287 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
289 std::unique_ptr<BlockFrequencyInfo>
BFI;
290 std::unique_ptr<BranchProbabilityInfo> BPI;
292 if (HasProfileData) {
298 bool Changed = Impl.
runImpl(F, TLI, LVI, AA, &DDT, HasProfileData,
299 std::move(BFI), std::move(BPI));
301 dbgs() <<
"LVI for function '" << F.
getName() <<
"':\n";
302 LVI->printLVI(F, *DT,
dbgs());
317 std::unique_ptr<BlockFrequencyInfo>
BFI;
318 std::unique_ptr<BranchProbabilityInfo> BPI;
325 bool Changed =
runImpl(F, &TLI, &LVI, &AA, &DDT, HasProfileData,
326 std::move(BFI), std::move(BPI));
340 std::unique_ptr<BlockFrequencyInfo> BFI_,
341 std::unique_ptr<BranchProbabilityInfo> BPI_) {
351 HasProfileData = HasProfileData_;
354 HasGuards = GuardDecl && !GuardDecl->
use_empty();
355 if (HasProfileData) {
356 BPI = std::move(BPI_);
357 BFI = std::move(BFI_);
370 bool EverChanged =
false;
375 if (Unreachable.
count(&BB))
382 if (&BB == &F.getEntryBlock() || DDT->pendingDeletedBB(&BB))
389 <<
"' with terminator: " << *BB.getTerminator()
391 LoopHeaders.erase(&BB);
392 LVI->eraseBlock(&BB);
401 if (BI && BI->isUnconditional() &&
403 BB.getFirstNonPHIOrDbg()->isTerminator() &&
406 !LoopHeaders.count(&BB) && !LoopHeaders.count(BI->getSuccessor(0)) &&
410 LVI->eraseBlock(&BB);
414 EverChanged |= Changed;
446 I.replaceUsesOfWith(Cond, ToVal);
458 assert(StopAt->
getParent() == BB &&
"Not an instruction from proper BB?");
470 if (isa<SwitchInst>(StopAt))
474 if (isa<IndirectBrInst>(StopAt))
485 for (; &*
I != StopAt; ++
I) {
488 if (Size > Threshold)
492 if (isa<DbgInfoIntrinsic>(
I))
continue;
495 if (isa<BitCastInst>(
I) &&
I->getType()->isPointerTy())
500 if (
I->getType()->isTokenTy() &&
I->isUsedOutsideOfBlock(BB))
510 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
511 if (CI->cannotDuplicate() || CI->isConvergent())
515 else if (!isa<IntrinsicInst>(CI))
517 else if (!CI->getType()->isVectorTy())
522 return Size > Bonus ? Size - Bonus : 0;
543 for (
const auto &Edge : Edges)
544 LoopHeaders.insert(Edge.second);
557 if (
UndefValue *U = dyn_cast<UndefValue>(Val))
579 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
584 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
589 Result.
push_back(std::make_pair(KC, Pred));
591 return !Result.
empty();
619 Constant *PredCst = LVI->getConstantOnEdge(V,
P, BB, CxtI);
624 return !Result.
empty();
628 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
633 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
634 Value *InVal = PN->getIncomingValue(i);
636 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
638 Constant *CI = LVI->getConstantOnEdge(InVal,
639 PN->getIncomingBlock(i),
642 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
646 return !Result.
empty();
651 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
653 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
655 ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI);
660 for (
auto &R : Result)
675 ComputeValueKnownInPredecessors(I->
getOperand(0), BB, LHSVals,
677 ComputeValueKnownInPredecessors(I->
getOperand(1), BB, RHSVals,
680 if (LHSVals.empty() && RHSVals.empty())
693 for (
const auto &LHSVal : LHSVals)
694 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
696 LHSKnownBBs.insert(LHSVal.second);
698 for (
const auto &RHSVal : RHSVals)
699 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
702 if (!LHSKnownBBs.count(RHSVal.second))
706 return !Result.
empty();
710 if (I->
getOpcode() == Instruction::Xor &&
712 cast<ConstantInt>(I->
getOperand(1))->isOne()) {
713 ComputeValueKnownInPredecessors(I->
getOperand(0), BB, Result,
719 for (
auto &R : Result)
728 &&
"A binary operator creating a block address?");
729 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
731 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
735 for (
const auto &LHSVal : LHSVals) {
740 Result.
push_back(std::make_pair(KC, LHSVal.second));
744 return !Result.
empty();
748 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
750 Type *CmpType = Cmp->getType();
751 Value *CmpLHS = Cmp->getOperand(0);
752 Value *CmpRHS = Cmp->getOperand(1);
778 if (!isa<Constant>(RHS))
783 if (LHSInst && LHSInst->getParent() == BB)
787 ResT = LVI->getPredicateOnEdge(Pred, LHS,
788 cast<Constant>(RHS), PredBB, BB,
796 Result.
push_back(std::make_pair(KC, PredBB));
799 return !Result.
empty();
804 if (isa<Constant>(CmpRHS) && !CmpType->
isVectorTy()) {
805 Constant *CmpConst = cast<Constant>(CmpRHS);
807 if (!isa<Instruction>(CmpLHS) ||
808 cast<Instruction>(CmpLHS)->
getParent() != BB) {
817 LVI->getPredicateOnEdge(Pred, CmpLHS,
818 CmpConst,
P, BB, CxtI ? CxtI : Cmp);
826 return !Result.
empty();
837 if (isa<ConstantInt>(CmpConst) &&
839 if (!isa<Instruction>(AddLHS) ||
840 cast<Instruction>(AddLHS)->
getParent() != BB) {
850 AddLHS,
P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
856 Pred, cast<ConstantInt>(CmpConst)->getValue());
869 return !Result.
empty();
877 ComputeValueKnownInPredecessors(I->
getOperand(0), BB, LHSVals,
880 for (
const auto &LHSVal : LHSVals) {
884 Result.
push_back(std::make_pair(KC, LHSVal.second));
887 return !Result.
empty();
897 if ((TrueVal || FalseVal) &&
898 ComputeValueKnownInPredecessors(
SI->getCondition(), BB, Conds,
900 for (
auto &
C : Conds) {
905 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
907 KnownCond = CI->isOne();
909 assert(isa<UndefValue>(Cond) &&
"Unexpected condition value");
913 KnownCond = (TrueVal !=
nullptr);
917 if (
Constant *Val = KnownCond ? TrueVal : FalseVal)
918 Result.
push_back(std::make_pair(Val,
C.second));
921 return !Result.
empty();
930 Constant *CI = LVI->getConstant(V, BB, CxtI);
933 Result.
push_back(std::make_pair(KC, Pred));
936 return !Result.
empty();
946 unsigned MinSucc = 0;
949 unsigned MinNumPreds =
pred_size(TestBB);
953 if (NumPreds < MinNumPreds) {
955 MinNumPreds = NumPreds;
977 if (DDT->pendingDeletedBB(BB) ||
990 if (LoopHeaders.erase(SinglePred))
991 LoopHeaders.insert(BB);
993 LVI->eraseBlock(SinglePred);
1024 LVI->eraseBlock(BB);
1029 if (TryToUnfoldSelectInCurrBB(BB))
1033 if (HasGuards && ProcessGuards(BB))
1043 if (
BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1045 if (BI->isUnconditional())
return false;
1046 Condition = BI->getCondition();
1047 }
else if (
SwitchInst *
SI = dyn_cast<SwitchInst>(Terminator)) {
1048 Condition =
SI->getCondition();
1049 }
else if (
IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1051 if (IB->getNumSuccessors() == 0)
return false;
1060 if (
Instruction *
I = dyn_cast<Instruction>(Condition)) {
1064 I->replaceAllUsesWith(SimpleVal);
1066 I->eraseFromParent();
1067 Condition = SimpleVal;
1073 if (isa<UndefValue>(Condition)) {
1075 std::vector<DominatorTree::UpdateType> Updates;
1081 if (i == BestSucc)
continue;
1088 <<
"' folding undef terminator: " << *BBTerm <<
'\n');
1091 DDT->applyUpdates(Updates);
1112 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
1117 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
1124 if (CondBr && CondConst) {
1135 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1144 if (CondCmp->use_empty())
1145 CondCmp->eraseFromParent();
1153 else if (CondCmp->getParent() == BB) {
1159 DDT->deleteEdge(BB, ToRemoveSucc);
1165 if (TryToUnfoldSelect(CondCmp, BB))
1174 Value *SimplifyValue = CondInst;
1175 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1176 if (isa<Constant>(CondCmp->getOperand(1)))
1177 SimplifyValue = CondCmp->getOperand(0);
1181 if (
LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1182 if (SimplifyPartiallyRedundantLoad(LoadI))
1186 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1187 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1193 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1198 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1199 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1200 return ProcessBranchOnPHI(PN);
1203 if (CondInst->
getOpcode() == Instruction::Xor &&
1205 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1209 if (ProcessImpliedCondition(BB))
1217 if (!BI || !BI->isConditional())
1220 Value *Cond = BI->getCondition();
1229 if (!PBI || !PBI->isConditional())
1231 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1238 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1239 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1242 BI->eraseFromParent();
1243 DDT->deleteEdge(BB, RemoveSucc);
1246 CurrentBB = CurrentPred;
1255 if (
Instruction *OpInst = dyn_cast<Instruction>(Op))
1256 if (OpInst->getParent() == BB)
1298 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1304 if (AvailableVal == LoadI)
1306 if (AvailableVal->getType() != LoadI->
getType())
1308 AvailableVal, LoadI->
getType(),
"", LoadI);
1317 if (BBIt != LoadBB->
begin())
1329 AvailablePredsTy AvailablePreds;
1337 if (!PredsScanned.
insert(PredBB).second)
1340 BBIt = PredBB->end();
1341 unsigned NumScanedInst = 0;
1342 Value *PredAvailable =
nullptr;
1346 "Attempting to CSE volatile or atomic loads");
1357 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1361 BBIt = SinglePredBB->
end();
1364 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1369 if (!PredAvailable) {
1370 OneUnavailablePred = PredBB;
1375 CSELoads.
push_back(cast<LoadInst>(PredAvailable));
1379 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1384 if (AvailablePreds.empty())
return false;
1401 if (PredsScanned.
size() != AvailablePreds.size() &&
1403 for (
auto I = LoadBB->
begin(); &*
I != LoadI; ++
I)
1410 if (PredsScanned.
size() == AvailablePreds.size()+1 &&
1412 UnavailablePred = OneUnavailablePred;
1413 }
else if (PredsScanned.
size() != AvailablePreds.size()) {
1419 for (
const auto &AvailablePred : AvailablePreds)
1420 AvailablePredSet.
insert(AvailablePred.first);
1425 if (isa<IndirectBrInst>(
P->getTerminator()))
1428 if (!AvailablePredSet.
count(
P))
1433 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit,
"thread-pre-split");
1439 if (UnavailablePred) {
1441 "Can't handle critical edge here!");
1449 NewVal->setAAMetadata(AATags);
1451 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1469 AvailablePredsTy::iterator
I =
1471 std::make_pair(P, (
Value*)
nullptr));
1473 assert(I != AvailablePreds.end() && I->first == P &&
1474 "Didn't find entry for predecessor!");
1480 Value *&PredV = I->second;
1481 if (PredV->getType() != LoadI->
getType())
1488 for (
LoadInst *PredLoadI : CSELoads) {
1505 assert(!PredToDestList.empty());
1512 for (
const auto &PredToDest : PredToDestList)
1513 if (PredToDest.second)
1514 DestPopularity[PredToDest.second]++;
1516 if (DestPopularity.empty())
1522 unsigned Popularity = DPI->second;
1525 for (++DPI; DPI != DestPopularity.
end(); ++DPI) {
1528 if (DPI->second < Popularity)
1530 else if (DPI->second == Popularity) {
1535 SamePopularity.
clear();
1536 MostPopularDest = DPI->first;
1537 Popularity = DPI->second;
1545 if (!SamePopularity.
empty()) {
1546 SamePopularity.
push_back(MostPopularDest);
1548 for (
unsigned i = 0; ; ++i) {
1560 return MostPopularDest;
1568 if (LoopHeaders.count(BB))
1572 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1576 "ComputeValueKnownInPredecessors returned true with no values");
1579 for (
const auto &PredValue : PredValues) {
1581 <<
"': FOUND condition = " << *PredValue.first
1582 <<
" for pred '" << PredValue.second->getName() <<
"'.\n";
1597 unsigned PredWithKnownDest = 0;
1598 for (
const auto &PredValue : PredValues) {
1600 if (!SeenPreds.insert(Pred).second)
1606 if (isa<UndefValue>(Val))
1609 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1610 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->
isZero());
1612 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1613 DestBB =
SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1616 &&
"Unexpected terminator");
1617 assert(isa<BlockAddress>(Val) &&
"Expecting a constant blockaddress");
1618 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1622 if (PredToDestList.
empty()) {
1626 if (OnlyDest != DestBB)
1627 OnlyDest = MultipleDestSentinel;
1631 OnlyVal = MultipleVal;
1635 ++PredWithKnownDest;
1642 PredToDestList.
push_back(std::make_pair(Pred, DestBB));
1646 if (PredToDestList.
empty())
1652 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1653 if (PredWithKnownDest == (
size_t)
pred_size(BB)) {
1654 bool SeenFirstBranchToOnlyDest =
false;
1655 std::vector <DominatorTree::UpdateType> Updates;
1658 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1659 SeenFirstBranchToOnlyDest =
true;
1661 SuccBB->removePredecessor(BB,
true);
1670 DDT->applyUpdates(Updates);
1674 if (
auto *CondInst = dyn_cast<Instruction>(Cond)) {
1675 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1676 CondInst->eraseFromParent();
1684 else if (OnlyVal && OnlyVal != MultipleVal &&
1685 CondInst->getParent() == BB)
1698 if (MostPopularDest == MultipleDestSentinel) {
1703 [&](
const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1704 return LoopHeaders.count(PredToDest.second) != 0;
1707 if (PredToDestList.
empty())
1716 for (
const auto &PredToDest : PredToDestList)
1717 if (PredToDest.second == MostPopularDest) {
1730 if (!MostPopularDest)
1735 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1756 if (PredBr->isUnconditional()) {
1757 PredBBs[0] = PredBB;
1759 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1781 if (!isa<PHINode>(BB->
front()))
1808 if (!ComputeValueKnownInPredecessors(BO->
getOperand(0), BB, XorOpValues,
1810 assert(XorOpValues.empty());
1811 if (!ComputeValueKnownInPredecessors(BO->
getOperand(1), BB, XorOpValues,
1817 assert(!XorOpValues.empty() &&
1818 "ComputeValueKnownInPredecessors returned true with no values");
1822 unsigned NumTrue = 0, NumFalse = 0;
1823 for (
const auto &XorOpValue : XorOpValues) {
1824 if (isa<UndefValue>(XorOpValue.first))
1827 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1835 if (NumTrue > NumFalse)
1837 else if (NumTrue != 0 || NumFalse != 0)
1843 for (
const auto &XorOpValue : XorOpValues) {
1844 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1847 BlocksToFoldInto.
push_back(XorOpValue.second);
1852 if (BlocksToFoldInto.size() ==
1853 cast<PHINode>(BB->
front()).getNumIncomingValues()) {
1858 }
else if (SplitVal->
isZero()) {
1871 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1884 Value *IV = PN.getIncomingValueForBlock(OldPred);
1887 if (
Instruction *Inst = dyn_cast<Instruction>(IV)) {
1889 if (I != ValueMap.
end())
1893 PN.addIncoming(IV, NewPred);
1906 <<
"' - would thread to self!\n");
1912 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
1914 bool BBIsHeader = LoopHeaders.count(BB);
1915 bool SuccIsHeader = LoopHeaders.count(SuccBB);
1916 dbgs() <<
" Not threading across " 1917 << (BBIsHeader ?
"loop header BB '" :
"block BB '") << BB->
getName()
1918 <<
"' to dest " << (SuccIsHeader ?
"loop header BB '" :
"block BB '")
1919 << SuccBB->
getName() <<
"' - it might create an irreducible loop!\n";
1924 unsigned JumpThreadCost =
1926 if (JumpThreadCost > BBDupThreshold) {
1928 <<
"' - Cost is too high: " << JumpThreadCost <<
"\n");
1934 if (PredBBs.
size() == 1)
1935 PredBB = PredBBs[0];
1938 <<
" common predecessors.\n");
1939 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
1944 <<
"' to '" << SuccBB->
getName()
1945 <<
"' with cost: " << JumpThreadCost
1946 <<
", across block:\n " << *BB <<
"\n");
1952 LVI->threadEdge(PredBB, BB, SuccBB);
1965 if (HasProfileData) {
1967 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
1968 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
1977 for (; !isa<TerminatorInst>(BI); ++BI) {
1981 ValueMapping[&*BI] = New;
1987 if (I != ValueMapping.
end())
2027 for (
Use &U :
I.uses()) {
2029 if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
2030 if (UserPN->getIncomingBlock(U) == BB)
2039 if (UsesToRename.
empty())
2041 LLVM_DEBUG(
dbgs() <<
"JT: Renaming non-local uses of: " <<
I <<
"\n");
2050 while (!UsesToRename.
empty())
2061 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2073 const char *Suffix) {
2080 for (
auto Pred : Preds)
2081 FreqMap.
insert(std::make_pair(
2082 Pred,
BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2087 std::string NewName = std::string(Suffix) +
".split-lp";
2093 std::vector<DominatorTree::UpdateType> Updates;
2094 Updates.reserve((2 * Preds.size()) + NewBBs.
size());
2095 for (
auto NewBB : NewBBs) {
2102 NewBBFreq += FreqMap.
lookup(Pred);
2108 DDT->applyUpdates(Updates);
2112 bool JumpThreadingPass::doesBlockHaveProfileData(
BasicBlock *BB) {
2120 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2121 if (MDName->
getString() !=
"branch_weights")
2132 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(
BasicBlock *PredBB,
2136 if (!HasProfileData)
2139 assert(
BFI && BPI &&
"BFI & BPI should have been created here");
2143 auto BBOrigFreq =
BFI->getBlockFreq(BB);
2144 auto NewBBFreq =
BFI->getBlockFreq(NewBB);
2145 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2146 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2147 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2153 auto SuccFreq = (Succ == SuccBB)
2154 ? BB2SuccBBFreq - NewBBFreq
2155 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2156 BBSuccFreq.
push_back(SuccFreq.getFrequency());
2159 uint64_t MaxBBSuccFreq =
2160 *std::max_element(BBSuccFreq.
begin(), BBSuccFreq.
end());
2163 if (MaxBBSuccFreq == 0)
2165 {1,
static_cast<unsigned>(BBSuccFreq.
size())});
2167 for (uint64_t Freq : BBSuccFreq)
2168 BBSuccProbs.push_back(
2176 for (
int I = 0,
E = BBSuccProbs.size();
I <
E;
I++)
2177 BPI->setEdgeProbability(BB,
I, BBSuccProbs[
I]);
2213 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2215 for (
auto Prob : BBSuccProbs)
2221 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2232 assert(!PredBBs.
empty() &&
"Can't handle an empty set");
2237 if (LoopHeaders.count(BB)) {
2239 <<
"' into predecessor block '" << PredBBs[0]->getName()
2240 <<
"' - it might create an irreducible loop!\n");
2244 unsigned DuplicationCost =
2246 if (DuplicationCost > BBDupThreshold) {
2248 <<
"' - Cost is too high: " << DuplicationCost <<
"\n");
2253 std::vector<DominatorTree::UpdateType> Updates;
2255 if (PredBBs.
size() == 1)
2256 PredBB = PredBBs[0];
2259 <<
" common predecessors.\n");
2260 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
2267 <<
"' into end of '" << PredBB->
getName()
2268 <<
"' to eliminate branch on phi. Cost: " 2269 << DuplicationCost <<
" block is:" << *BB <<
"\n");
2275 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2293 for (; BI != BB->
end(); ++BI) {
2300 if (I != ValueMapping.end())
2310 ValueMapping[&*BI] = IV;
2316 ValueMapping[&*BI] = New;
2346 for (
Use &U :
I.uses()) {
2348 if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
2349 if (UserPN->getIncomingBlock(U) == BB)
2358 if (UsesToRename.
empty())
2361 LLVM_DEBUG(
dbgs() <<
"JT: Renaming non-local uses of: " <<
I <<
"\n");
2366 SSAUpdate.Initialize(
I.getType(),
I.getName());
2367 SSAUpdate.AddAvailableValue(BB, &
I);
2368 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&
I]);
2370 while (!UsesToRename.
empty())
2377 BB->removePredecessor(PredBB,
true);
2380 OldPredBranch->eraseFromParent();
2381 DDT->applyUpdates(Updates);
2405 CondLHS->getParent() != BB)
2408 for (
unsigned I = 0,
E = CondLHS->getNumIncomingValues();
I !=
E; ++
I) {
2430 CondRHS, Pred, BB, CondCmp);
2433 CondRHS, Pred, BB, CondCmp);
2436 LHSFolds != RHSFolds) {
2447 BB->getParent(), BB);
2494 if (LoopHeaders.count(BB))
2501 [](
Value *V) {
return !isa<ConstantInt>(V); }))
2514 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2517 if (Cmp->getParent() == BB && Cmp->
hasOneUse() &&
2518 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2519 if (
SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2520 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2524 }
else if (
SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2526 if (isUnfoldCandidate(SelectI, U.get())) {
2546 std::vector<DominatorTree::UpdateType> Updates;
2547 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2556 DDT->applyUpdates(Updates);
2604 if (
auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2606 if (
match(&
I, m_Intrinsic<Intrinsic::experimental_guard>()))
2607 if (ThreadGuard(BB, cast<IntrinsicInst>(&
I), BI))
2626 bool TrueDestIsSafe =
false;
2627 bool FalseDestIsSafe =
false;
2632 TrueDestIsSafe =
true;
2637 FalseDestIsSafe =
true;
2640 if (!TrueDestIsSafe && !FalseDestIsSafe)
2643 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2644 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2649 if (Cost > BBDupThreshold)
2654 BB, PredGuardedBlock, AfterGuard, GuardedMapping);
2655 assert(GuardedBlock &&
"Could not create the guarded block?");
2660 BB, PredUnguardedBlock, Guard, UnguardedMapping);
2661 assert(UnguardedBlock &&
"Could not create the unguarded block?");
2663 << GuardedBlock->
getName() <<
"\n");
2680 for (
auto BI = BB->
begin(); &*BI != AfterGuard; ++BI)
2681 if (!isa<PHINode>(&*BI))
2685 assert(InsertionPoint &&
"Empty block?");
2687 for (
auto *Inst :
reverse(ToRemove)) {
2688 if (!Inst->use_empty()) {
2690 NewPN->
addIncoming(UnguardedMapping[Inst], UnguardedBlock);
2691 NewPN->
addIncoming(GuardedMapping[Inst], GuardedBlock);
2693 Inst->replaceAllUsesWith(NewPN);
2695 Inst->eraseFromParent();
Legacy wrapper pass to provide the GlobalsAAResult object.
bool 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...
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...
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
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.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static IntegerType * getInt1Ty(LLVMContext &C)
Helper class for SSA formation on a set of values defined in multiple blocks.
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
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.
Compute iterated dominance frontiers using a linear time algorithm.
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'.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
void initializeJumpThreadingPass(PassRegistry &)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DominatorTree *DT=nullptr)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
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().
const Value * getTrueValue() const
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
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.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass * createJumpThreadingPass(int Threshold=-1)
iterator begin()
Instruction iterator methods.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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, DominatorTree *DT=nullptr, DeferredDominance *DDT=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.
void setName(const Twine &Name)
Change the name of the value.
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.
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
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)
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.
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
bool runImpl(Function &F, TargetLibraryInfo *TLI_, LazyValueInfo *LVI_, AliasAnalysis *AA_, DeferredDominance *DDT_, bool HasProfileData_, std::unique_ptr< BlockFrequencyInfo > BFI_, std::unique_ptr< BranchProbabilityInfo > BPI_)
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...
Value * getOperand(unsigned i) const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
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)
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.
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.
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.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
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.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
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 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...
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
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 aliases.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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 TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
bool ProcessBranchOnPHI(PHINode *PN)
ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on a PHI node in the curren...
bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, Instruction *CxtI=nullptr)
ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see if we can infer that the ...
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.
bool isExceptional() const
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)
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
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...
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)
Class to defer updates to a DominatorTree.
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.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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.
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
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)
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.
void combineMetadataForCSE(Instruction *K, const Instruction *J)
Combine the metadata of two instructions so that K can replace J.
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.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
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)
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
See the comments on JumpThreadingPass.
void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
Delete the specified block, which must have no predecessors.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
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.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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(BasicBlock *BB)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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)
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
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...
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...
This header defines various interfaces for pass management in LLVM.
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 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.
bool hasProfileData() const
Return true if the function is annotated with profile data.
uint32_t getNumerator() const
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.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.