#include "llvm/Transforms/Scalar/GuardWidening.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/GuardUtils.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/GuardUtils.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include <functional>
using namespace llvm;
#define DEBUG_TYPE "guard-widening"
STATISTIC(GuardsEliminated, "Number of eliminated guards");
STATISTIC(CondBranchEliminated, "Number of eliminated conditional branches");
static cl::opt<bool>
WidenBranchGuards("guard-widening-widen-branch-guards", cl::Hidden,
cl::desc("Whether or not we should widen guards "
"expressed as branches by widenable conditions"),
cl::init(true));
namespace {
static Value *getCondition(Instruction *I) {
if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
"Bad guard intrinsic?");
return GI->getArgOperand(0);
}
Value *Cond, *WC;
BasicBlock *IfTrueBB, *IfFalseBB;
if (parseWidenableBranch(I, Cond, WC, IfTrueBB, IfFalseBB))
return Cond;
return cast<BranchInst>(I)->getCondition();
}
static void setCondition(Instruction *I, Value *NewCond) {
if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
"Bad guard intrinsic?");
GI->setArgOperand(0, NewCond);
return;
}
cast<BranchInst>(I)->setCondition(NewCond);
}
static void eliminateGuard(Instruction *GuardInst, MemorySSAUpdater *MSSAU) {
GuardInst->eraseFromParent();
if (MSSAU)
MSSAU->removeMemoryAccess(GuardInst);
++GuardsEliminated;
}
class GuardWideningImpl {
DominatorTree &DT;
PostDominatorTree *PDT;
LoopInfo &LI;
MemorySSAUpdater *MSSAU;
DomTreeNode *Root;
std::function<bool(BasicBlock*)> BlockFilter;
SmallVector<Instruction *, 16> EliminatedGuardsAndBranches;
DenseSet<Instruction *> WidenedGuards;
bool eliminateInstrViaWidening(
Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
GuardsPerBlock, bool InvertCondition = false);
enum WideningScore {
WS_IllegalOrNegative,
WS_Neutral,
WS_Positive,
WS_VeryPositive
};
static StringRef scoreTypeToString(WideningScore WS);
WideningScore computeWideningScore(Instruction *DominatedInstr,
Instruction *DominatingGuard,
bool InvertCond);
bool isAvailableAt(const Value *V, const Instruction *InsertPos) const {
SmallPtrSet<const Instruction *, 8> Visited;
return isAvailableAt(V, InsertPos, Visited);
}
bool isAvailableAt(const Value *V, const Instruction *InsertPos,
SmallPtrSetImpl<const Instruction *> &Visited) const;
void makeAvailableAt(Value *V, Instruction *InsertPos) const;
bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
Value *&Result, bool InvertCondition);
class RangeCheck {
const Value *Base;
const ConstantInt *Offset;
const Value *Length;
ICmpInst *CheckInst;
public:
explicit RangeCheck(const Value *Base, const ConstantInt *Offset,
const Value *Length, ICmpInst *CheckInst)
: Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
void setBase(const Value *NewBase) { Base = NewBase; }
void setOffset(const ConstantInt *NewOffset) { Offset = NewOffset; }
const Value *getBase() const { return Base; }
const ConstantInt *getOffset() const { return Offset; }
const APInt &getOffsetValue() const { return getOffset()->getValue(); }
const Value *getLength() const { return Length; };
ICmpInst *getCheckInst() const { return CheckInst; }
void print(raw_ostream &OS, bool PrintTypes = false) {
OS << "Base: ";
Base->printAsOperand(OS, PrintTypes);
OS << " Offset: ";
Offset->printAsOperand(OS, PrintTypes);
OS << " Length: ";
Length->printAsOperand(OS, PrintTypes);
}
LLVM_DUMP_METHOD void dump() {
print(dbgs());
dbgs() << "\n";
}
};
bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
SmallPtrSet<const Value *, 8> Visited;
return parseRangeChecks(CheckCond, Checks, Visited);
}
bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
SmallPtrSetImpl<const Value *> &Visited);
bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
SmallVectorImpl<RangeCheck> &CombinedChecks) const;
bool isWideningCondProfitable(Value *Cond0, Value *Cond1, bool InvertCond) {
Value *ResultUnused;
return widenCondCommon(Cond0, Cond1, nullptr, ResultUnused,
InvertCond);
}
void widenGuard(Instruction *ToWiden, Value *NewCondition,
bool InvertCondition) {
Value *Result;
widenCondCommon(getCondition(ToWiden), NewCondition, ToWiden, Result,
InvertCondition);
if (isGuardAsWidenableBranch(ToWiden)) {
setWidenableBranchCond(cast<BranchInst>(ToWiden), Result);
return;
}
setCondition(ToWiden, Result);
}
public:
explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
LoopInfo &LI, MemorySSAUpdater *MSSAU,
DomTreeNode *Root,
std::function<bool(BasicBlock*)> BlockFilter)
: DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU), Root(Root),
BlockFilter(BlockFilter) {}
bool run();
};
}
static bool isSupportedGuardInstruction(const Instruction *Insn) {
if (isGuard(Insn))
return true;
if (WidenBranchGuards && isGuardAsWidenableBranch(Insn))
return true;
return false;
}
bool GuardWideningImpl::run() {
DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
bool Changed = false;
for (auto DFI = df_begin(Root), DFE = df_end(Root);
DFI != DFE; ++DFI) {
auto *BB = (*DFI)->getBlock();
if (!BlockFilter(BB))
continue;
auto &CurrentList = GuardsInBlock[BB];
for (auto &I : *BB)
if (isSupportedGuardInstruction(&I))
CurrentList.push_back(cast<Instruction>(&I));
for (auto *II : CurrentList)
Changed |= eliminateInstrViaWidening(II, DFI, GuardsInBlock);
}
assert(EliminatedGuardsAndBranches.empty() || Changed);
for (auto *I : EliminatedGuardsAndBranches)
if (!WidenedGuards.count(I)) {
assert(isa<ConstantInt>(getCondition(I)) && "Should be!");
if (isSupportedGuardInstruction(I))
eliminateGuard(I, MSSAU);
else {
assert(isa<BranchInst>(I) &&
"Eliminated something other than guard or branch?");
++CondBranchEliminated;
}
}
return Changed;
}
bool GuardWideningImpl::eliminateInstrViaWidening(
Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
GuardsInBlock, bool InvertCondition) {
if (isa<ConstantInt>(getCondition(Instr)))
return false;
Instruction *BestSoFar = nullptr;
auto BestScoreSoFar = WS_IllegalOrNegative;
for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
auto *CurBB = DFSI.getPath(i)->getBlock();
if (!BlockFilter(CurBB))
break;
assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
auto I = GuardsInCurBB.begin();
auto E = Instr->getParent() == CurBB ? find(GuardsInCurBB, Instr)
: GuardsInCurBB.end();
#ifndef NDEBUG
{
unsigned Index = 0;
for (auto &I : *CurBB) {
if (Index == GuardsInCurBB.size())
break;
if (GuardsInCurBB[Index] == &I)
Index++;
}
assert(Index == GuardsInCurBB.size() &&
"Guards expected to be in order!");
}
#endif
assert((i == (e - 1)) == (Instr->getParent() == CurBB) && "Bad DFS?");
for (auto *Candidate : make_range(I, E)) {
auto Score = computeWideningScore(Instr, Candidate, InvertCondition);
LLVM_DEBUG(dbgs() << "Score between " << *getCondition(Instr)
<< " and " << *getCondition(Candidate) << " is "
<< scoreTypeToString(Score) << "\n");
if (Score > BestScoreSoFar) {
BestScoreSoFar = Score;
BestSoFar = Candidate;
}
}
}
if (BestScoreSoFar == WS_IllegalOrNegative) {
LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *Instr << "\n");
return false;
}
assert(BestSoFar != Instr && "Should have never visited same guard!");
assert(DT.dominates(BestSoFar, Instr) && "Should be!");
LLVM_DEBUG(dbgs() << "Widening " << *Instr << " into " << *BestSoFar
<< " with score " << scoreTypeToString(BestScoreSoFar)
<< "\n");
widenGuard(BestSoFar, getCondition(Instr), InvertCondition);
auto NewGuardCondition = InvertCondition
? ConstantInt::getFalse(Instr->getContext())
: ConstantInt::getTrue(Instr->getContext());
setCondition(Instr, NewGuardCondition);
EliminatedGuardsAndBranches.push_back(Instr);
WidenedGuards.insert(BestSoFar);
return true;
}
GuardWideningImpl::WideningScore
GuardWideningImpl::computeWideningScore(Instruction *DominatedInstr,
Instruction *DominatingGuard,
bool InvertCond) {
Loop *DominatedInstrLoop = LI.getLoopFor(DominatedInstr->getParent());
Loop *DominatingGuardLoop = LI.getLoopFor(DominatingGuard->getParent());
bool HoistingOutOfLoop = false;
if (DominatingGuardLoop != DominatedInstrLoop) {
if (DominatingGuardLoop &&
!DominatingGuardLoop->contains(DominatedInstrLoop))
return WS_IllegalOrNegative;
HoistingOutOfLoop = true;
}
if (!isAvailableAt(getCondition(DominatedInstr), DominatingGuard))
return WS_IllegalOrNegative;
if (isWideningCondProfitable(getCondition(DominatedInstr),
getCondition(DominatingGuard), InvertCond))
return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
if (HoistingOutOfLoop)
return WS_Positive;
auto MaybeHoistingOutOfIf = [&]() {
auto *DominatingBlock = DominatingGuard->getParent();
auto *DominatedBlock = DominatedInstr->getParent();
if (isGuardAsWidenableBranch(DominatingGuard))
DominatingBlock = cast<BranchInst>(DominatingGuard)->getSuccessor(0);
if (DominatedBlock == DominatingBlock)
return false;
if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
return false;
if (!PDT) return true;
return !PDT->dominates(DominatedBlock, DominatingBlock);
};
return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
}
bool GuardWideningImpl::isAvailableAt(
const Value *V, const Instruction *Loc,
SmallPtrSetImpl<const Instruction *> &Visited) const {
auto *Inst = dyn_cast<Instruction>(V);
if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
return true;
if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
Inst->mayReadFromMemory())
return false;
Visited.insert(Inst);
assert(!isa<PHINode>(Loc) &&
"PHIs should return false for isSafeToSpeculativelyExecute");
assert(DT.isReachableFromEntry(Inst->getParent()) &&
"We did a DFS from the block entry!");
return all_of(Inst->operands(),
[&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
}
void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) const {
auto *Inst = dyn_cast<Instruction>(V);
if (!Inst || DT.dominates(Inst, Loc))
return;
assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
!Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
for (Value *Op : Inst->operands())
makeAvailableAt(Op, Loc);
Inst->moveBefore(Loc);
Inst->dropPoisonGeneratingFlags();
}
bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
Instruction *InsertPt, Value *&Result,
bool InvertCondition) {
using namespace llvm::PatternMatch;
{
ConstantInt *RHS0, *RHS1;
Value *LHS;
ICmpInst::Predicate Pred0, Pred1;
if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
if (InvertCondition)
Pred1 = ICmpInst::getInversePredicate(Pred1);
ConstantRange CR0 =
ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
ConstantRange CR1 =
ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
if (Optional<ConstantRange> Intersect = CR0.exactIntersectWith(CR1)) {
APInt NewRHSAP;
CmpInst::Predicate Pred;
if (Intersect->getEquivalentICmp(Pred, NewRHSAP)) {
if (InsertPt) {
ConstantInt *NewRHS =
ConstantInt::get(Cond0->getContext(), NewRHSAP);
Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
}
return true;
}
}
}
}
{
SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
if (!InvertCondition &&
parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
combineRangeChecks(Checks, CombinedChecks)) {
if (InsertPt) {
Result = nullptr;
for (auto &RC : CombinedChecks) {
makeAvailableAt(RC.getCheckInst(), InsertPt);
if (Result)
Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
InsertPt);
else
Result = RC.getCheckInst();
}
assert(Result && "Failed to find result value");
Result->setName("wide.chk");
}
return true;
}
}
if (InsertPt) {
makeAvailableAt(Cond0, InsertPt);
makeAvailableAt(Cond1, InsertPt);
if (InvertCondition)
Cond1 = BinaryOperator::CreateNot(Cond1, "inverted", InsertPt);
Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
}
return false;
}
bool GuardWideningImpl::parseRangeChecks(
Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
SmallPtrSetImpl<const Value *> &Visited) {
if (!Visited.insert(CheckCond).second)
return true;
using namespace llvm::PatternMatch;
{
Value *AndLHS, *AndRHS;
if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
return parseRangeChecks(AndLHS, Checks) &&
parseRangeChecks(AndRHS, Checks);
}
auto *IC = dyn_cast<ICmpInst>(CheckCond);
if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
(IC->getPredicate() != ICmpInst::ICMP_ULT &&
IC->getPredicate() != ICmpInst::ICMP_UGT))
return false;
const Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
if (IC->getPredicate() == ICmpInst::ICMP_UGT)
std::swap(CmpLHS, CmpRHS);
auto &DL = IC->getModule()->getDataLayout();
GuardWideningImpl::RangeCheck Check(
CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
CmpRHS, IC);
if (!isKnownNonNegative(Check.getLength(), DL))
return false;
bool Changed;
auto &Ctx = CheckCond->getContext();
do {
Value *OpLHS;
ConstantInt *OpRHS;
Changed = false;
#ifndef NDEBUG
auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
"Unreachable instruction?");
#endif
if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
Check.setBase(OpLHS);
APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Changed = true;
} else if (match(Check.getBase(),
m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
KnownBits Known = computeKnownBits(OpLHS, DL);
if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
Check.setBase(OpLHS);
APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Changed = true;
}
}
} while (Changed);
Checks.push_back(Check);
return true;
}
bool GuardWideningImpl::combineRangeChecks(
SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) const {
unsigned OldCount = Checks.size();
while (!Checks.empty()) {
const Value *CurrentBase = Checks.front().getBase();
const Value *CurrentLength = Checks.front().getLength();
SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
};
copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
erase_if(Checks, IsCurrentCheck);
assert(CurrentChecks.size() != 0 && "We know we have at least one!");
if (CurrentChecks.size() < 3) {
llvm::append_range(RangeChecksOut, CurrentChecks);
continue;
}
llvm::sort(CurrentChecks, [&](const GuardWideningImpl::RangeCheck &LHS,
const GuardWideningImpl::RangeCheck &RHS) {
return LHS.getOffsetValue().slt(RHS.getOffsetValue());
});
const ConstantInt *MinOffset = CurrentChecks.front().getOffset();
const ConstantInt *MaxOffset = CurrentChecks.back().getOffset();
unsigned BitWidth = MaxOffset->getValue().getBitWidth();
if ((MaxOffset->getValue() - MinOffset->getValue())
.ugt(APInt::getSignedMinValue(BitWidth)))
return false;
APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
const APInt &HighOffset = MaxOffset->getValue();
auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
};
if (MaxDiff.isMinValue() || !all_of(drop_begin(CurrentChecks), OffsetOK))
return false;
RangeChecksOut.emplace_back(CurrentChecks.front());
RangeChecksOut.emplace_back(CurrentChecks.back());
}
assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
return RangeChecksOut.size() != OldCount;
}
#ifndef NDEBUG
StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
switch (WS) {
case WS_IllegalOrNegative:
return "IllegalOrNegative";
case WS_Neutral:
return "Neutral";
case WS_Positive:
return "Positive";
case WS_VeryPositive:
return "VeryPositive";
}
llvm_unreachable("Fully covered switch above!");
}
#endif
PreservedAnalyses GuardWideningPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
auto *MSSAA = AM.getCachedResult<MemorySSAAnalysis>(F);
std::unique_ptr<MemorySSAUpdater> MSSAU;
if (MSSAA)
MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAA->getMSSA());
if (!GuardWideningImpl(DT, &PDT, LI, MSSAU ? MSSAU.get() : nullptr,
DT.getRootNode(), [](BasicBlock *) { return true; })
.run())
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
PA.preserve<MemorySSAAnalysis>();
return PA;
}
PreservedAnalyses GuardWideningPass::run(Loop &L, LoopAnalysisManager &AM,
LoopStandardAnalysisResults &AR,
LPMUpdater &U) {
BasicBlock *RootBB = L.getLoopPredecessor();
if (!RootBB)
RootBB = L.getHeader();
auto BlockFilter = [&](BasicBlock *BB) {
return BB == RootBB || L.contains(BB);
};
std::unique_ptr<MemorySSAUpdater> MSSAU;
if (AR.MSSA)
MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
if (!GuardWideningImpl(AR.DT, nullptr, AR.LI, MSSAU ? MSSAU.get() : nullptr,
AR.DT.getNode(RootBB), BlockFilter).run())
return PreservedAnalyses::all();
auto PA = getLoopPassPreservedAnalyses();
if (AR.MSSA)
PA.preserve<MemorySSAAnalysis>();
return PA;
}
namespace {
struct GuardWideningLegacyPass : public FunctionPass {
static char ID;
GuardWideningLegacyPass() : FunctionPass(ID) {
initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
std::unique_ptr<MemorySSAUpdater> MSSAU;
if (MSSAWP)
MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA());
return GuardWideningImpl(DT, &PDT, LI, MSSAU ? MSSAU.get() : nullptr,
DT.getRootNode(),
[](BasicBlock *) { return true; })
.run();
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<MemorySSAWrapperPass>();
}
};
struct LoopGuardWideningLegacyPass : public LoopPass {
static char ID;
LoopGuardWideningLegacyPass() : LoopPass(ID) {
initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
if (skipLoop(L))
return false;
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
std::unique_ptr<MemorySSAUpdater> MSSAU;
if (MSSAWP)
MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA());
BasicBlock *RootBB = L->getLoopPredecessor();
if (!RootBB)
RootBB = L->getHeader();
auto BlockFilter = [&](BasicBlock *BB) {
return BB == RootBB || L->contains(BB);
};
return GuardWideningImpl(DT, PDT, LI, MSSAU ? MSSAU.get() : nullptr,
DT.getNode(RootBB), BlockFilter).run();
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
getLoopAnalysisUsage(AU);
AU.addPreserved<PostDominatorTreeWrapperPass>();
AU.addPreserved<MemorySSAWrapperPass>();
}
};
}
char GuardWideningLegacyPass::ID = 0;
char LoopGuardWideningLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
false, false)
INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
"Widen guards (within a single loop, as a loop pass)",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
"Widen guards (within a single loop, as a loop pass)",
false, false)
FunctionPass *llvm::createGuardWideningPass() {
return new GuardWideningLegacyPass();
}
Pass *llvm::createLoopGuardWideningPass() {
return new LoopGuardWideningLegacyPass();
}