#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumeBundleQueries.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/InstructionPrecedenceTracking.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/PHITransAddr.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.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/LLVMContext.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/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Transforms/Utils/VNCoercion.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <utility>
using namespace llvm;
using namespace llvm::gvn;
using namespace llvm::VNCoercion;
using namespace PatternMatch;
#define DEBUG_TYPE "gvn"
STATISTIC(NumGVNInstr, "Number of instructions deleted");
STATISTIC(NumGVNLoad, "Number of loads deleted");
STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
STATISTIC(NumGVNBlocks, "Number of blocks merged");
STATISTIC(NumGVNSimpl, "Number of instructions simplified");
STATISTIC(NumGVNEqProp, "Number of equalities propagated");
STATISTIC(NumPRELoad, "Number of loads PRE'd");
STATISTIC(NumPRELoopLoad, "Number of loop loads PRE'd");
STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
"Number of blocks speculated as available in "
"IsValueFullyAvailableInBlock(), max");
STATISTIC(MaxBBSpeculationCutoffReachedTimes,
"Number of times we we reached gvn-max-block-speculations cut-off "
"preventing further exploration");
static cl::opt<bool> GVNEnablePRE("enable-pre", cl::init(true), cl::Hidden);
static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true));
static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre",
cl::init(true));
static cl::opt<bool>
GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre",
cl::init(false));
static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true));
static cl::opt<uint32_t> MaxNumDeps(
"gvn-max-num-deps", cl::Hidden, cl::init(100),
cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
static cl::opt<uint32_t> MaxBBSpeculations(
"gvn-max-block-speculations", cl::Hidden, cl::init(600),
cl::desc("Max number of blocks we're willing to speculate on (and recurse "
"into) when deducing if a value is fully available or not in GVN "
"(default = 600)"));
struct llvm::GVNPass::Expression {
uint32_t opcode;
bool commutative = false;
Type *type = nullptr;
SmallVector<uint32_t, 4> varargs;
Expression(uint32_t o = ~2U) : opcode(o) {}
bool operator==(const Expression &other) const {
if (opcode != other.opcode)
return false;
if (opcode == ~0U || opcode == ~1U)
return true;
if (type != other.type)
return false;
if (varargs != other.varargs)
return false;
return true;
}
friend hash_code hash_value(const Expression &Value) {
return hash_combine(
Value.opcode, Value.type,
hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
}
};
namespace llvm {
template <> struct DenseMapInfo<GVNPass::Expression> {
static inline GVNPass::Expression getEmptyKey() { return ~0U; }
static inline GVNPass::Expression getTombstoneKey() { return ~1U; }
static unsigned getHashValue(const GVNPass::Expression &e) {
using llvm::hash_value;
return static_cast<unsigned>(hash_value(e));
}
static bool isEqual(const GVNPass::Expression &LHS,
const GVNPass::Expression &RHS) {
return LHS == RHS;
}
};
}
struct llvm::gvn::AvailableValue {
enum class ValType {
SimpleVal, LoadVal, MemIntrin, UndefVal, SelectVal, };
Value *Val;
ValType Kind;
unsigned Offset = 0;
static AvailableValue get(Value *V, unsigned Offset = 0) {
AvailableValue Res;
Res.Val = V;
Res.Kind = ValType::SimpleVal;
Res.Offset = Offset;
return Res;
}
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
AvailableValue Res;
Res.Val = MI;
Res.Kind = ValType::MemIntrin;
Res.Offset = Offset;
return Res;
}
static AvailableValue getLoad(LoadInst *Load, unsigned Offset = 0) {
AvailableValue Res;
Res.Val = Load;
Res.Kind = ValType::LoadVal;
Res.Offset = Offset;
return Res;
}
static AvailableValue getUndef() {
AvailableValue Res;
Res.Val = nullptr;
Res.Kind = ValType::UndefVal;
Res.Offset = 0;
return Res;
}
static AvailableValue getSelect(SelectInst *Sel) {
AvailableValue Res;
Res.Val = Sel;
Res.Kind = ValType::SelectVal;
Res.Offset = 0;
return Res;
}
bool isSimpleValue() const { return Kind == ValType::SimpleVal; }
bool isCoercedLoadValue() const { return Kind == ValType::LoadVal; }
bool isMemIntrinValue() const { return Kind == ValType::MemIntrin; }
bool isUndefValue() const { return Kind == ValType::UndefVal; }
bool isSelectValue() const { return Kind == ValType::SelectVal; }
Value *getSimpleValue() const {
assert(isSimpleValue() && "Wrong accessor");
return Val;
}
LoadInst *getCoercedLoadValue() const {
assert(isCoercedLoadValue() && "Wrong accessor");
return cast<LoadInst>(Val);
}
MemIntrinsic *getMemIntrinValue() const {
assert(isMemIntrinValue() && "Wrong accessor");
return cast<MemIntrinsic>(Val);
}
SelectInst *getSelectValue() const {
assert(isSelectValue() && "Wrong accessor");
return cast<SelectInst>(Val);
}
Value *MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt,
GVNPass &gvn) const;
};
struct llvm::gvn::AvailableValueInBlock {
BasicBlock *BB = nullptr;
AvailableValue AV;
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
AvailableValueInBlock Res;
Res.BB = BB;
Res.AV = std::move(AV);
return Res;
}
static AvailableValueInBlock get(BasicBlock *BB, Value *V,
unsigned Offset = 0) {
return get(BB, AvailableValue::get(V, Offset));
}
static AvailableValueInBlock getUndef(BasicBlock *BB) {
return get(BB, AvailableValue::getUndef());
}
static AvailableValueInBlock getSelect(BasicBlock *BB, SelectInst *Sel) {
return get(BB, AvailableValue::getSelect(Sel));
}
Value *MaterializeAdjustedValue(LoadInst *Load, GVNPass &gvn) const {
return AV.MaterializeAdjustedValue(Load, BB->getTerminator(), gvn);
}
};
GVNPass::Expression GVNPass::ValueTable::createExpr(Instruction *I) {
Expression e;
e.type = I->getType();
e.opcode = I->getOpcode();
if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(I)) {
e.varargs.push_back(lookupOrAdd(GCR->getOperand(0)));
e.varargs.push_back(lookupOrAdd(GCR->getBasePtr()));
e.varargs.push_back(lookupOrAdd(GCR->getDerivedPtr()));
} else {
for (Use &Op : I->operands())
e.varargs.push_back(lookupOrAdd(Op));
}
if (I->isCommutative()) {
assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!");
if (e.varargs[0] > e.varargs[1])
std::swap(e.varargs[0], e.varargs[1]);
e.commutative = true;
}
if (auto *C = dyn_cast<CmpInst>(I)) {
CmpInst::Predicate Predicate = C->getPredicate();
if (e.varargs[0] > e.varargs[1]) {
std::swap(e.varargs[0], e.varargs[1]);
Predicate = CmpInst::getSwappedPredicate(Predicate);
}
e.opcode = (C->getOpcode() << 8) | Predicate;
e.commutative = true;
} else if (auto *E = dyn_cast<InsertValueInst>(I)) {
e.varargs.append(E->idx_begin(), E->idx_end());
} else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
ArrayRef<int> ShuffleMask = SVI->getShuffleMask();
e.varargs.append(ShuffleMask.begin(), ShuffleMask.end());
}
return e;
}
GVNPass::Expression GVNPass::ValueTable::createCmpExpr(
unsigned Opcode, CmpInst::Predicate Predicate, Value *LHS, Value *RHS) {
assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
"Not a comparison!");
Expression e;
e.type = CmpInst::makeCmpResultType(LHS->getType());
e.varargs.push_back(lookupOrAdd(LHS));
e.varargs.push_back(lookupOrAdd(RHS));
if (e.varargs[0] > e.varargs[1]) {
std::swap(e.varargs[0], e.varargs[1]);
Predicate = CmpInst::getSwappedPredicate(Predicate);
}
e.opcode = (Opcode << 8) | Predicate;
e.commutative = true;
return e;
}
GVNPass::Expression
GVNPass::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
assert(EI && "Not an ExtractValueInst?");
Expression e;
e.type = EI->getType();
e.opcode = 0;
WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
e.opcode = WO->getBinaryOp();
e.varargs.push_back(lookupOrAdd(WO->getLHS()));
e.varargs.push_back(lookupOrAdd(WO->getRHS()));
return e;
}
e.opcode = EI->getOpcode();
for (Use &Op : EI->operands())
e.varargs.push_back(lookupOrAdd(Op));
append_range(e.varargs, EI->indices());
return e;
}
GVNPass::Expression GVNPass::ValueTable::createGEPExpr(GetElementPtrInst *GEP) {
Expression E;
Type *PtrTy = GEP->getType()->getScalarType();
const DataLayout &DL = GEP->getModule()->getDataLayout();
unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
MapVector<Value *, APInt> VariableOffsets;
APInt ConstantOffset(BitWidth, 0);
if (PtrTy->isOpaquePointerTy() &&
GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) {
LLVMContext &Context = GEP->getContext();
E.opcode = GEP->getOpcode();
E.type = nullptr;
E.varargs.push_back(lookupOrAdd(GEP->getPointerOperand()));
for (const auto &Pair : VariableOffsets) {
E.varargs.push_back(lookupOrAdd(Pair.first));
E.varargs.push_back(lookupOrAdd(ConstantInt::get(Context, Pair.second)));
}
if (!ConstantOffset.isZero())
E.varargs.push_back(
lookupOrAdd(ConstantInt::get(Context, ConstantOffset)));
} else {
E.opcode = GEP->getOpcode();
E.type = GEP->getSourceElementType();
for (Use &Op : GEP->operands())
E.varargs.push_back(lookupOrAdd(Op));
}
return E;
}
GVNPass::ValueTable::ValueTable() = default;
GVNPass::ValueTable::ValueTable(const ValueTable &) = default;
GVNPass::ValueTable::ValueTable(ValueTable &&) = default;
GVNPass::ValueTable::~ValueTable() = default;
GVNPass::ValueTable &
GVNPass::ValueTable::operator=(const GVNPass::ValueTable &Arg) = default;
void GVNPass::ValueTable::add(Value *V, uint32_t num) {
valueNumbering.insert(std::make_pair(V, num));
if (PHINode *PN = dyn_cast<PHINode>(V))
NumberingPhi[num] = PN;
}
uint32_t GVNPass::ValueTable::lookupOrAddCall(CallInst *C) {
if (AA->doesNotAccessMemory(C)) {
Expression exp = createExpr(C);
uint32_t e = assignExpNewValueNum(exp).first;
valueNumbering[C] = e;
return e;
} else if (MD && AA->onlyReadsMemory(C)) {
Expression exp = createExpr(C);
auto ValNum = assignExpNewValueNum(exp);
if (ValNum.second) {
valueNumbering[C] = ValNum.first;
return ValNum.first;
}
MemDepResult local_dep = MD->getDependency(C);
if (!local_dep.isDef() && !local_dep.isNonLocal()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
if (local_dep.isDef()) {
CallInst *local_cdep = dyn_cast<CallInst>(local_dep.getInst());
if (!local_cdep || local_cdep->arg_size() != C->arg_size()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
for (unsigned i = 0, e = C->arg_size(); i < e; ++i) {
uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
if (c_vn != cd_vn) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
uint32_t v = lookupOrAdd(local_cdep);
valueNumbering[C] = v;
return v;
}
const MemoryDependenceResults::NonLocalDepInfo &deps =
MD->getNonLocalCallDependency(C);
CallInst* cdep = nullptr;
for (unsigned i = 0, e = deps.size(); i != e; ++i) {
const NonLocalDepEntry *I = &deps[i];
if (I->getResult().isNonLocal())
continue;
if (!I->getResult().isDef() || cdep != nullptr) {
cdep = nullptr;
break;
}
CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
cdep = NonLocalDepCall;
continue;
}
cdep = nullptr;
break;
}
if (!cdep) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
if (cdep->arg_size() != C->arg_size()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
for (unsigned i = 0, e = C->arg_size(); i < e; ++i) {
uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
if (c_vn != cd_vn) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
uint32_t v = lookupOrAdd(cdep);
valueNumbering[C] = v;
return v;
} else {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
bool GVNPass::ValueTable::exists(Value *V) const {
return valueNumbering.count(V) != 0;
}
uint32_t GVNPass::ValueTable::lookupOrAdd(Value *V) {
DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
if (VI != valueNumbering.end())
return VI->second;
if (!isa<Instruction>(V)) {
valueNumbering[V] = nextValueNumber;
return nextValueNumber++;
}
Instruction* I = cast<Instruction>(V);
Expression exp;
switch (I->getOpcode()) {
case Instruction::Call:
return lookupOrAddCall(cast<CallInst>(I));
case Instruction::FNeg:
case Instruction::Add:
case Instruction::FAdd:
case Instruction::Sub:
case Instruction::FSub:
case Instruction::Mul:
case Instruction::FMul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::FDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::FRem:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::ICmp:
case Instruction::FCmp:
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::AddrSpaceCast:
case Instruction::BitCast:
case Instruction::Select:
case Instruction::Freeze:
case Instruction::ExtractElement:
case Instruction::InsertElement:
case Instruction::ShuffleVector:
case Instruction::InsertValue:
exp = createExpr(I);
break;
case Instruction::GetElementPtr:
exp = createGEPExpr(cast<GetElementPtrInst>(I));
break;
case Instruction::ExtractValue:
exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
break;
case Instruction::PHI:
valueNumbering[V] = nextValueNumber;
NumberingPhi[nextValueNumber] = cast<PHINode>(V);
return nextValueNumber++;
default:
valueNumbering[V] = nextValueNumber;
return nextValueNumber++;
}
uint32_t e = assignExpNewValueNum(exp).first;
valueNumbering[V] = e;
return e;
}
uint32_t GVNPass::ValueTable::lookup(Value *V, bool Verify) const {
DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
if (Verify) {
assert(VI != valueNumbering.end() && "Value not numbered?");
return VI->second;
}
return (VI != valueNumbering.end()) ? VI->second : 0;
}
uint32_t GVNPass::ValueTable::lookupOrAddCmp(unsigned Opcode,
CmpInst::Predicate Predicate,
Value *LHS, Value *RHS) {
Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
return assignExpNewValueNum(exp).first;
}
void GVNPass::ValueTable::clear() {
valueNumbering.clear();
expressionNumbering.clear();
NumberingPhi.clear();
PhiTranslateTable.clear();
nextValueNumber = 1;
Expressions.clear();
ExprIdx.clear();
nextExprNumber = 0;
}
void GVNPass::ValueTable::erase(Value *V) {
uint32_t Num = valueNumbering.lookup(V);
valueNumbering.erase(V);
if (isa<PHINode>(V))
NumberingPhi.erase(Num);
}
void GVNPass::ValueTable::verifyRemoved(const Value *V) const {
for (DenseMap<Value*, uint32_t>::const_iterator
I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
assert(I->first != V && "Inst still occurs in value numbering map!");
}
}
bool GVNPass::isPREEnabled() const {
return Options.AllowPRE.value_or(GVNEnablePRE);
}
bool GVNPass::isLoadPREEnabled() const {
return Options.AllowLoadPRE.value_or(GVNEnableLoadPRE);
}
bool GVNPass::isLoadInLoopPREEnabled() const {
return Options.AllowLoadInLoopPRE.value_or(GVNEnableLoadInLoopPRE);
}
bool GVNPass::isLoadPRESplitBackedgeEnabled() const {
return Options.AllowLoadPRESplitBackedge.value_or(
GVNEnableSplitBackedgeInLoadPRE);
}
bool GVNPass::isMemDepEnabled() const {
return Options.AllowMemDep.value_or(GVNEnableMemDep);
}
PreservedAnalyses GVNPass::run(Function &F, FunctionAnalysisManager &AM) {
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
auto *MemDep =
isMemDepEnabled() ? &AM.getResult<MemoryDependenceAnalysis>(F) : nullptr;
auto *LI = AM.getCachedResult<LoopAnalysis>(F);
auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F);
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
bool Changed = runImpl(F, AC, DT, TLI, AA, MemDep, LI, &ORE,
MSSA ? &MSSA->getMSSA() : nullptr);
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<DominatorTreeAnalysis>();
PA.preserve<TargetLibraryAnalysis>();
if (MSSA)
PA.preserve<MemorySSAAnalysis>();
if (LI)
PA.preserve<LoopAnalysis>();
return PA;
}
void GVNPass::printPipeline(
raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
static_cast<PassInfoMixin<GVNPass> *>(this)->printPipeline(
OS, MapClassName2PassName);
OS << "<";
if (Options.AllowPRE != None)
OS << (Options.AllowPRE.value() ? "" : "no-") << "pre;";
if (Options.AllowLoadPRE != None)
OS << (Options.AllowLoadPRE.value() ? "" : "no-") << "load-pre;";
if (Options.AllowLoadPRESplitBackedge != None)
OS << (Options.AllowLoadPRESplitBackedge.value() ? "" : "no-")
<< "split-backedge-load-pre;";
if (Options.AllowMemDep != None)
OS << (Options.AllowMemDep.value() ? "" : "no-") << "memdep";
OS << ">";
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void GVNPass::dump(DenseMap<uint32_t, Value *> &d) const {
errs() << "{\n";
for (auto &I : d) {
errs() << I.first << "\n";
I.second->dump();
}
errs() << "}\n";
}
#endif
enum class AvailabilityState : char {
Unavailable = 0,
Available = 1,
SpeculativelyAvailable = 2,
};
static bool IsValueFullyAvailableInBlock(
BasicBlock *BB,
DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) {
SmallVector<BasicBlock *, 32> Worklist;
Optional<BasicBlock *> UnavailableBB;
unsigned NumNewNewSpeculativelyAvailableBBs = 0;
#ifndef NDEBUG
SmallSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs;
SmallVector<BasicBlock *, 32> AvailableBBs;
#endif
Worklist.emplace_back(BB);
while (!Worklist.empty()) {
BasicBlock *CurrBB = Worklist.pop_back_val(); std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV =
FullyAvailableBlocks.try_emplace(
CurrBB, AvailabilityState::SpeculativelyAvailable);
AvailabilityState &State = IV.first->second;
if (!IV.second) {
if (State == AvailabilityState::Unavailable) {
UnavailableBB = CurrBB;
break; }
#ifndef NDEBUG
AvailableBBs.emplace_back(CurrBB);
#endif
continue; }
++NumNewNewSpeculativelyAvailableBBs;
bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations;
if (OutOfBudget || pred_empty(CurrBB)) {
MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
State = AvailabilityState::Unavailable;
UnavailableBB = CurrBB;
break; }
#ifndef NDEBUG
NewSpeculativelyAvailableBBs.insert(CurrBB);
#endif
Worklist.append(pred_begin(CurrBB), pred_end(CurrBB));
}
#if LLVM_ENABLE_STATS
IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
NumNewNewSpeculativelyAvailableBBs);
#endif
auto MarkAsFixpointAndEnqueueSuccessors =
[&](BasicBlock *BB, AvailabilityState FixpointState) {
auto It = FullyAvailableBlocks.find(BB);
if (It == FullyAvailableBlocks.end())
return; switch (AvailabilityState &State = It->second) {
case AvailabilityState::Unavailable:
case AvailabilityState::Available:
return; case AvailabilityState::SpeculativelyAvailable: State = FixpointState;
#ifndef NDEBUG
assert(NewSpeculativelyAvailableBBs.erase(BB) &&
"Found a speculatively available successor leftover?");
#endif
Worklist.append(succ_begin(BB), succ_end(BB));
return;
}
};
if (UnavailableBB) {
Worklist.clear();
Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB));
while (!Worklist.empty())
MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
AvailabilityState::Unavailable);
}
#ifndef NDEBUG
Worklist.clear();
for (BasicBlock *AvailableBB : AvailableBBs)
Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB));
while (!Worklist.empty())
MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
AvailabilityState::Available);
assert(NewSpeculativelyAvailableBBs.empty() &&
"Must have fixed all the new speculatively available blocks.");
#endif
return !UnavailableBB;
}
static Value *
ConstructSSAForLoadSet(LoadInst *Load,
SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
GVNPass &gvn) {
if (ValuesPerBlock.size() == 1 &&
gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
Load->getParent())) {
assert(!ValuesPerBlock[0].AV.isUndefValue() &&
"Dead BB dominate this block");
return ValuesPerBlock[0].MaterializeAdjustedValue(Load, gvn);
}
SmallVector<PHINode*, 8> NewPHIs;
SSAUpdater SSAUpdate(&NewPHIs);
SSAUpdate.Initialize(Load->getType(), Load->getName());
for (const AvailableValueInBlock &AV : ValuesPerBlock) {
BasicBlock *BB = AV.BB;
if (AV.AV.isUndefValue())
continue;
if (SSAUpdate.HasValueForBlock(BB))
continue;
if (BB == Load->getParent() &&
((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == Load) ||
(AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == Load)))
continue;
SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(Load, gvn));
}
return SSAUpdate.GetValueInMiddleOfBlock(Load->getParent());
}
static LoadInst *findDominatingLoad(Value *Ptr, Type *LoadTy, SelectInst *Sel,
DominatorTree &DT) {
for (Value *U : Ptr->users()) {
auto *LI = dyn_cast<LoadInst>(U);
if (LI && LI->getType() == LoadTy && LI->getParent() == Sel->getParent() &&
DT.dominates(LI, Sel))
return LI;
}
return nullptr;
}
Value *AvailableValue::MaterializeAdjustedValue(LoadInst *Load,
Instruction *InsertPt,
GVNPass &gvn) const {
Value *Res;
Type *LoadTy = Load->getType();
const DataLayout &DL = Load->getModule()->getDataLayout();
if (isSimpleValue()) {
Res = getSimpleValue();
if (Res->getType() != LoadTy) {
Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
<< " " << *getSimpleValue() << '\n'
<< *Res << '\n'
<< "\n\n\n");
}
} else if (isCoercedLoadValue()) {
LoadInst *CoercedLoad = getCoercedLoadValue();
if (CoercedLoad->getType() == LoadTy && Offset == 0) {
Res = CoercedLoad;
} else {
Res = getLoadValueForLoad(CoercedLoad, Offset, LoadTy, InsertPt, DL);
gvn.getMemDep().removeInstruction(CoercedLoad);
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
<< " " << *getCoercedLoadValue() << '\n'
<< *Res << '\n'
<< "\n\n\n");
}
} else if (isMemIntrinValue()) {
Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
InsertPt, DL);
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
<< " " << *getMemIntrinValue() << '\n'
<< *Res << '\n'
<< "\n\n\n");
} else if (isSelectValue()) {
SelectInst *Sel = getSelectValue();
LoadInst *L1 = findDominatingLoad(Sel->getOperand(1), LoadTy, Sel,
gvn.getDominatorTree());
LoadInst *L2 = findDominatingLoad(Sel->getOperand(2), LoadTy, Sel,
gvn.getDominatorTree());
assert(L1 && L2 &&
"must be able to obtain dominating loads for both value operands of "
"the select");
Res = SelectInst::Create(Sel->getCondition(), L1, L2, "", Sel);
} else {
llvm_unreachable("Should not materialize value from dead block");
}
assert(Res && "failed to materialize?");
return Res;
}
static bool isLifetimeStart(const Instruction *Inst) {
if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
return II->getIntrinsicID() == Intrinsic::lifetime_start;
return false;
}
static bool liesBetween(const Instruction *From, Instruction *Between,
const Instruction *To, DominatorTree *DT) {
if (From->getParent() == Between->getParent())
return DT->dominates(From, Between);
SmallSet<BasicBlock *, 1> Exclusion;
Exclusion.insert(Between->getParent());
return !isPotentiallyReachable(From, To, &Exclusion, DT);
}
static void reportMayClobberedLoad(LoadInst *Load, MemDepResult DepInfo,
DominatorTree *DT,
OptimizationRemarkEmitter *ORE) {
using namespace ore;
User *OtherAccess = nullptr;
OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", Load);
R << "load of type " << NV("Type", Load->getType()) << " not eliminated"
<< setExtraArgs();
for (auto *U : Load->getPointerOperand()->users()) {
if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
cast<Instruction>(U)->getFunction() == Load->getFunction() &&
DT->dominates(cast<Instruction>(U), Load)) {
if (OtherAccess) {
if (DT->dominates(cast<Instruction>(OtherAccess), cast<Instruction>(U)))
OtherAccess = U;
else
assert(U == OtherAccess || DT->dominates(cast<Instruction>(U),
cast<Instruction>(OtherAccess)));
} else
OtherAccess = U;
}
}
if (!OtherAccess) {
for (auto *U : Load->getPointerOperand()->users()) {
if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
cast<Instruction>(U)->getFunction() == Load->getFunction() &&
isPotentiallyReachable(cast<Instruction>(U), Load, nullptr, DT)) {
if (OtherAccess) {
if (liesBetween(cast<Instruction>(OtherAccess), cast<Instruction>(U),
Load, DT)) {
OtherAccess = U;
} else if (!liesBetween(cast<Instruction>(U),
cast<Instruction>(OtherAccess), Load, DT)) {
OtherAccess = nullptr;
break;
} } else {
OtherAccess = U;
}
}
}
}
if (OtherAccess)
R << " in favor of " << NV("OtherAccess", OtherAccess);
R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
ORE->emit(R);
}
static Optional<AvailableValue>
tryToConvertLoadOfPtrSelect(BasicBlock *DepBB, BasicBlock::iterator End,
Value *Address, Type *LoadTy, DominatorTree &DT,
AAResults *AA) {
auto *Sel = dyn_cast_or_null<SelectInst>(Address);
if (!Sel || DepBB != Sel->getParent())
return None;
LoadInst *L1 = findDominatingLoad(Sel->getOperand(1), LoadTy, Sel, DT);
LoadInst *L2 = findDominatingLoad(Sel->getOperand(2), LoadTy, Sel, DT);
if (!L1 || !L2)
return None;
Instruction *EarlierLoad = L1->comesBefore(L2) ? L1 : L2;
MemoryLocation L1Loc = MemoryLocation::get(L1);
MemoryLocation L2Loc = MemoryLocation::get(L2);
if (any_of(make_range(EarlierLoad->getIterator(), End), [&](Instruction &I) {
return isModSet(AA->getModRefInfo(&I, L1Loc)) ||
isModSet(AA->getModRefInfo(&I, L2Loc));
}))
return None;
return AvailableValue::getSelect(Sel);
}
bool GVNPass::AnalyzeLoadAvailability(LoadInst *Load, MemDepResult DepInfo,
Value *Address, AvailableValue &Res) {
if (!DepInfo.isDef() && !DepInfo.isClobber()) {
assert(isa<SelectInst>(Address));
if (auto R = tryToConvertLoadOfPtrSelect(
Load->getParent(), Load->getIterator(), Address, Load->getType(),
getDominatorTree(), getAliasAnalysis())) {
Res = *R;
return true;
}
return false;
}
assert((DepInfo.isDef() || DepInfo.isClobber()) &&
"expected a local dependence");
assert(Load->isUnordered() && "rules below are incorrect for ordered access");
const DataLayout &DL = Load->getModule()->getDataLayout();
Instruction *DepInst = DepInfo.getInst();
if (DepInfo.isClobber()) {
if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
if (Address && Load->isAtomic() <= DepSI->isAtomic()) {
int Offset =
analyzeLoadFromClobberingStore(Load->getType(), Address, DepSI, DL);
if (Offset != -1) {
Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
return true;
}
}
}
if (LoadInst *DepLoad = dyn_cast<LoadInst>(DepInst)) {
if (DepLoad != Load && Address &&
Load->isAtomic() <= DepLoad->isAtomic()) {
Type *LoadType = Load->getType();
int Offset = -1;
if (DepInfo.isClobber() &&
canCoerceMustAliasedValueToLoad(DepLoad, LoadType, DL)) {
const auto ClobberOff = MD->getClobberOffset(DepLoad);
Offset = (ClobberOff == None || *ClobberOff < 0) ? -1 : *ClobberOff;
}
if (Offset == -1)
Offset =
analyzeLoadFromClobberingLoad(LoadType, Address, DepLoad, DL);
if (Offset != -1) {
Res = AvailableValue::getLoad(DepLoad, Offset);
return true;
}
}
}
if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
if (Address && !Load->isAtomic()) {
int Offset = analyzeLoadFromClobberingMemInst(Load->getType(), Address,
DepMI, DL);
if (Offset != -1) {
Res = AvailableValue::getMI(DepMI, Offset);
return true;
}
}
}
LLVM_DEBUG(
dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
dbgs() << " is clobbered by " << *DepInst << '\n';);
if (ORE->allowExtraAnalysis(DEBUG_TYPE))
reportMayClobberedLoad(Load, DepInfo, DT, ORE);
return false;
}
assert(DepInfo.isDef() && "follows from above");
if (isa<AllocaInst>(DepInst) || isLifetimeStart(DepInst)) {
Res = AvailableValue::get(UndefValue::get(Load->getType()));
return true;
}
if (Constant *InitVal =
getInitialValueOfAllocation(DepInst, TLI, Load->getType())) {
Res = AvailableValue::get(InitVal);
return true;
}
if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), Load->getType(),
DL))
return false;
if (S->isAtomic() < Load->isAtomic())
return false;
Res = AvailableValue::get(S->getValueOperand());
return true;
}
if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
if (!canCoerceMustAliasedValueToLoad(LD, Load->getType(), DL))
return false;
if (LD->isAtomic() < Load->isAtomic())
return false;
Res = AvailableValue::getLoad(LD);
return true;
}
LLVM_DEBUG(
dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
dbgs() << " has unknown def " << *DepInst << '\n';);
return false;
}
void GVNPass::AnalyzeLoadAvailability(LoadInst *Load, LoadDepVect &Deps,
AvailValInBlkVect &ValuesPerBlock,
UnavailBlkVect &UnavailableBlocks) {
unsigned NumDeps = Deps.size();
for (unsigned i = 0, e = NumDeps; i != e; ++i) {
BasicBlock *DepBB = Deps[i].getBB();
MemDepResult DepInfo = Deps[i].getResult();
if (DeadBlocks.count(DepBB)) {
ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
continue;
}
Value *Address = Deps[i].getAddress();
if (!DepInfo.isDef() && !DepInfo.isClobber()) {
if (auto R = tryToConvertLoadOfPtrSelect(
DepBB, DepBB->end(), Address, Load->getType(), getDominatorTree(),
getAliasAnalysis())) {
ValuesPerBlock.push_back(
AvailableValueInBlock::get(DepBB, std::move(*R)));
continue;
}
UnavailableBlocks.push_back(DepBB);
continue;
}
AvailableValue AV;
if (AnalyzeLoadAvailability(Load, DepInfo, Address, AV)) {
ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
std::move(AV)));
} else {
UnavailableBlocks.push_back(DepBB);
}
}
assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
"post condition violation");
}
void GVNPass::eliminatePartiallyRedundantLoad(
LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
MapVector<BasicBlock *, Value *> &AvailableLoads) {
for (const auto &AvailableLoad : AvailableLoads) {
BasicBlock *UnavailableBlock = AvailableLoad.first;
Value *LoadPtr = AvailableLoad.second;
auto *NewLoad =
new LoadInst(Load->getType(), LoadPtr, Load->getName() + ".pre",
Load->isVolatile(), Load->getAlign(), Load->getOrdering(),
Load->getSyncScopeID(), UnavailableBlock->getTerminator());
NewLoad->setDebugLoc(Load->getDebugLoc());
if (MSSAU) {
auto *MSSA = MSSAU->getMemorySSA();
auto *LoadAcc = MSSA->getMemoryAccess(Load);
auto *DefiningAcc =
isa<MemoryDef>(LoadAcc) ? LoadAcc : LoadAcc->getDefiningAccess();
auto *NewAccess = MSSAU->createMemoryAccessInBB(
NewLoad, DefiningAcc, NewLoad->getParent(),
MemorySSA::BeforeTerminator);
if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess))
MSSAU->insertDef(NewDef, true);
else
MSSAU->insertUse(cast<MemoryUse>(NewAccess), true);
}
AAMDNodes Tags = Load->getAAMetadata();
if (Tags)
NewLoad->setAAMetadata(Tags);
if (auto *MD = Load->getMetadata(LLVMContext::MD_invariant_load))
NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
if (auto *InvGroupMD = Load->getMetadata(LLVMContext::MD_invariant_group))
NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
if (auto *RangeMD = Load->getMetadata(LLVMContext::MD_range))
NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
if (auto *AccessMD = Load->getMetadata(LLVMContext::MD_access_group))
if (LI &&
LI->getLoopFor(Load->getParent()) == LI->getLoopFor(UnavailableBlock))
NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
ValuesPerBlock.push_back(
AvailableValueInBlock::get(UnavailableBlock, NewLoad));
MD->invalidateCachedPointerInfo(LoadPtr);
LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
}
Value *V = ConstructSSAForLoadSet(Load, ValuesPerBlock, *this);
Load->replaceAllUsesWith(V);
if (isa<PHINode>(V))
V->takeName(Load);
if (Instruction *I = dyn_cast<Instruction>(V))
I->setDebugLoc(Load->getDebugLoc());
if (V->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(V);
markInstructionForDeletion(Load);
ORE->emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "LoadPRE", Load)
<< "load eliminated by PRE";
});
}
bool GVNPass::PerformLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
UnavailBlkVect &UnavailableBlocks) {
SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
UnavailableBlocks.end());
BasicBlock *LoadBB = Load->getParent();
BasicBlock *TmpBB = LoadBB;
bool MustEnsureSafetyOfSpeculativeExecution =
ICF->isDominatedByICFIFromSameBlock(Load);
while (TmpBB->getSinglePredecessor()) {
TmpBB = TmpBB->getSinglePredecessor();
if (TmpBB == LoadBB) return false;
if (Blockers.count(TmpBB))
return false;
if (TmpBB->getTerminator()->getNumSuccessors() != 1)
return false;
MustEnsureSafetyOfSpeculativeExecution =
MustEnsureSafetyOfSpeculativeExecution || ICF->hasICF(TmpBB);
}
assert(TmpBB);
LoadBB = TmpBB;
MapVector<BasicBlock *, Value *> PredLoads;
DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks;
for (const AvailableValueInBlock &AV : ValuesPerBlock)
FullyAvailableBlocks[AV.BB] = AvailabilityState::Available;
for (BasicBlock *UnavailableBB : UnavailableBlocks)
FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable;
SmallVector<BasicBlock *, 4> CriticalEdgePred;
for (BasicBlock *Pred : predecessors(LoadBB)) {
if (Pred->getTerminator()->isEHPad()) {
LLVM_DEBUG(
dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
<< Pred->getName() << "': " << *Load << '\n');
return false;
}
if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
continue;
}
if (Pred->getTerminator()->getNumSuccessors() != 1) {
if (isa<IndirectBrInst>(Pred->getTerminator())) {
LLVM_DEBUG(
dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
<< Pred->getName() << "': " << *Load << '\n');
return false;
}
if (LoadBB->isEHPad()) {
LLVM_DEBUG(
dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
<< Pred->getName() << "': " << *Load << '\n');
return false;
}
if (!isLoadPRESplitBackedgeEnabled())
if (DT->dominates(LoadBB, Pred)) {
LLVM_DEBUG(
dbgs()
<< "COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
<< Pred->getName() << "': " << *Load << '\n');
return false;
}
CriticalEdgePred.push_back(Pred);
} else {
PredLoads[Pred] = nullptr;
}
}
unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
assert(NumUnavailablePreds != 0 &&
"Fully available value should already be eliminated!");
if (NumUnavailablePreds != 1)
return false;
if (MustEnsureSafetyOfSpeculativeExecution) {
if (CriticalEdgePred.size())
if (!isSafeToSpeculativelyExecute(Load, LoadBB->getFirstNonPHI(), DT))
return false;
for (auto &PL : PredLoads)
if (!isSafeToSpeculativelyExecute(Load, PL.first->getTerminator(), DT))
return false;
}
for (BasicBlock *OrigPred : CriticalEdgePred) {
BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
PredLoads[NewPred] = nullptr;
LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
<< LoadBB->getName() << '\n');
}
bool CanDoPRE = true;
const DataLayout &DL = Load->getModule()->getDataLayout();
SmallVector<Instruction*, 8> NewInsts;
for (auto &PredLoad : PredLoads) {
BasicBlock *UnavailablePred = PredLoad.first;
Value *LoadPtr = Load->getPointerOperand();
BasicBlock *Cur = Load->getParent();
while (Cur != LoadBB) {
PHITransAddr Address(LoadPtr, DL, AC);
LoadPtr = Address.PHITranslateWithInsertion(
Cur, Cur->getSinglePredecessor(), *DT, NewInsts);
if (!LoadPtr) {
CanDoPRE = false;
break;
}
Cur = Cur->getSinglePredecessor();
}
if (LoadPtr) {
PHITransAddr Address(LoadPtr, DL, AC);
LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred, *DT,
NewInsts);
}
if (!LoadPtr) {
LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
<< *Load->getPointerOperand() << "\n");
CanDoPRE = false;
break;
}
PredLoad.second = LoadPtr;
}
if (!CanDoPRE) {
while (!NewInsts.empty()) {
NewInsts.pop_back_val()->eraseFromParent();
}
return !CriticalEdgePred.empty();
}
LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *Load << '\n');
LLVM_DEBUG(if (!NewInsts.empty()) dbgs() << "INSERTED " << NewInsts.size()
<< " INSTS: " << *NewInsts.back()
<< '\n');
for (Instruction *I : NewInsts) {
I->updateLocationAfterHoist();
VN.lookupOrAdd(I);
}
eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, PredLoads);
++NumPRELoad;
return true;
}
bool GVNPass::performLoopLoadPRE(LoadInst *Load,
AvailValInBlkVect &ValuesPerBlock,
UnavailBlkVect &UnavailableBlocks) {
if (!LI)
return false;
const Loop *L = LI->getLoopFor(Load->getParent());
if (!L || L->getHeader() != Load->getParent())
return false;
BasicBlock *Preheader = L->getLoopPreheader();
BasicBlock *Latch = L->getLoopLatch();
if (!Preheader || !Latch)
return false;
Value *LoadPtr = Load->getPointerOperand();
if (!L->isLoopInvariant(LoadPtr))
return false;
if (ICF->isDominatedByICFIFromSameBlock(Load))
return false;
BasicBlock *LoopBlock = nullptr;
for (auto *Blocker : UnavailableBlocks) {
if (!L->contains(Blocker))
continue;
if (LoopBlock)
return false;
if (L != LI->getLoopFor(Blocker))
return false;
if (DT->dominates(Blocker, Latch))
return false;
if (Blocker->getTerminator()->mayWriteToMemory())
return false;
LoopBlock = Blocker;
}
if (!LoopBlock)
return false;
if (LoadPtr->canBeFreed())
return false;
MapVector<BasicBlock *, Value *> AvailableLoads;
AvailableLoads[LoopBlock] = LoadPtr;
AvailableLoads[Preheader] = LoadPtr;
LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOOP LOAD: " << *Load << '\n');
eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, AvailableLoads);
++NumPRELoopLoad;
return true;
}
static void reportLoadElim(LoadInst *Load, Value *AvailableValue,
OptimizationRemarkEmitter *ORE) {
using namespace ore;
ORE->emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "LoadElim", Load)
<< "load of type " << NV("Type", Load->getType()) << " eliminated"
<< setExtraArgs() << " in favor of "
<< NV("InfavorOfValue", AvailableValue);
});
}
bool GVNPass::processNonLocalLoad(LoadInst *Load) {
if (Load->getParent()->getParent()->hasFnAttribute(
Attribute::SanitizeAddress) ||
Load->getParent()->getParent()->hasFnAttribute(
Attribute::SanitizeHWAddress))
return false;
LoadDepVect Deps;
MD->getNonLocalPointerDependency(Load, Deps);
unsigned NumDeps = Deps.size();
if (NumDeps > MaxNumDeps)
return false;
if (NumDeps == 1 &&
!Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
LLVM_DEBUG(dbgs() << "GVN: non-local load "; Load->printAsOperand(dbgs());
dbgs() << " has unknown dependencies\n";);
return false;
}
bool Changed = false;
if (GetElementPtrInst *GEP =
dyn_cast<GetElementPtrInst>(Load->getOperand(0))) {
for (Use &U : GEP->indices())
if (Instruction *I = dyn_cast<Instruction>(U.get()))
Changed |= performScalarPRE(I);
}
AvailValInBlkVect ValuesPerBlock;
UnavailBlkVect UnavailableBlocks;
AnalyzeLoadAvailability(Load, Deps, ValuesPerBlock, UnavailableBlocks);
if (ValuesPerBlock.empty())
return Changed;
if (UnavailableBlocks.empty()) {
LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *Load << '\n');
Value *V = ConstructSSAForLoadSet(Load, ValuesPerBlock, *this);
Load->replaceAllUsesWith(V);
if (isa<PHINode>(V))
V->takeName(Load);
if (Instruction *I = dyn_cast<Instruction>(V))
if (Load->getDebugLoc() && Load->getParent() == I->getParent())
I->setDebugLoc(Load->getDebugLoc());
if (V->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(V);
markInstructionForDeletion(Load);
++NumGVNLoad;
reportLoadElim(Load, V, ORE);
return true;
}
if (!isPREEnabled() || !isLoadPREEnabled())
return Changed;
if (!isLoadInLoopPREEnabled() && LI && LI->getLoopFor(Load->getParent()))
return Changed;
if (performLoopLoadPRE(Load, ValuesPerBlock, UnavailableBlocks) ||
PerformLoadPRE(Load, ValuesPerBlock, UnavailableBlocks))
return true;
return Changed;
}
static bool impliesEquivalanceIfTrue(CmpInst* Cmp) {
if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_EQ)
return true;
if (Cmp->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
(Cmp->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
Cmp->getFastMathFlags().noNaNs())) {
Value *LHS = Cmp->getOperand(0);
Value *RHS = Cmp->getOperand(1);
if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero())
return true;
if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero())
return true;;
}
return false;
}
static bool impliesEquivalanceIfFalse(CmpInst* Cmp) {
if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_NE)
return true;
if ((Cmp->getPredicate() == CmpInst::Predicate::FCMP_ONE &&
Cmp->getFastMathFlags().noNaNs()) ||
Cmp->getPredicate() == CmpInst::Predicate::FCMP_UNE) {
Value *LHS = Cmp->getOperand(0);
Value *RHS = Cmp->getOperand(1);
if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero())
return true;
if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero())
return true;;
}
return false;
}
static bool hasUsersIn(Value *V, BasicBlock *BB) {
for (User *U : V->users())
if (isa<Instruction>(U) &&
cast<Instruction>(U)->getParent() == BB)
return true;
return false;
}
bool GVNPass::processAssumeIntrinsic(AssumeInst *IntrinsicI) {
Value *V = IntrinsicI->getArgOperand(0);
if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
if (Cond->isZero()) {
Type *Int8Ty = Type::getInt8Ty(V->getContext());
auto *NewS = new StoreInst(PoisonValue::get(Int8Ty),
Constant::getNullValue(Int8Ty->getPointerTo()),
IntrinsicI);
if (MSSAU) {
const MemoryUseOrDef *FirstNonDom = nullptr;
const auto *AL =
MSSAU->getMemorySSA()->getBlockAccesses(IntrinsicI->getParent());
if (AL) {
for (auto &Acc : *AL) {
if (auto *Current = dyn_cast<MemoryUseOrDef>(&Acc))
if (!Current->getMemoryInst()->comesBefore(NewS)) {
FirstNonDom = Current;
break;
}
}
}
auto *NewDef =
FirstNonDom ? MSSAU->createMemoryAccessBefore(
NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(),
const_cast<MemoryUseOrDef *>(FirstNonDom))
: MSSAU->createMemoryAccessInBB(
NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(),
NewS->getParent(), MemorySSA::BeforeTerminator);
MSSAU->insertDef(cast<MemoryDef>(NewDef), false);
}
}
if (isAssumeWithEmptyBundle(*IntrinsicI))
markInstructionForDeletion(IntrinsicI);
return false;
} else if (isa<Constant>(V)) {
return false;
}
Constant *True = ConstantInt::getTrue(V->getContext());
bool Changed = false;
for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
Changed |= propagateEquality(V, True, Edge, false);
}
ReplaceOperandsWithMap[V] = True;
Value *NotV;
if (match(V, m_Not(m_Value(NotV))))
ReplaceOperandsWithMap[NotV] = ConstantInt::getFalse(V->getContext());
if (auto *CmpI = dyn_cast<CmpInst>(V)) {
if (impliesEquivalanceIfTrue(CmpI)) {
Value *CmpLHS = CmpI->getOperand(0);
Value *CmpRHS = CmpI->getOperand(1);
if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS))
std::swap(CmpLHS, CmpRHS);
if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))
std::swap(CmpLHS, CmpRHS);
if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) ||
(isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) {
uint32_t LVN = VN.lookupOrAdd(CmpLHS);
uint32_t RVN = VN.lookupOrAdd(CmpRHS);
if (LVN < RVN)
std::swap(CmpLHS, CmpRHS);
}
if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS))
return Changed;
LLVM_DEBUG(dbgs() << "Replacing dominated uses of "
<< *CmpLHS << " with "
<< *CmpRHS << " in block "
<< IntrinsicI->getParent()->getName() << "\n");
if (hasUsersIn(CmpLHS, IntrinsicI->getParent()))
ReplaceOperandsWithMap[CmpLHS] = CmpRHS;
}
}
return Changed;
}
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
patchReplacementInstruction(I, Repl);
I->replaceAllUsesWith(Repl);
}
bool GVNPass::processLoad(LoadInst *L) {
if (!MD)
return false;
if (!L->isUnordered())
return false;
if (L->use_empty()) {
markInstructionForDeletion(L);
return true;
}
MemDepResult Dep = MD->getDependency(L);
if (Dep.isNonLocal())
return processNonLocalLoad(L);
Value *Address = L->getPointerOperand();
if (!Dep.isDef() && !Dep.isClobber() && !isa<SelectInst>(Address)) {
LLVM_DEBUG(
dbgs() << "GVN: load "; L->printAsOperand(dbgs());
dbgs() << " has unknown dependence\n";);
return false;
}
AvailableValue AV;
if (AnalyzeLoadAvailability(L, Dep, Address, AV)) {
Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
patchAndReplaceAllUsesWith(L, AvailableValue);
markInstructionForDeletion(L);
if (MSSAU)
MSSAU->removeMemoryAccess(L);
++NumGVNLoad;
reportLoadElim(L, AvailableValue, ORE);
if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(AvailableValue);
return true;
}
return false;
}
std::pair<uint32_t, bool>
GVNPass::ValueTable::assignExpNewValueNum(Expression &Exp) {
uint32_t &e = expressionNumbering[Exp];
bool CreateNewValNum = !e;
if (CreateNewValNum) {
Expressions.push_back(Exp);
if (ExprIdx.size() < nextValueNumber + 1)
ExprIdx.resize(nextValueNumber * 2);
e = nextValueNumber;
ExprIdx[nextValueNumber++] = nextExprNumber++;
}
return {e, CreateNewValNum};
}
bool GVNPass::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
GVNPass &Gvn) {
LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
while (Vals && Vals->BB == BB)
Vals = Vals->Next;
return !Vals;
}
uint32_t GVNPass::ValueTable::phiTranslate(const BasicBlock *Pred,
const BasicBlock *PhiBlock,
uint32_t Num, GVNPass &Gvn) {
auto FindRes = PhiTranslateTable.find({Num, Pred});
if (FindRes != PhiTranslateTable.end())
return FindRes->second;
uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
PhiTranslateTable.insert({{Num, Pred}, NewNum});
return NewNum;
}
bool GVNPass::ValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum,
const BasicBlock *Pred,
const BasicBlock *PhiBlock,
GVNPass &Gvn) {
CallInst *Call = nullptr;
LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
while (Vals) {
Call = dyn_cast<CallInst>(Vals->Val);
if (Call && Call->getParent() == PhiBlock)
break;
Vals = Vals->Next;
}
if (AA->doesNotAccessMemory(Call))
return true;
if (!MD || !AA->onlyReadsMemory(Call))
return false;
MemDepResult local_dep = MD->getDependency(Call);
if (!local_dep.isNonLocal())
return false;
const MemoryDependenceResults::NonLocalDepInfo &deps =
MD->getNonLocalCallDependency(Call);
for (const NonLocalDepEntry &D : deps) {
if (D.getResult().isNonFuncLocal())
return true;
}
return false;
}
uint32_t GVNPass::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
const BasicBlock *PhiBlock,
uint32_t Num, GVNPass &Gvn) {
if (PHINode *PN = NumberingPhi[Num]) {
for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false))
return TransVal;
}
return Num;
}
if (!areAllValsInBB(Num, PhiBlock, Gvn))
return Num;
if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
return Num;
Expression Exp = Expressions[ExprIdx[Num]];
for (unsigned i = 0; i < Exp.varargs.size(); i++) {
if ((i > 1 && Exp.opcode == Instruction::InsertValue) ||
(i > 0 && Exp.opcode == Instruction::ExtractValue) ||
(i > 1 && Exp.opcode == Instruction::ShuffleVector))
continue;
Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn);
}
if (Exp.commutative) {
assert(Exp.varargs.size() >= 2 && "Unsupported commutative instruction!");
if (Exp.varargs[0] > Exp.varargs[1]) {
std::swap(Exp.varargs[0], Exp.varargs[1]);
uint32_t Opcode = Exp.opcode >> 8;
if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
Exp.opcode = (Opcode << 8) |
CmpInst::getSwappedPredicate(
static_cast<CmpInst::Predicate>(Exp.opcode & 255));
}
}
if (uint32_t NewNum = expressionNumbering[Exp]) {
if (Exp.opcode == Instruction::Call && NewNum != Num)
return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num;
return NewNum;
}
return Num;
}
void GVNPass::ValueTable::eraseTranslateCacheEntry(
uint32_t Num, const BasicBlock &CurrBlock) {
for (const BasicBlock *Pred : predecessors(&CurrBlock))
PhiTranslateTable.erase({Num, Pred});
}
Value *GVNPass::findLeader(const BasicBlock *BB, uint32_t num) {
LeaderTableEntry Vals = LeaderTable[num];
if (!Vals.Val) return nullptr;
Value *Val = nullptr;
if (DT->dominates(Vals.BB, BB)) {
Val = Vals.Val;
if (isa<Constant>(Val)) return Val;
}
LeaderTableEntry* Next = Vals.Next;
while (Next) {
if (DT->dominates(Next->BB, BB)) {
if (isa<Constant>(Next->Val)) return Next->Val;
if (!Val) Val = Next->Val;
}
Next = Next->Next;
}
return Val;
}
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
DominatorTree *DT) {
const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
assert((!Pred || Pred == E.getStart()) &&
"No edge between these basic blocks!");
return Pred != nullptr;
}
void GVNPass::assignBlockRPONumber(Function &F) {
BlockRPONumber.clear();
uint32_t NextBlockNumber = 1;
ReversePostOrderTraversal<Function *> RPOT(&F);
for (BasicBlock *BB : RPOT)
BlockRPONumber[BB] = NextBlockNumber++;
InvalidBlockRPONumbers = false;
}
bool GVNPass::replaceOperandsForInBlockEquality(Instruction *Instr) const {
bool Changed = false;
for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
Value *Operand = Instr->getOperand(OpNum);
auto it = ReplaceOperandsWithMap.find(Operand);
if (it != ReplaceOperandsWithMap.end()) {
LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with "
<< *it->second << " in instruction " << *Instr << '\n');
Instr->setOperand(OpNum, it->second);
Changed = true;
}
}
return Changed;
}
bool GVNPass::propagateEquality(Value *LHS, Value *RHS,
const BasicBlockEdge &Root,
bool DominatesByEdge) {
SmallVector<std::pair<Value*, Value*>, 4> Worklist;
Worklist.push_back(std::make_pair(LHS, RHS));
bool Changed = false;
const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
while (!Worklist.empty()) {
std::pair<Value*, Value*> Item = Worklist.pop_back_val();
LHS = Item.first; RHS = Item.second;
if (LHS == RHS)
continue;
assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
if (isa<Constant>(LHS) && isa<Constant>(RHS))
continue;
if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
std::swap(LHS, RHS);
assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
uint32_t LVN = VN.lookupOrAdd(LHS);
if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
(isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
uint32_t RVN = VN.lookupOrAdd(RHS);
if (LVN < RVN) {
std::swap(LHS, RHS);
LVN = RVN;
}
}
if (RootDominatesEnd && !isa<Instruction>(RHS))
addToLeaderTable(LVN, RHS, Root.getEnd());
if (!LHS->hasOneUse()) {
unsigned NumReplacements =
DominatesByEdge
? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
: replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
Changed |= NumReplacements > 0;
NumGVNEqProp += NumReplacements;
if (MD)
MD->invalidateCachedPointerInfo(LHS);
}
if (!RHS->getType()->isIntegerTy(1))
continue;
ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
if (!CI)
continue;
bool isKnownTrue = CI->isMinusOne();
bool isKnownFalse = !isKnownTrue;
Value *A, *B;
if ((isKnownTrue && match(LHS, m_LogicalAnd(m_Value(A), m_Value(B)))) ||
(isKnownFalse && match(LHS, m_LogicalOr(m_Value(A), m_Value(B))))) {
Worklist.push_back(std::make_pair(A, RHS));
Worklist.push_back(std::make_pair(B, RHS));
continue;
}
if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
if ((isKnownTrue && impliesEquivalanceIfTrue(Cmp)) ||
(isKnownFalse && impliesEquivalanceIfFalse(Cmp)))
Worklist.push_back(std::make_pair(Op0, Op1));
CmpInst::Predicate NotPred = Cmp->getInversePredicate();
Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
uint32_t NextNum = VN.getNextUnusedValueNumber();
uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
if (Num < NextNum) {
Value *NotCmp = findLeader(Root.getEnd(), Num);
if (NotCmp && isa<Instruction>(NotCmp)) {
unsigned NumReplacements =
DominatesByEdge
? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
: replaceDominatedUsesWith(NotCmp, NotVal, *DT,
Root.getStart());
Changed |= NumReplacements > 0;
NumGVNEqProp += NumReplacements;
if (MD)
MD->invalidateCachedPointerInfo(NotCmp);
}
}
if (RootDominatesEnd)
addToLeaderTable(Num, NotVal, Root.getEnd());
continue;
}
}
return Changed;
}
bool GVNPass::processInstruction(Instruction *I) {
if (isa<DbgInfoIntrinsic>(I))
return false;
const DataLayout &DL = I->getModule()->getDataLayout();
if (Value *V = simplifyInstruction(I, {DL, TLI, DT, AC})) {
bool Changed = false;
if (!I->use_empty()) {
ICF->removeUsersOf(I);
I->replaceAllUsesWith(V);
Changed = true;
}
if (isInstructionTriviallyDead(I, TLI)) {
markInstructionForDeletion(I);
Changed = true;
}
if (Changed) {
if (MD && V->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(V);
++NumGVNSimpl;
return true;
}
}
if (auto *Assume = dyn_cast<AssumeInst>(I))
return processAssumeIntrinsic(Assume);
if (LoadInst *Load = dyn_cast<LoadInst>(I)) {
if (processLoad(Load))
return true;
unsigned Num = VN.lookupOrAdd(Load);
addToLeaderTable(Num, Load, Load->getParent());
return false;
}
if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
if (!BI->isConditional())
return false;
if (isa<Constant>(BI->getCondition()))
return processFoldableCondBr(BI);
Value *BranchCond = BI->getCondition();
BasicBlock *TrueSucc = BI->getSuccessor(0);
BasicBlock *FalseSucc = BI->getSuccessor(1);
if (TrueSucc == FalseSucc)
return false;
BasicBlock *Parent = BI->getParent();
bool Changed = false;
Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
BasicBlockEdge TrueE(Parent, TrueSucc);
Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
BasicBlockEdge FalseE(Parent, FalseSucc);
Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
return Changed;
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
Value *SwitchCond = SI->getCondition();
BasicBlock *Parent = SI->getParent();
bool Changed = false;
SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
++SwitchEdges[SI->getSuccessor(i)];
for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
i != e; ++i) {
BasicBlock *Dst = i->getCaseSuccessor();
if (SwitchEdges.lookup(Dst) == 1) {
BasicBlockEdge E(Parent, Dst);
Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true);
}
}
return Changed;
}
if (I->getType()->isVoidTy())
return false;
uint32_t NextNum = VN.getNextUnusedValueNumber();
unsigned Num = VN.lookupOrAdd(I);
if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) {
addToLeaderTable(Num, I, I->getParent());
return false;
}
if (Num >= NextNum) {
addToLeaderTable(Num, I, I->getParent());
return false;
}
Value *Repl = findLeader(I->getParent(), Num);
if (!Repl) {
addToLeaderTable(Num, I, I->getParent());
return false;
} else if (Repl == I) {
return false;
}
patchAndReplaceAllUsesWith(I, Repl);
if (MD && Repl->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(Repl);
markInstructionForDeletion(I);
return true;
}
bool GVNPass::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
const TargetLibraryInfo &RunTLI, AAResults &RunAA,
MemoryDependenceResults *RunMD, LoopInfo *LI,
OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) {
AC = &RunAC;
DT = &RunDT;
VN.setDomTree(DT);
TLI = &RunTLI;
VN.setAliasAnalysis(&RunAA);
MD = RunMD;
ImplicitControlFlowTracking ImplicitCFT;
ICF = &ImplicitCFT;
this->LI = LI;
VN.setMemDep(MD);
ORE = RunORE;
InvalidBlockRPONumbers = true;
MemorySSAUpdater Updater(MSSA);
MSSAU = MSSA ? &Updater : nullptr;
bool Changed = false;
bool ShouldContinue = true;
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
bool removedBlock = MergeBlockIntoPredecessor(&BB, &DTU, LI, MSSAU, MD);
if (removedBlock)
++NumGVNBlocks;
Changed |= removedBlock;
}
unsigned Iteration = 0;
while (ShouldContinue) {
LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
(void) Iteration;
ShouldContinue = iterateOnFunction(F);
Changed |= ShouldContinue;
++Iteration;
}
if (isPREEnabled()) {
assignValNumForDeadCode();
bool PREChanged = true;
while (PREChanged) {
PREChanged = performPRE(F);
Changed |= PREChanged;
}
}
cleanupGlobalSets();
DeadBlocks.clear();
if (MSSA && VerifyMemorySSA)
MSSA->verifyMemorySSA();
return Changed;
}
bool GVNPass::processBlock(BasicBlock *BB) {
assert(InstrsToErase.empty() &&
"We expect InstrsToErase to be empty across iterations");
if (DeadBlocks.count(BB))
return false;
ReplaceOperandsWithMap.clear();
bool ChangedFunction = false;
ChangedFunction |= EliminateDuplicatePHINodes(BB);
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
BI != BE;) {
if (!ReplaceOperandsWithMap.empty())
ChangedFunction |= replaceOperandsForInBlockEquality(&*BI);
ChangedFunction |= processInstruction(&*BI);
if (InstrsToErase.empty()) {
++BI;
continue;
}
NumGVNInstr += InstrsToErase.size();
bool AtStart = BI == BB->begin();
if (!AtStart)
--BI;
for (auto *I : InstrsToErase) {
assert(I->getParent() == BB && "Removing instruction from wrong block?");
LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n');
salvageKnowledge(I, AC);
salvageDebugInfo(*I);
if (MD) MD->removeInstruction(I);
if (MSSAU)
MSSAU->removeMemoryAccess(I);
LLVM_DEBUG(verifyRemoved(I));
ICF->removeInstruction(I);
I->eraseFromParent();
}
InstrsToErase.clear();
if (AtStart)
BI = BB->begin();
else
++BI;
}
return ChangedFunction;
}
bool GVNPass::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
BasicBlock *Curr, unsigned int ValNo) {
bool success = true;
for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
Value *Op = Instr->getOperand(i);
if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
continue;
if (!VN.exists(Op)) {
success = false;
break;
}
uint32_t TValNo =
VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
if (Value *V = findLeader(Pred, TValNo)) {
Instr->setOperand(i, V);
} else {
success = false;
break;
}
}
if (!success)
return false;
Instr->insertBefore(Pred->getTerminator());
Instr->setName(Instr->getName() + ".pre");
Instr->setDebugLoc(Instr->getDebugLoc());
ICF->insertInstructionTo(Instr, Pred);
unsigned Num = VN.lookupOrAdd(Instr);
VN.add(Instr, Num);
addToLeaderTable(Num, Instr, Pred);
return true;
}
bool GVNPass::performScalarPRE(Instruction *CurInst) {
if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() ||
isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
isa<DbgInfoIntrinsic>(CurInst))
return false;
if (isa<CmpInst>(CurInst))
return false;
if (isa<GetElementPtrInst>(CurInst))
return false;
if (auto *CallB = dyn_cast<CallBase>(CurInst)) {
if (CallB->isInlineAsm())
return false;
if (CallB->isConvergent())
return false;
}
uint32_t ValNo = VN.lookup(CurInst);
unsigned NumWith = 0;
unsigned NumWithout = 0;
BasicBlock *PREPred = nullptr;
BasicBlock *CurrentBlock = CurInst->getParent();
if (InvalidBlockRPONumbers)
assignBlockRPONumber(*CurrentBlock->getParent());
SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
for (BasicBlock *P : predecessors(CurrentBlock)) {
if (!DT->isReachableFromEntry(P)) {
NumWithout = 2;
break;
}
assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
"Invalid BlockRPONumber map.");
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
llvm::any_of(CurInst->operands(), [&](const Use &U) {
if (auto *Inst = dyn_cast<Instruction>(U.get()))
return Inst->getParent() == CurrentBlock;
return false;
})) {
NumWithout = 2;
break;
}
uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
Value *predV = findLeader(P, TValNo);
if (!predV) {
predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
PREPred = P;
++NumWithout;
} else if (predV == CurInst) {
NumWithout = 2;
break;
} else {
predMap.push_back(std::make_pair(predV, P));
++NumWith;
}
}
if (NumWithout > 1 || NumWith == 0)
return false;
Instruction *PREInstr = nullptr;
if (NumWithout != 0) {
if (!isSafeToSpeculativelyExecute(CurInst)) {
if (ICF->isDominatedByICFIFromSameBlock(CurInst))
return false;
}
if (isa<IndirectBrInst>(PREPred->getTerminator()))
return false;
unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
return false;
}
PREInstr = CurInst->clone();
if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
LLVM_DEBUG(verifyRemoved(PREInstr));
PREInstr->deleteValue();
return false;
}
}
assert(PREInstr != nullptr || NumWithout == 0);
++NumGVNPRE;
PHINode *Phi =
PHINode::Create(CurInst->getType(), predMap.size(),
CurInst->getName() + ".pre-phi", &CurrentBlock->front());
for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
if (Value *V = predMap[i].first) {
patchReplacementInstruction(CurInst, V);
Phi->addIncoming(V, predMap[i].second);
} else
Phi->addIncoming(PREInstr, PREPred);
}
VN.add(Phi, ValNo);
VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
addToLeaderTable(ValNo, Phi, CurrentBlock);
Phi->setDebugLoc(CurInst->getDebugLoc());
CurInst->replaceAllUsesWith(Phi);
if (MD && Phi->getType()->isPtrOrPtrVectorTy())
MD->invalidateCachedPointerInfo(Phi);
VN.erase(CurInst);
removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
if (MD)
MD->removeInstruction(CurInst);
if (MSSAU)
MSSAU->removeMemoryAccess(CurInst);
LLVM_DEBUG(verifyRemoved(CurInst));
ICF->removeInstruction(CurInst);
CurInst->eraseFromParent();
++NumGVNInstr;
return true;
}
bool GVNPass::performPRE(Function &F) {
bool Changed = false;
for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
if (CurrentBlock == &F.getEntryBlock())
continue;
if (CurrentBlock->isEHPad())
continue;
for (BasicBlock::iterator BI = CurrentBlock->begin(),
BE = CurrentBlock->end();
BI != BE;) {
Instruction *CurInst = &*BI++;
Changed |= performScalarPRE(CurInst);
}
}
if (splitCriticalEdges())
Changed = true;
return Changed;
}
BasicBlock *GVNPass::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
BasicBlock *BB = SplitCriticalEdge(
Pred, Succ,
CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify());
if (BB) {
if (MD)
MD->invalidateCachedPredecessors();
InvalidBlockRPONumbers = true;
}
return BB;
}
bool GVNPass::splitCriticalEdges() {
if (toSplit.empty())
return false;
bool Changed = false;
do {
std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
Changed |= SplitCriticalEdge(Edge.first, Edge.second,
CriticalEdgeSplittingOptions(DT, LI, MSSAU)) !=
nullptr;
} while (!toSplit.empty());
if (Changed) {
if (MD)
MD->invalidateCachedPredecessors();
InvalidBlockRPONumbers = true;
}
return Changed;
}
bool GVNPass::iterateOnFunction(Function &F) {
cleanupGlobalSets();
bool Changed = false;
ReversePostOrderTraversal<Function *> RPOT(&F);
for (BasicBlock *BB : RPOT)
Changed |= processBlock(BB);
return Changed;
}
void GVNPass::cleanupGlobalSets() {
VN.clear();
LeaderTable.clear();
BlockRPONumber.clear();
TableAllocator.Reset();
ICF->clear();
InvalidBlockRPONumbers = true;
}
void GVNPass::verifyRemoved(const Instruction *Inst) const {
VN.verifyRemoved(Inst);
for (const auto &I : LeaderTable) {
const LeaderTableEntry *Node = &I.second;
assert(Node->Val != Inst && "Inst still in value numbering scope!");
while (Node->Next) {
Node = Node->Next;
assert(Node->Val != Inst && "Inst still in value numbering scope!");
}
}
}
void GVNPass::addDeadBlock(BasicBlock *BB) {
SmallVector<BasicBlock *, 4> NewDead;
SmallSetVector<BasicBlock *, 4> DF;
NewDead.push_back(BB);
while (!NewDead.empty()) {
BasicBlock *D = NewDead.pop_back_val();
if (DeadBlocks.count(D))
continue;
SmallVector<BasicBlock *, 8> Dom;
DT->getDescendants(D, Dom);
DeadBlocks.insert(Dom.begin(), Dom.end());
for (BasicBlock *B : Dom) {
for (BasicBlock *S : successors(B)) {
if (DeadBlocks.count(S))
continue;
bool AllPredDead = true;
for (BasicBlock *P : predecessors(S))
if (!DeadBlocks.count(P)) {
AllPredDead = false;
break;
}
if (!AllPredDead) {
DF.insert(S);
} else {
NewDead.push_back(S);
}
}
}
}
for (BasicBlock *B : DF) {
if (DeadBlocks.count(B))
continue;
SmallVector<BasicBlock *, 4> Preds(predecessors(B));
for (BasicBlock *P : Preds) {
if (!DeadBlocks.count(P))
continue;
if (llvm::is_contained(successors(P), B) &&
isCriticalEdge(P->getTerminator(), B)) {
if (BasicBlock *S = splitCriticalEdges(P, B))
DeadBlocks.insert(P = S);
}
}
for (BasicBlock *P : predecessors(B)) {
if (!DeadBlocks.count(P))
continue;
for (PHINode &Phi : B->phis()) {
Phi.setIncomingValueForBlock(P, PoisonValue::get(Phi.getType()));
if (MD)
MD->invalidateCachedPointerInfo(&Phi);
}
}
}
}
bool GVNPass::processFoldableCondBr(BranchInst *BI) {
if (!BI || BI->isUnconditional())
return false;
if (BI->getSuccessor(0) == BI->getSuccessor(1))
return false;
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
if (!Cond)
return false;
BasicBlock *DeadRoot =
Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
if (DeadBlocks.count(DeadRoot))
return false;
if (!DeadRoot->getSinglePredecessor())
DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
addDeadBlock(DeadRoot);
return true;
}
void GVNPass::assignValNumForDeadCode() {
for (BasicBlock *BB : DeadBlocks) {
for (Instruction &Inst : *BB) {
unsigned ValNum = VN.lookupOrAdd(&Inst);
addToLeaderTable(ValNum, &Inst, BB);
}
}
}
class llvm::gvn::GVNLegacyPass : public FunctionPass {
public:
static char ID;
explicit GVNLegacyPass(bool NoMemDepAnalysis = !GVNEnableMemDep)
: FunctionPass(ID), Impl(GVNOptions().setMemDep(!NoMemDepAnalysis)) {
initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
return Impl.runImpl(
F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
getAnalysis<AAResultsWrapperPass>().getAAResults(),
Impl.isMemDepEnabled()
? &getAnalysis<MemoryDependenceWrapperPass>().getMemDep()
: nullptr,
LIWP ? &LIWP->getLoopInfo() : nullptr,
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(),
MSSAWP ? &MSSAWP->getMSSA() : nullptr);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
if (Impl.isMemDepEnabled())
AU.addRequired<MemoryDependenceWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.addPreserved<TargetLibraryInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
AU.addPreserved<MemorySSAWrapperPass>();
}
private:
GVNPass Impl;
};
char GVNLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) {
return new GVNLegacyPass(NoMemDepAnalysis);
}