#include "llvm/Transforms/Scalar/JumpThreading.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/GuardUtils.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/BlockFrequency.h"
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <memory>
#include <utility>
using namespace llvm;
using namespace jumpthreading;
#define DEBUG_TYPE "jump-threading"
STATISTIC(NumThreads, "Number of jumps threaded");
STATISTIC(NumFolds, "Number of terminators folded");
STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
static cl::opt<unsigned>
BBDuplicateThreshold("jump-threading-threshold",
cl::desc("Max block size to duplicate for jump threading"),
cl::init(6), cl::Hidden);
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);
static cl::opt<bool> PrintLVIAfterJumpThreading(
"print-lvi-after-jump-threading",
cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
cl::Hidden);
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);
namespace {
class JumpThreading : public FunctionPass {
JumpThreadingPass Impl;
public:
static char ID;
JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<LazyValueInfoWrapperPass>();
AU.addPreserved<LazyValueInfoWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
}
void releaseMemory() override { Impl.releaseMemory(); }
};
}
char JumpThreading::ID = 0;
INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
"Jump Threading", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(JumpThreading, "jump-threading",
"Jump Threading", false, false)
FunctionPass *llvm::createJumpThreadingPass(int Threshold) {
return new JumpThreading(Threshold);
}
JumpThreadingPass::JumpThreadingPass(int T) {
DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
}
static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
if (!CondBr)
return;
uint64_t TrueWeight, FalseWeight;
if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight))
return;
if (TrueWeight + FalseWeight == 0)
return;
auto GetPredOutEdge =
[](BasicBlock *IncomingBB,
BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
auto *PredBB = IncomingBB;
auto *SuccBB = PhiBB;
SmallPtrSet<BasicBlock *, 16> Visited;
while (true) {
BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
if (PredBr && PredBr->isConditional())
return {PredBB, SuccBB};
Visited.insert(PredBB);
auto *SinglePredBB = PredBB->getSinglePredecessor();
if (!SinglePredBB)
return {nullptr, nullptr};
if (Visited.count(SinglePredBB))
return {nullptr, nullptr};
SuccBB = PredBB;
PredBB = SinglePredBB;
}
};
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *PhiOpnd = PN->getIncomingValue(i);
ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
if (!CI || !CI->getType()->isIntegerTy(1))
continue;
BranchProbability BP =
(CI->isOne() ? BranchProbability::getBranchProbability(
TrueWeight, TrueWeight + FalseWeight)
: BranchProbability::getBranchProbability(
FalseWeight, TrueWeight + FalseWeight));
auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
if (!PredOutEdge.first)
return;
BasicBlock *PredBB = PredOutEdge.first;
BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
if (!PredBr)
return;
uint64_t PredTrueWeight, PredFalseWeight;
if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight))
continue;
if (BP >= BranchProbability(50, 100))
continue;
SmallVector<uint32_t, 2> Weights;
if (PredBr->getSuccessor(0) == PredOutEdge.second) {
Weights.push_back(BP.getNumerator());
Weights.push_back(BP.getCompl().getNumerator());
} else {
Weights.push_back(BP.getCompl().getNumerator());
Weights.push_back(BP.getNumerator());
}
PredBr->setMetadata(LLVMContext::MD_prof,
MDBuilder(PredBr->getParent()->getContext())
.createBranchWeights(Weights));
}
}
bool JumpThreading::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
auto TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
if (TTI->hasBranchDivergence())
return false;
auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
std::unique_ptr<BlockFrequencyInfo> BFI;
std::unique_ptr<BranchProbabilityInfo> BPI;
if (F.hasProfileData()) {
LoopInfo LI{*DT};
BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
}
bool Changed = Impl.runImpl(F, TLI, TTI, LVI, AA, &DTU, F.hasProfileData(),
std::move(BFI), std::move(BPI));
if (PrintLVIAfterJumpThreading) {
dbgs() << "LVI for function '" << F.getName() << "':\n";
LVI->printLVI(F, DTU.getDomTree(), dbgs());
}
return Changed;
}
PreservedAnalyses JumpThreadingPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
if (TTI.hasBranchDivergence())
return PreservedAnalyses::all();
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &LVI = AM.getResult<LazyValueAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
std::unique_ptr<BlockFrequencyInfo> BFI;
std::unique_ptr<BranchProbabilityInfo> BPI;
if (F.hasProfileData()) {
LoopInfo LI{DominatorTree(F)};
BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
}
bool Changed = runImpl(F, &TLI, &TTI, &LVI, &AA, &DTU, F.hasProfileData(),
std::move(BFI), std::move(BPI));
if (PrintLVIAfterJumpThreading) {
dbgs() << "LVI for function '" << F.getName() << "':\n";
LVI.printLVI(F, DTU.getDomTree(), dbgs());
}
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<DominatorTreeAnalysis>();
PA.preserve<LazyValueAnalysis>();
return PA;
}
bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
AliasAnalysis *AA_, DomTreeUpdater *DTU_,
bool HasProfileData_,
std::unique_ptr<BlockFrequencyInfo> BFI_,
std::unique_ptr<BranchProbabilityInfo> BPI_) {
LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
TLI = TLI_;
TTI = TTI_;
LVI = LVI_;
AA = AA_;
DTU = DTU_;
BFI.reset();
BPI.reset();
HasProfileData = HasProfileData_;
auto *GuardDecl = F.getParent()->getFunction(
Intrinsic::getName(Intrinsic::experimental_guard));
HasGuards = GuardDecl && !GuardDecl->use_empty();
if (HasProfileData) {
BPI = std::move(BPI_);
BFI = std::move(BFI_);
}
if (BBDuplicateThreshold.getNumOccurrences())
BBDupThreshold = BBDuplicateThreshold;
else if (F.hasFnAttribute(Attribute::MinSize))
BBDupThreshold = 3;
else
BBDupThreshold = DefaultBBDupThreshold;
SmallPtrSet<BasicBlock *, 16> Unreachable;
assert(DTU && "DTU isn't passed into JumpThreading before using it.");
assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
DominatorTree &DT = DTU->getDomTree();
for (auto &BB : F)
if (!DT.isReachableFromEntry(&BB))
Unreachable.insert(&BB);
if (!ThreadAcrossLoopHeaders)
findLoopHeaders(F);
bool EverChanged = false;
bool Changed;
do {
Changed = false;
for (auto &BB : F) {
if (Unreachable.count(&BB))
continue;
while (processBlock(&BB)) Changed = true;
if (Changed)
RemoveRedundantDbgInstrs(&BB);
if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
continue;
if (pred_empty(&BB)) {
LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()
<< "' with terminator: " << *BB.getTerminator()
<< '\n');
LoopHeaders.erase(&BB);
LVI->eraseBlock(&BB);
DeleteDeadBlock(&BB, DTU);
Changed = true;
continue;
}
auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
if (BI && BI->isUnconditional()) {
BasicBlock *Succ = BI->getSuccessor(0);
if (
BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
!LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) {
RemoveRedundantDbgInstrs(Succ);
LVI->eraseBlock(&BB);
Changed = true;
}
}
}
EverChanged |= Changed;
} while (Changed);
LoopHeaders.clear();
return EverChanged;
}
static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
BasicBlock *KnownAtEndOfBB) {
bool Changed = false;
assert(Cond->getType() == ToVal->getType());
if (Cond->getParent() == KnownAtEndOfBB)
Changed |= replaceNonLocalUsesWith(Cond, ToVal);
for (Instruction &I : reverse(*KnownAtEndOfBB)) {
if (&I == Cond)
break;
if (!isGuaranteedToTransferExecutionToSuccessor(&I))
break;
Changed |= I.replaceUsesOfWith(Cond, ToVal);
}
if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
Cond->eraseFromParent();
Changed = true;
}
return Changed;
}
static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
BasicBlock *BB,
Instruction *StopAt,
unsigned Threshold) {
assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
BasicBlock::const_iterator I(BB->getFirstNonPHI());
unsigned Bonus = 0;
if (BB->getTerminator() == StopAt) {
if (isa<SwitchInst>(StopAt))
Bonus = 6;
if (isa<IndirectBrInst>(StopAt))
Bonus = 8;
}
Threshold += Bonus;
unsigned Size = 0;
for (; &*I != StopAt; ++I) {
if (Size > Threshold)
return Size;
if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
return ~0U;
if (const CallInst *CI = dyn_cast<CallInst>(I))
if (CI->cannotDuplicate() || CI->isConvergent())
return ~0U;
if (TTI->getUserCost(&*I, TargetTransformInfo::TCK_SizeAndLatency)
== TargetTransformInfo::TCC_Free)
continue;
++Size;
if (const CallInst *CI = dyn_cast<CallInst>(I)) {
if (!isa<IntrinsicInst>(CI))
Size += 3;
else if (!CI->getType()->isVectorTy())
Size += 1;
}
}
return Size > Bonus ? Size - Bonus : 0;
}
void JumpThreadingPass::findLoopHeaders(Function &F) {
SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
FindFunctionBackedges(F, Edges);
for (const auto &Edge : Edges)
LoopHeaders.insert(Edge.second);
}
static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
if (!Val)
return nullptr;
if (UndefValue *U = dyn_cast<UndefValue>(Val))
return U;
if (Preference == WantBlockAddress)
return dyn_cast<BlockAddress>(Val->stripPointerCasts());
return dyn_cast<ConstantInt>(Val);
}
bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
Value *V, BasicBlock *BB, PredValueInfo &Result,
ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
Instruction *CxtI) {
if (!RecursionSet.insert(V).second)
return false;
if (Constant *KC = getKnownConstant(V, Preference)) {
for (BasicBlock *Pred : predecessors(BB))
Result.emplace_back(KC, Pred);
return !Result.empty();
}
Instruction *I = dyn_cast<Instruction>(V);
if (!I || I->getParent() != BB) {
for (BasicBlock *P : predecessors(BB)) {
Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
if (Constant *KC = getKnownConstant(PredCst, Preference))
Result.emplace_back(KC, P);
}
return !Result.empty();
}
if (PHINode *PN = dyn_cast<PHINode>(I)) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *InVal = PN->getIncomingValue(i);
if (Constant *KC = getKnownConstant(InVal, Preference)) {
Result.emplace_back(KC, PN->getIncomingBlock(i));
} else {
Constant *CI = LVI->getConstantOnEdge(InVal,
PN->getIncomingBlock(i),
BB, CxtI);
if (Constant *KC = getKnownConstant(CI, Preference))
Result.emplace_back(KC, PN->getIncomingBlock(i));
}
}
return !Result.empty();
}
if (CastInst *CI = dyn_cast<CastInst>(I)) {
Value *Source = CI->getOperand(0);
computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
RecursionSet, CxtI);
if (Result.empty())
return false;
for (auto &R : Result)
R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
return true;
}
if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
Value *Source = FI->getOperand(0);
computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
RecursionSet, CxtI);
erase_if(Result, [](auto &Pair) {
return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
});
return !Result.empty();
}
if (I->getType()->getPrimitiveSizeInBits() == 1) {
using namespace PatternMatch;
if (Preference != WantInteger)
return false;
Value *Op0, *Op1;
if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
PredValueInfoTy LHSVals, RHSVals;
computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
RecursionSet, CxtI);
computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
RecursionSet, CxtI);
if (LHSVals.empty() && RHSVals.empty())
return false;
ConstantInt *InterestingVal;
if (match(I, m_LogicalOr()))
InterestingVal = ConstantInt::getTrue(I->getContext());
else
InterestingVal = ConstantInt::getFalse(I->getContext());
SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
for (const auto &LHSVal : LHSVals)
if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
Result.emplace_back(InterestingVal, LHSVal.second);
LHSKnownBBs.insert(LHSVal.second);
}
for (const auto &RHSVal : RHSVals)
if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
if (!LHSKnownBBs.count(RHSVal.second))
Result.emplace_back(InterestingVal, RHSVal.second);
}
return !Result.empty();
}
if (I->getOpcode() == Instruction::Xor &&
isa<ConstantInt>(I->getOperand(1)) &&
cast<ConstantInt>(I->getOperand(1))->isOne()) {
computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
WantInteger, RecursionSet, CxtI);
if (Result.empty())
return false;
for (auto &R : Result)
R.first = ConstantExpr::getNot(R.first);
return true;
}
} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
if (Preference != WantInteger)
return false;
if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
const DataLayout &DL = BO->getModule()->getDataLayout();
PredValueInfoTy LHSVals;
computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
WantInteger, RecursionSet, CxtI);
for (const auto &LHSVal : LHSVals) {
Constant *V = LHSVal.first;
Constant *Folded =
ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
if (Constant *KC = getKnownConstant(Folded, WantInteger))
Result.emplace_back(KC, LHSVal.second);
}
}
return !Result.empty();
}
if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
if (Preference != WantInteger)
return false;
Type *CmpType = Cmp->getType();
Value *CmpLHS = Cmp->getOperand(0);
Value *CmpRHS = Cmp->getOperand(1);
CmpInst::Predicate Pred = Cmp->getPredicate();
PHINode *PN = dyn_cast<PHINode>(CmpLHS);
if (!PN)
PN = dyn_cast<PHINode>(CmpRHS);
if (PN && PN->getParent() == BB) {
const DataLayout &DL = PN->getModule()->getDataLayout();
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PredBB = PN->getIncomingBlock(i);
Value *LHS, *RHS;
if (PN == CmpLHS) {
LHS = PN->getIncomingValue(i);
RHS = CmpRHS->DoPHITranslation(BB, PredBB);
} else {
LHS = CmpLHS->DoPHITranslation(BB, PredBB);
RHS = PN->getIncomingValue(i);
}
Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
if (!Res) {
if (!isa<Constant>(RHS))
continue;
auto LHSInst = dyn_cast<Instruction>(LHS);
if (LHSInst && LHSInst->getParent() == BB)
continue;
LazyValueInfo::Tristate
ResT = LVI->getPredicateOnEdge(Pred, LHS,
cast<Constant>(RHS), PredBB, BB,
CxtI ? CxtI : Cmp);
if (ResT == LazyValueInfo::Unknown)
continue;
Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
}
if (Constant *KC = getKnownConstant(Res, WantInteger))
Result.emplace_back(KC, PredBB);
}
return !Result.empty();
}
if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
Constant *CmpConst = cast<Constant>(CmpRHS);
if (!isa<Instruction>(CmpLHS) ||
cast<Instruction>(CmpLHS)->getParent() != BB) {
for (BasicBlock *P : predecessors(BB)) {
LazyValueInfo::Tristate Res =
LVI->getPredicateOnEdge(Pred, CmpLHS,
CmpConst, P, BB, CxtI ? CxtI : Cmp);
if (Res == LazyValueInfo::Unknown)
continue;
Constant *ResC = ConstantInt::get(CmpType, Res);
Result.emplace_back(ResC, P);
}
return !Result.empty();
}
{
using namespace PatternMatch;
Value *AddLHS;
ConstantInt *AddConst;
if (isa<ConstantInt>(CmpConst) &&
match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
if (!isa<Instruction>(AddLHS) ||
cast<Instruction>(AddLHS)->getParent() != BB) {
for (BasicBlock *P : predecessors(BB)) {
ConstantRange CR = LVI->getConstantRangeOnEdge(
AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
CR = CR.add(AddConst->getValue());
ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
Pred, cast<ConstantInt>(CmpConst)->getValue());
Constant *ResC;
if (CmpRange.contains(CR))
ResC = ConstantInt::getTrue(CmpType);
else if (CmpRange.inverse().contains(CR))
ResC = ConstantInt::getFalse(CmpType);
else
continue;
Result.emplace_back(ResC, P);
}
return !Result.empty();
}
}
}
PredValueInfoTy LHSVals;
computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
WantInteger, RecursionSet, CxtI);
for (const auto &LHSVal : LHSVals) {
Constant *V = LHSVal.first;
Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
if (Constant *KC = getKnownConstant(Folded, WantInteger))
Result.emplace_back(KC, LHSVal.second);
}
return !Result.empty();
}
}
if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
PredValueInfoTy Conds;
if ((TrueVal || FalseVal) &&
computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
WantInteger, RecursionSet, CxtI)) {
for (auto &C : Conds) {
Constant *Cond = C.first;
bool KnownCond;
if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
KnownCond = CI->isOne();
} else {
assert(isa<UndefValue>(Cond) && "Unexpected condition value");
KnownCond = (TrueVal != nullptr);
}
if (Constant *Val = KnownCond ? TrueVal : FalseVal)
Result.emplace_back(Val, C.second);
}
return !Result.empty();
}
}
assert(CxtI->getParent() == BB && "CxtI should be in BB");
Constant *CI = LVI->getConstant(V, CxtI);
if (Constant *KC = getKnownConstant(CI, Preference)) {
for (BasicBlock *Pred : predecessors(BB))
Result.emplace_back(KC, Pred);
}
return !Result.empty();
}
static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
Instruction *BBTerm = BB->getTerminator();
unsigned MinSucc = 0;
BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
unsigned MinNumPreds = pred_size(TestBB);
for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
TestBB = BBTerm->getSuccessor(i);
unsigned NumPreds = pred_size(TestBB);
if (NumPreds < MinNumPreds) {
MinSucc = i;
MinNumPreds = NumPreds;
}
}
return MinSucc;
}
static bool hasAddressTakenAndUsed(BasicBlock *BB) {
if (!BB->hasAddressTaken()) return false;
BlockAddress *BA = BlockAddress::get(BB);
BA->removeDeadConstantUsers();
return !BA->use_empty();
}
bool JumpThreadingPass::processBlock(BasicBlock *BB) {
if (DTU->isBBPendingDeletion(BB) ||
(pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
return false;
if (maybeMergeBasicBlockIntoOnlyPred(BB))
return true;
if (tryToUnfoldSelectInCurrBB(BB))
return true;
if (HasGuards && processGuards(BB))
return true;
ConstantPreference Preference = WantInteger;
Value *Condition;
Instruction *Terminator = BB->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
if (BI->isUnconditional()) return false;
Condition = BI->getCondition();
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
Condition = SI->getCondition();
} else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
if (IB->getNumSuccessors() == 0) return false;
Condition = IB->getAddress()->stripPointerCasts();
Preference = WantBlockAddress;
} else {
return false; }
bool ConstantFolded = false;
if (Instruction *I = dyn_cast<Instruction>(Condition)) {
Value *SimpleVal =
ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
if (SimpleVal) {
I->replaceAllUsesWith(SimpleVal);
if (isInstructionTriviallyDead(I, TLI))
I->eraseFromParent();
Condition = SimpleVal;
ConstantFolded = true;
}
}
auto *FI = dyn_cast<FreezeInst>(Condition);
if (isa<UndefValue>(Condition) ||
(FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
unsigned BestSucc = getBestDestForJumpOnUndef(BB);
std::vector<DominatorTree::UpdateType> Updates;
Instruction *BBTerm = BB->getTerminator();
Updates.reserve(BBTerm->getNumSuccessors());
for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
if (i == BestSucc) continue;
BasicBlock *Succ = BBTerm->getSuccessor(i);
Succ->removePredecessor(BB, true);
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
<< "' folding undef terminator: " << *BBTerm << '\n');
BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
++NumFolds;
BBTerm->eraseFromParent();
DTU->applyUpdatesPermissive(Updates);
if (FI)
FI->eraseFromParent();
return true;
}
if (getKnownConstant(Condition, Preference)) {
LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
<< "' folding terminator: " << *BB->getTerminator()
<< '\n');
++NumFolds;
ConstantFoldTerminator(BB, true, nullptr, DTU);
if (HasProfileData)
BPI->eraseBlock(BB);
return true;
}
Instruction *CondInst = dyn_cast<Instruction>(Condition);
if (!CondInst) {
if (processThreadableEdges(Condition, BB, Preference, Terminator))
return true;
return ConstantFolded;
}
Value *CondWithoutFreeze = CondInst;
if (auto *FI = dyn_cast<FreezeInst>(CondInst))
CondWithoutFreeze = FI->getOperand(0);
if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) {
if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) {
LazyValueInfo::Tristate Ret =
LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
CondConst, BB->getTerminator(),
false);
if (Ret != LazyValueInfo::Unknown) {
auto *CI = Ret == LazyValueInfo::True ?
ConstantInt::getTrue(CondCmp->getType()) :
ConstantInt::getFalse(CondCmp->getType());
if (replaceFoldableUses(CondCmp, CI, BB))
return true;
}
if (tryToUnfoldSelect(CondCmp, BB))
return true;
}
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
if (tryToUnfoldSelect(SI, BB))
return true;
Value *SimplifyValue = CondWithoutFreeze;
if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
if (isa<Constant>(CondCmp->getOperand(1)))
SimplifyValue = CondCmp->getOperand(0);
if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
if (simplifyPartiallyRedundantLoad(LoadI))
return true;
if (PHINode *PN = dyn_cast<PHINode>(CondInst))
if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
updatePredecessorProfileMetadata(PN, BB);
if (processThreadableEdges(CondInst, BB, Preference, Terminator))
return true;
PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze);
if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
return processBranchOnPHI(PN);
if (CondInst->getOpcode() == Instruction::Xor &&
CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
return processBranchOnXOR(cast<BinaryOperator>(CondInst));
if (processImpliedCondition(BB))
return true;
return false;
}
bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
if (!BI || !BI->isConditional())
return false;
Value *Cond = BI->getCondition();
auto *FICond = dyn_cast<FreezeInst>(Cond);
if (FICond && FICond->hasOneUse())
Cond = FICond->getOperand(0);
else
FICond = nullptr;
BasicBlock *CurrentBB = BB;
BasicBlock *CurrentPred = BB->getSinglePredecessor();
unsigned Iter = 0;
auto &DL = BB->getModule()->getDataLayout();
while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
if (!PBI || !PBI->isConditional())
return false;
if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
return false;
bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
Optional<bool> Implication =
isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) {
if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
FICond->getOperand(0))
Implication = CondIsTrue;
}
if (Implication) {
BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
RemoveSucc->removePredecessor(BB);
BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
UncondBI->setDebugLoc(BI->getDebugLoc());
++NumFolds;
BI->eraseFromParent();
if (FICond)
FICond->eraseFromParent();
DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
if (HasProfileData)
BPI->eraseBlock(BB);
return true;
}
CurrentBB = CurrentPred;
CurrentPred = CurrentBB->getSinglePredecessor();
}
return false;
}
static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
if (Instruction *OpInst = dyn_cast<Instruction>(Op))
if (OpInst->getParent() == BB)
return true;
return false;
}
bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
if (!LoadI->isUnordered()) return false;
BasicBlock *LoadBB = LoadI->getParent();
if (LoadBB->getSinglePredecessor())
return false;
if (LoadBB->isEHPad())
return false;
Value *LoadedPtr = LoadI->getOperand(0);
if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
return false;
BasicBlock::iterator BBIt(LoadI);
bool IsLoadCSE;
if (Value *AvailableVal = FindAvailableLoadedValue(
LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
if (IsLoadCSE) {
LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
combineMetadataForCSE(NLoadI, LoadI, false);
};
if (AvailableVal == LoadI)
AvailableVal = PoisonValue::get(LoadI->getType());
if (AvailableVal->getType() != LoadI->getType())
AvailableVal = CastInst::CreateBitOrPointerCast(
AvailableVal, LoadI->getType(), "", LoadI);
LoadI->replaceAllUsesWith(AvailableVal);
LoadI->eraseFromParent();
return true;
}
if (BBIt != LoadBB->begin())
return false;
AAMDNodes AATags = LoadI->getAAMetadata();
SmallPtrSet<BasicBlock*, 8> PredsScanned;
using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
AvailablePredsTy AvailablePreds;
BasicBlock *OneUnavailablePred = nullptr;
SmallVector<LoadInst*, 8> CSELoads;
for (BasicBlock *PredBB : predecessors(LoadBB)) {
if (!PredsScanned.insert(PredBB).second)
continue;
BBIt = PredBB->end();
unsigned NumScanedInst = 0;
Value *PredAvailable = nullptr;
assert(LoadI->isUnordered() &&
"Attempting to CSE volatile or atomic loads");
Type *AccessTy = LoadI->getType();
const auto &DL = LoadI->getModule()->getDataLayout();
MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
AATags);
PredAvailable = findAvailablePtrLoadStore(Loc, AccessTy, LoadI->isAtomic(),
PredBB, BBIt, DefMaxInstsToScan,
AA, &IsLoadCSE, &NumScanedInst);
BasicBlock *SinglePredBB = PredBB;
while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
NumScanedInst < DefMaxInstsToScan) {
SinglePredBB = SinglePredBB->getSinglePredecessor();
if (SinglePredBB) {
BBIt = SinglePredBB->end();
PredAvailable = findAvailablePtrLoadStore(
Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
(DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
&NumScanedInst);
}
}
if (!PredAvailable) {
OneUnavailablePred = PredBB;
continue;
}
if (IsLoadCSE)
CSELoads.push_back(cast<LoadInst>(PredAvailable));
AvailablePreds.emplace_back(PredBB, PredAvailable);
}
if (AvailablePreds.empty()) return false;
BasicBlock *UnavailablePred = nullptr;
if (PredsScanned.size() != AvailablePreds.size() &&
!isSafeToSpeculativelyExecute(LoadI))
for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
return false;
if (PredsScanned.size() == AvailablePreds.size()+1 &&
OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
UnavailablePred = OneUnavailablePred;
} else if (PredsScanned.size() != AvailablePreds.size()) {
SmallVector<BasicBlock*, 8> PredsToSplit;
SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
for (const auto &AvailablePred : AvailablePreds)
AvailablePredSet.insert(AvailablePred.first);
for (BasicBlock *P : predecessors(LoadBB)) {
if (isa<IndirectBrInst>(P->getTerminator()))
return false;
if (!AvailablePredSet.count(P))
PredsToSplit.push_back(P);
}
UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
}
if (UnavailablePred) {
assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
"Can't handle critical edge here!");
LoadInst *NewVal = new LoadInst(
LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
LoadI->getName() + ".pr", false, LoadI->getAlign(),
LoadI->getOrdering(), LoadI->getSyncScopeID(),
UnavailablePred->getTerminator());
NewVal->setDebugLoc(LoadI->getDebugLoc());
if (AATags)
NewVal->setAAMetadata(AATags);
AvailablePreds.emplace_back(UnavailablePred, NewVal);
}
array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
&LoadBB->front());
PN->takeName(LoadI);
PN->setDebugLoc(LoadI->getDebugLoc());
for (pred_iterator PI = PB; PI != PE; ++PI) {
BasicBlock *P = *PI;
AvailablePredsTy::iterator I =
llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
assert(I != AvailablePreds.end() && I->first == P &&
"Didn't find entry for predecessor!");
Value *&PredV = I->second;
if (PredV->getType() != LoadI->getType())
PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
P->getTerminator());
PN->addIncoming(PredV, I->first);
}
for (LoadInst *PredLoadI : CSELoads) {
combineMetadataForCSE(PredLoadI, LoadI, true);
}
LoadI->replaceAllUsesWith(PN);
LoadI->eraseFromParent();
return true;
}
static BasicBlock *
findMostPopularDest(BasicBlock *BB,
const SmallVectorImpl<std::pair<BasicBlock *,
BasicBlock *>> &PredToDestList) {
assert(!PredToDestList.empty());
MapVector<BasicBlock *, unsigned> DestPopularity;
DestPopularity[nullptr] = 0;
for (auto *SuccBB : successors(BB))
DestPopularity[SuccBB] = 0;
for (const auto &PredToDest : PredToDestList)
if (PredToDest.second)
DestPopularity[PredToDest.second]++;
auto MostPopular = std::max_element(
DestPopularity.begin(), DestPopularity.end(), llvm::less_second());
return MostPopular->first;
}
Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
BasicBlock *PredPredBB,
Value *V) {
BasicBlock *PredBB = BB->getSinglePredecessor();
assert(PredBB && "Expected a single predecessor");
if (Constant *Cst = dyn_cast<Constant>(V)) {
return Cst;
}
Instruction *I = dyn_cast<Instruction>(V);
if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
}
if (PHINode *PHI = dyn_cast<PHINode>(V)) {
if (PHI->getParent() == PredBB)
return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
return nullptr;
}
if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
if (CondCmp->getParent() == BB) {
Constant *Op0 =
evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
Constant *Op1 =
evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
if (Op0 && Op1) {
return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
}
}
return nullptr;
}
return nullptr;
}
bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
ConstantPreference Preference,
Instruction *CxtI) {
if (LoopHeaders.count(BB))
return false;
PredValueInfoTy PredValues;
if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
CxtI)) {
return maybethreadThroughTwoBasicBlocks(BB, Cond);
}
assert(!PredValues.empty() &&
"computeValueKnownInPredecessors returned true with no values");
LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) {
dbgs() << " BB '" << BB->getName()
<< "': FOUND condition = " << *PredValue.first
<< " for pred '" << PredValue.second->getName() << "'.\n";
});
SmallPtrSet<BasicBlock*, 16> SeenPreds;
SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
BasicBlock *OnlyDest = nullptr;
BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
Constant *OnlyVal = nullptr;
Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
for (const auto &PredValue : PredValues) {
BasicBlock *Pred = PredValue.second;
if (!SeenPreds.insert(Pred).second)
continue;
Constant *Val = PredValue.first;
BasicBlock *DestBB;
if (isa<UndefValue>(Val))
DestBB = nullptr;
else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
} else {
assert(isa<IndirectBrInst>(BB->getTerminator())
&& "Unexpected terminator");
assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
DestBB = cast<BlockAddress>(Val)->getBasicBlock();
}
if (PredToDestList.empty()) {
OnlyDest = DestBB;
OnlyVal = Val;
} else {
if (OnlyDest != DestBB)
OnlyDest = MultipleDestSentinel;
if (Val != OnlyVal)
OnlyVal = MultipleVal;
}
if (isa<IndirectBrInst>(Pred->getTerminator()))
continue;
PredToDestList.emplace_back(Pred, DestBB);
}
if (PredToDestList.empty())
return false;
if (OnlyDest && OnlyDest != MultipleDestSentinel) {
if (BB->hasNPredecessors(PredToDestList.size())) {
bool SeenFirstBranchToOnlyDest = false;
std::vector <DominatorTree::UpdateType> Updates;
Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
for (BasicBlock *SuccBB : successors(BB)) {
if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
SeenFirstBranchToOnlyDest = true; } else {
SuccBB->removePredecessor(BB, true); Updates.push_back({DominatorTree::Delete, BB, SuccBB});
}
}
Instruction *Term = BB->getTerminator();
BranchInst::Create(OnlyDest, Term);
++NumFolds;
Term->eraseFromParent();
DTU->applyUpdatesPermissive(Updates);
if (HasProfileData)
BPI->eraseBlock(BB);
if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
CondInst->eraseFromParent();
else if (OnlyVal && OnlyVal != MultipleVal)
replaceFoldableUses(CondInst, OnlyVal, BB);
}
return true;
}
}
BasicBlock *MostPopularDest = OnlyDest;
if (MostPopularDest == MultipleDestSentinel) {
erase_if(PredToDestList,
[&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
return LoopHeaders.contains(PredToDest.second);
});
if (PredToDestList.empty())
return false;
MostPopularDest = findMostPopularDest(BB, PredToDestList);
}
SmallVector<BasicBlock*, 16> PredsToFactor;
for (const auto &PredToDest : PredToDestList)
if (PredToDest.second == MostPopularDest) {
BasicBlock *Pred = PredToDest.first;
for (BasicBlock *Succ : successors(Pred))
if (Succ == BB)
PredsToFactor.push_back(Pred);
}
if (!MostPopularDest)
MostPopularDest = BB->getTerminator()->
getSuccessor(getBestDestForJumpOnUndef(BB));
return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
}
bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
BasicBlock *BB = PN->getParent();
SmallVector<BasicBlock*, 1> PredBBs;
PredBBs.resize(1);
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PredBB = PN->getIncomingBlock(i);
if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
if (PredBr->isUnconditional()) {
PredBBs[0] = PredBB;
if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
return true;
}
}
return false;
}
bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
BasicBlock *BB = BO->getParent();
if (isa<ConstantInt>(BO->getOperand(0)) ||
isa<ConstantInt>(BO->getOperand(1)))
return false;
if (!isa<PHINode>(BB->front()))
return false;
if (BB->isEHPad())
return false;
PredValueInfoTy XorOpValues;
bool isLHS = true;
if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
WantInteger, BO)) {
assert(XorOpValues.empty());
if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
WantInteger, BO))
return false;
isLHS = false;
}
assert(!XorOpValues.empty() &&
"computeValueKnownInPredecessors returned true with no values");
unsigned NumTrue = 0, NumFalse = 0;
for (const auto &XorOpValue : XorOpValues) {
if (isa<UndefValue>(XorOpValue.first))
continue;
if (cast<ConstantInt>(XorOpValue.first)->isZero())
++NumFalse;
else
++NumTrue;
}
ConstantInt *SplitVal = nullptr;
if (NumTrue > NumFalse)
SplitVal = ConstantInt::getTrue(BB->getContext());
else if (NumTrue != 0 || NumFalse != 0)
SplitVal = ConstantInt::getFalse(BB->getContext());
SmallVector<BasicBlock*, 8> BlocksToFoldInto;
for (const auto &XorOpValue : XorOpValues) {
if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
continue;
BlocksToFoldInto.push_back(XorOpValue.second);
}
if (BlocksToFoldInto.size() ==
cast<PHINode>(BB->front()).getNumIncomingValues()) {
if (!SplitVal) {
BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
BO->eraseFromParent();
} else if (SplitVal->isZero()) {
BO->replaceAllUsesWith(BO->getOperand(isLHS));
BO->eraseFromParent();
} else {
BO->setOperand(!isLHS, SplitVal);
}
return true;
}
if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
return isa<IndirectBrInst>(Pred->getTerminator());
}))
return false;
return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
}
static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
BasicBlock *OldPred,
BasicBlock *NewPred,
DenseMap<Instruction*, Value*> &ValueMap) {
for (PHINode &PN : PHIBB->phis()) {
Value *IV = PN.getIncomingValueForBlock(OldPred);
if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
if (I != ValueMap.end())
IV = I->second;
}
PN.addIncoming(IV, NewPred);
}
}
bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
BasicBlock *SinglePred = BB->getSinglePredecessor();
if (!SinglePred)
return false;
const Instruction *TI = SinglePred->getTerminator();
if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
SinglePred == BB || hasAddressTakenAndUsed(BB))
return false;
if (LoopHeaders.erase(SinglePred))
LoopHeaders.insert(BB);
LVI->eraseBlock(SinglePred);
MergeBasicBlockIntoOnlyPred(BB, DTU);
if (!isGuaranteedToTransferExecutionToSuccessor(BB))
LVI->eraseBlock(BB);
return true;
}
void JumpThreadingPass::updateSSA(
BasicBlock *BB, BasicBlock *NewBB,
DenseMap<Instruction *, Value *> &ValueMapping) {
SSAUpdater SSAUpdate;
SmallVector<Use *, 16> UsesToRename;
for (Instruction &I : *BB) {
for (Use &U : I.uses()) {
Instruction *User = cast<Instruction>(U.getUser());
if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
if (UserPN->getIncomingBlock(U) == BB)
continue;
} else if (User->getParent() == BB)
continue;
UsesToRename.push_back(&U);
}
if (UsesToRename.empty())
continue;
LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
SSAUpdate.Initialize(I.getType(), I.getName());
SSAUpdate.AddAvailableValue(BB, &I);
SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
while (!UsesToRename.empty())
SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
LLVM_DEBUG(dbgs() << "\n");
}
}
DenseMap<Instruction *, Value *>
JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI,
BasicBlock::iterator BE, BasicBlock *NewBB,
BasicBlock *PredBB) {
DenseMap<Instruction *, Value *> ValueMapping;
for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
ValueMapping[PN] = NewPN;
}
SmallVector<MDNode *> NoAliasScopes;
DenseMap<MDNode *, MDNode *> ClonedScopes;
LLVMContext &Context = PredBB->getContext();
identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
for (; BI != BE; ++BI) {
Instruction *New = BI->clone();
New->setName(BI->getName());
NewBB->getInstList().push_back(New);
ValueMapping[&*BI] = New;
adaptNoAliasScopes(New, ClonedScopes, Context);
for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
if (I != ValueMapping.end())
New->setOperand(i, I->second);
}
}
return ValueMapping;
}
bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
Value *Cond) {
BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
if (!CondBr)
return false;
BasicBlock *PredBB = BB->getSinglePredecessor();
if (!PredBB)
return false;
BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
if (!PredBBBranch || PredBBBranch->isUnconditional())
return false;
if (PredBB->getSinglePredecessor())
return false;
if (llvm::is_contained(successors(PredBB), PredBB))
return false;
if (LoopHeaders.count(PredBB))
return false;
if (PredBB->isEHPad())
return false;
unsigned ZeroCount = 0;
unsigned OneCount = 0;
BasicBlock *ZeroPred = nullptr;
BasicBlock *OnePred = nullptr;
for (BasicBlock *P : predecessors(PredBB)) {
if (isa<IndirectBrInst>(P->getTerminator()))
continue;
if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
evaluateOnPredecessorEdge(BB, P, Cond))) {
if (CI->isZero()) {
ZeroCount++;
ZeroPred = P;
} else if (CI->isOne()) {
OneCount++;
OnePred = P;
}
}
}
BasicBlock *PredPredBB;
if (ZeroCount == 1) {
PredPredBB = ZeroPred;
} else if (OneCount == 1) {
PredPredBB = OnePred;
} else {
return false;
}
BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
if (SuccBB == BB) {
LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
<< "' - would thread to self!\n");
return false;
}
if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
LLVM_DEBUG({
bool BBIsHeader = LoopHeaders.count(BB);
bool SuccIsHeader = LoopHeaders.count(SuccBB);
dbgs() << " Not threading across "
<< (BBIsHeader ? "loop header BB '" : "block BB '")
<< BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '")
<< SuccBB->getName()
<< "' - it might create an irreducible loop!\n";
});
return false;
}
unsigned BBCost = getJumpThreadDuplicationCost(
TTI, BB, BB->getTerminator(), BBDupThreshold);
unsigned PredBBCost = getJumpThreadDuplicationCost(
TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
BBCost + PredBBCost > BBDupThreshold) {
LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
<< "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n");
return false;
}
threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
return true;
}
void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
BasicBlock *PredBB,
BasicBlock *BB,
BasicBlock *SuccBB) {
LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"
<< BB->getName() << "'\n");
BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
BasicBlock *NewBB =
BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
PredBB->getParent(), PredBB);
NewBB->moveAfter(PredBB);
if (HasProfileData) {
auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
BPI->getEdgeProbability(PredPredBB, PredBB);
BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
}
DenseMap<Instruction *, Value *> ValueMapping =
cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
if (HasProfileData)
BPI->copyEdgeProbabilities(PredBB, NewBB);
Instruction *PredPredTerm = PredPredBB->getTerminator();
for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
if (PredPredTerm->getSuccessor(i) == PredBB) {
PredBB->removePredecessor(PredPredBB, true);
PredPredTerm->setSuccessor(i, NewBB);
}
addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
ValueMapping);
addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
ValueMapping);
DTU->applyUpdatesPermissive(
{{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
{DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
{DominatorTree::Insert, PredPredBB, NewBB},
{DominatorTree::Delete, PredPredBB, PredBB}});
updateSSA(PredBB, NewBB, ValueMapping);
SimplifyInstructionsInBlock(NewBB, TLI);
SimplifyInstructionsInBlock(PredBB, TLI);
SmallVector<BasicBlock *, 1> PredsToFactor;
PredsToFactor.push_back(NewBB);
threadEdge(BB, PredsToFactor, SuccBB);
}
bool JumpThreadingPass::tryThreadEdge(
BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
BasicBlock *SuccBB) {
if (SuccBB == BB) {
LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
<< "' - would thread to self!\n");
return false;
}
if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
LLVM_DEBUG({
bool BBIsHeader = LoopHeaders.count(BB);
bool SuccIsHeader = LoopHeaders.count(SuccBB);
dbgs() << " Not threading across "
<< (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
<< "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
<< SuccBB->getName() << "' - it might create an irreducible loop!\n";
});
return false;
}
unsigned JumpThreadCost = getJumpThreadDuplicationCost(
TTI, BB, BB->getTerminator(), BBDupThreshold);
if (JumpThreadCost > BBDupThreshold) {
LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
<< "' - Cost is too high: " << JumpThreadCost << "\n");
return false;
}
threadEdge(BB, PredBBs, SuccBB);
return true;
}
void JumpThreadingPass::threadEdge(BasicBlock *BB,
const SmallVectorImpl<BasicBlock *> &PredBBs,
BasicBlock *SuccBB) {
assert(SuccBB != BB && "Don't create an infinite loop");
assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
"Don't thread across loop headers");
BasicBlock *PredBB;
if (PredBBs.size() == 1)
PredBB = PredBBs[0];
else {
LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
<< " common predecessors.\n");
PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
}
LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()
<< "' to '" << SuccBB->getName()
<< ", across block:\n " << *BB << "\n");
LVI->threadEdge(PredBB, BB, SuccBB);
BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
BB->getName()+".thread",
BB->getParent(), BB);
NewBB->moveAfter(PredBB);
if (HasProfileData) {
auto NewBBFreq =
BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
}
DenseMap<Instruction *, Value *> ValueMapping =
cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Instruction *PredTerm = PredBB->getTerminator();
for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
if (PredTerm->getSuccessor(i) == BB) {
BB->removePredecessor(PredBB, true);
PredTerm->setSuccessor(i, NewBB);
}
DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
{DominatorTree::Insert, PredBB, NewBB},
{DominatorTree::Delete, PredBB, BB}});
updateSSA(BB, NewBB, ValueMapping);
SimplifyInstructionsInBlock(NewBB, TLI);
updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
++NumThreads;
}
BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
ArrayRef<BasicBlock *> Preds,
const char *Suffix) {
SmallVector<BasicBlock *, 2> NewBBs;
DenseMap<BasicBlock *, BlockFrequency> FreqMap;
if (HasProfileData)
for (auto Pred : Preds)
FreqMap.insert(std::make_pair(
Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
if (BB->isLandingPad()) {
std::string NewName = std::string(Suffix) + ".split-lp";
SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
} else {
NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
}
std::vector<DominatorTree::UpdateType> Updates;
Updates.reserve((2 * Preds.size()) + NewBBs.size());
for (auto NewBB : NewBBs) {
BlockFrequency NewBBFreq(0);
Updates.push_back({DominatorTree::Insert, NewBB, BB});
for (auto Pred : predecessors(NewBB)) {
Updates.push_back({DominatorTree::Delete, Pred, BB});
Updates.push_back({DominatorTree::Insert, Pred, NewBB});
if (HasProfileData) NewBBFreq += FreqMap.lookup(Pred);
}
if (HasProfileData) BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
}
DTU->applyUpdatesPermissive(Updates);
return NewBBs[0];
}
bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
const Instruction *TI = BB->getTerminator();
assert(TI->getNumSuccessors() > 1 && "not a split");
MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
if (!WeightsNode)
return false;
MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
if (MDName->getString() != "branch_weights")
return false;
return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
}
void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
BasicBlock *BB,
BasicBlock *NewBB,
BasicBlock *SuccBB) {
if (!HasProfileData)
return;
assert(BFI && BPI && "BFI & BPI should have been created here");
auto BBOrigFreq = BFI->getBlockFreq(BB);
auto NewBBFreq = BFI->getBlockFreq(NewBB);
auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
auto BBNewFreq = BBOrigFreq - NewBBFreq;
BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
SmallVector<uint64_t, 4> BBSuccFreq;
for (BasicBlock *Succ : successors(BB)) {
auto SuccFreq = (Succ == SuccBB)
? BB2SuccBBFreq - NewBBFreq
: BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
BBSuccFreq.push_back(SuccFreq.getFrequency());
}
uint64_t MaxBBSuccFreq =
*std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
SmallVector<BranchProbability, 4> BBSuccProbs;
if (MaxBBSuccFreq == 0)
BBSuccProbs.assign(BBSuccFreq.size(),
{1, static_cast<unsigned>(BBSuccFreq.size())});
else {
for (uint64_t Freq : BBSuccFreq)
BBSuccProbs.push_back(
BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
BBSuccProbs.end());
}
BPI->setEdgeProbability(BB, BBSuccProbs);
if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
SmallVector<uint32_t, 4> Weights;
for (auto Prob : BBSuccProbs)
Weights.push_back(Prob.getNumerator());
auto TI = BB->getTerminator();
TI->setMetadata(
LLVMContext::MD_prof,
MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
}
}
bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
assert(!PredBBs.empty() && "Can't handle an empty set");
if (LoopHeaders.count(BB)) {
LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
<< "' into predecessor block '" << PredBBs[0]->getName()
<< "' - it might create an irreducible loop!\n");
return false;
}
unsigned DuplicationCost = getJumpThreadDuplicationCost(
TTI, BB, BB->getTerminator(), BBDupThreshold);
if (DuplicationCost > BBDupThreshold) {
LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
<< "' - Cost is too high: " << DuplicationCost << "\n");
return false;
}
std::vector<DominatorTree::UpdateType> Updates;
BasicBlock *PredBB;
if (PredBBs.size() == 1)
PredBB = PredBBs[0];
else {
LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
<< " common predecessors.\n");
PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
}
Updates.push_back({DominatorTree::Delete, PredBB, BB});
LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()
<< "' into end of '" << PredBB->getName()
<< "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB << "\n");
BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
BasicBlock *OldPredBB = PredBB;
PredBB = SplitEdge(OldPredBB, BB);
Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
Updates.push_back({DominatorTree::Insert, PredBB, BB});
Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
}
DenseMap<Instruction*, Value*> ValueMapping;
BasicBlock::iterator BI = BB->begin();
for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
for (; BI != BB->end(); ++BI) {
Instruction *New = BI->clone();
for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
if (I != ValueMapping.end())
New->setOperand(i, I->second);
}
if (Value *IV = simplifyInstruction(
New,
{BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
ValueMapping[&*BI] = IV;
if (!New->mayHaveSideEffects()) {
New->deleteValue();
New = nullptr;
}
} else {
ValueMapping[&*BI] = New;
}
if (New) {
New->setName(BI->getName());
PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
}
}
BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
ValueMapping);
addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
ValueMapping);
updateSSA(BB, PredBB, ValueMapping);
BB->removePredecessor(PredBB, true);
OldPredBranch->eraseFromParent();
if (HasProfileData)
BPI->copyEdgeProbabilities(BB, PredBB);
DTU->applyUpdatesPermissive(Updates);
++NumDupes;
return true;
}
void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
SelectInst *SI, PHINode *SIUse,
unsigned Idx) {
BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
BB->getParent(), BB);
PredTerm->removeFromParent();
NewBB->getInstList().insert(NewBB->end(), PredTerm);
auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
SIUse->setIncomingValue(Idx, SI->getFalseValue());
SIUse->addIncoming(SI->getTrueValue(), NewBB);
SI->eraseFromParent();
DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
{DominatorTree::Insert, Pred, NewBB}});
for (BasicBlock::iterator BI = BB->begin();
PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
if (Phi != SIUse)
Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
}
bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
if (!CondPHI || CondPHI->getParent() != BB)
return false;
for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
BasicBlock *Pred = CondPHI->getIncomingBlock(I);
SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
continue;
BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
if (!PredTerm || !PredTerm->isUnconditional())
continue;
unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
return true;
}
return false;
}
bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
if (!CondBr || !CondBr->isConditional() || !CondLHS ||
CondLHS->getParent() != BB)
return false;
for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
BasicBlock *Pred = CondLHS->getIncomingBlock(I);
SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
continue;
BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
if (!PredTerm || !PredTerm->isUnconditional())
continue;
LazyValueInfo::Tristate LHSFolds =
LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
CondRHS, Pred, BB, CondCmp);
LazyValueInfo::Tristate RHSFolds =
LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
CondRHS, Pred, BB, CondCmp);
if ((LHSFolds != LazyValueInfo::Unknown ||
RHSFolds != LazyValueInfo::Unknown) &&
LHSFolds != RHSFolds) {
unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
return true;
}
}
return false;
}
bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
return false;
if (LoopHeaders.count(BB))
return false;
for (BasicBlock::iterator BI = BB->begin();
PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
if (llvm::all_of(PN->incoming_values(),
[](Value *V) { return !isa<ConstantInt>(V); }))
continue;
auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
using namespace PatternMatch;
if (SI->getParent() != BB)
return false;
Value *Cond = SI->getCondition();
bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
};
SelectInst *SI = nullptr;
for (Use &U : PN->uses()) {
if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
SI = SelectI;
break;
}
} else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
if (isUnfoldCandidate(SelectI, U.get())) {
SI = SelectI;
break;
}
}
}
if (!SI)
continue;
Value *Cond = SI->getCondition();
if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI))
Cond = new FreezeInst(Cond, "cond.fr", SI);
Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false);
BasicBlock *SplitBB = SI->getParent();
BasicBlock *NewBB = Term->getParent();
PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
NewPN->addIncoming(SI->getFalseValue(), BB);
SI->replaceAllUsesWith(NewPN);
SI->eraseFromParent();
std::vector<DominatorTree::UpdateType> Updates;
Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
Updates.push_back({DominatorTree::Insert, BB, SplitBB});
Updates.push_back({DominatorTree::Insert, BB, NewBB});
Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
for (auto *Succ : successors(SplitBB)) {
Updates.push_back({DominatorTree::Delete, BB, Succ});
Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
}
DTU->applyUpdatesPermissive(Updates);
return true;
}
return false;
}
bool JumpThreadingPass::processGuards(BasicBlock *BB) {
using namespace PatternMatch;
BasicBlock *Pred1, *Pred2;
auto PI = pred_begin(BB), PE = pred_end(BB);
if (PI == PE)
return false;
Pred1 = *PI++;
if (PI == PE)
return false;
Pred2 = *PI++;
if (PI != PE)
return false;
if (Pred1 == Pred2)
return false;
auto *Parent = Pred1->getSinglePredecessor();
if (!Parent || Parent != Pred2->getSinglePredecessor())
return false;
if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
for (auto &I : *BB)
if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
return true;
return false;
}
bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
BranchInst *BI) {
assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
assert(BI->isConditional() && "Unconditional branch has 2 successors?");
Value *GuardCond = Guard->getArgOperand(0);
Value *BranchCond = BI->getCondition();
BasicBlock *TrueDest = BI->getSuccessor(0);
BasicBlock *FalseDest = BI->getSuccessor(1);
auto &DL = BB->getModule()->getDataLayout();
bool TrueDestIsSafe = false;
bool FalseDestIsSafe = false;
auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
if (Impl && *Impl)
TrueDestIsSafe = true;
else {
Impl = isImpliedCondition(BranchCond, GuardCond, DL, false);
if (Impl && *Impl)
FalseDestIsSafe = true;
}
if (!TrueDestIsSafe && !FalseDestIsSafe)
return false;
BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
ValueToValueMapTy UnguardedMapping, GuardedMapping;
Instruction *AfterGuard = Guard->getNextNode();
unsigned Cost =
getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
if (Cost > BBDupThreshold)
return false;
BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
assert(GuardedBlock && "Could not create the guarded block?");
BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
assert(UnguardedBlock && "Could not create the unguarded block?");
LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
<< GuardedBlock->getName() << "\n");
SmallVector<Instruction *, 4> ToRemove;
for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
if (!isa<PHINode>(&*BI))
ToRemove.push_back(&*BI);
Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
assert(InsertionPoint && "Empty block?");
for (auto *Inst : reverse(ToRemove)) {
if (!Inst->use_empty()) {
PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
NewPN->insertBefore(InsertionPoint);
Inst->replaceAllUsesWith(NewPN);
}
Inst->eraseFromParent();
}
return true;
}