#include "llvm/Transforms/Scalar/NewGVN.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SparseBitVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.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/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ArrayRecycler.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/PointerLikeTypeTraits.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVNExpression.h"
#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/PredicateInfo.h"
#include "llvm/Transforms/Utils/VNCoercion.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
using namespace llvm::GVNExpression;
using namespace llvm::VNCoercion;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "newgvn"
STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
STATISTIC(NumGVNMaxIterations,
"Maximum Number of iterations it took to converge GVN");
STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
STATISTIC(NumGVNAvoidedSortedLeaderChanges,
"Number of avoided sorted leader changes");
STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
STATISTIC(NumGVNPHIOfOpsEliminations,
"Number of things eliminated using PHI of ops");
DEBUG_COUNTER(VNCounter, "newgvn-vn",
"Controls which instructions are value numbered");
DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
"Controls which instructions we create phi of ops for");
static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
cl::init(false), cl::Hidden);
static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(true),
cl::Hidden);
namespace llvm {
namespace GVNExpression {
Expression::~Expression() = default;
BasicExpression::~BasicExpression() = default;
CallExpression::~CallExpression() = default;
LoadExpression::~LoadExpression() = default;
StoreExpression::~StoreExpression() = default;
AggregateValueExpression::~AggregateValueExpression() = default;
PHIExpression::~PHIExpression() = default;
} }
namespace {
struct TarjanSCC {
TarjanSCC() : Components(1) {}
void Start(const Instruction *Start) {
if (Root.lookup(Start) == 0)
FindSCC(Start);
}
const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
unsigned ComponentID = ValueToComponent.lookup(V);
assert(ComponentID > 0 &&
"Asking for a component for a value we never processed");
return Components[ComponentID];
}
private:
void FindSCC(const Instruction *I) {
Root[I] = ++DFSNum;
unsigned int OurDFS = DFSNum;
for (auto &Op : I->operands()) {
if (auto *InstOp = dyn_cast<Instruction>(Op)) {
if (Root.lookup(Op) == 0)
FindSCC(InstOp);
if (!InComponent.count(Op))
Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
}
}
if (Root.lookup(I) == OurDFS) {
unsigned ComponentID = Components.size();
Components.resize(Components.size() + 1);
auto &Component = Components.back();
Component.insert(I);
LLVM_DEBUG(dbgs() << "Component root is " << *I << "\n");
InComponent.insert(I);
ValueToComponent[I] = ComponentID;
while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
auto *Member = Stack.back();
LLVM_DEBUG(dbgs() << "Component member is " << *Member << "\n");
Component.insert(Member);
InComponent.insert(Member);
ValueToComponent[Member] = ComponentID;
Stack.pop_back();
}
} else {
Stack.push_back(I);
}
}
unsigned int DFSNum = 1;
SmallPtrSet<const Value *, 8> InComponent;
DenseMap<const Value *, unsigned int> Root;
SmallVector<const Value *, 8> Stack;
SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
DenseMap<const Value *, unsigned> ValueToComponent;
};
class CongruenceClass {
public:
using MemberType = Value;
using MemberSet = SmallPtrSet<MemberType *, 4>;
using MemoryMemberType = MemoryPhi;
using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
explicit CongruenceClass(unsigned ID) : ID(ID) {}
CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
: ID(ID), RepLeader(Leader), DefiningExpr(E) {}
unsigned getID() const { return ID; }
bool isDead() const {
return empty() && memory_empty();
}
Value *getLeader() const { return RepLeader; }
void setLeader(Value *Leader) { RepLeader = Leader; }
const std::pair<Value *, unsigned int> &getNextLeader() const {
return NextLeader;
}
void resetNextLeader() { NextLeader = {nullptr, ~0}; }
void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
if (LeaderPair.second < NextLeader.second)
NextLeader = LeaderPair;
}
Value *getStoredValue() const { return RepStoredValue; }
void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
const Expression *getDefiningExpr() const { return DefiningExpr; }
bool empty() const { return Members.empty(); }
unsigned size() const { return Members.size(); }
MemberSet::const_iterator begin() const { return Members.begin(); }
MemberSet::const_iterator end() const { return Members.end(); }
void insert(MemberType *M) { Members.insert(M); }
void erase(MemberType *M) { Members.erase(M); }
void swap(MemberSet &Other) { Members.swap(Other); }
bool memory_empty() const { return MemoryMembers.empty(); }
unsigned memory_size() const { return MemoryMembers.size(); }
MemoryMemberSet::const_iterator memory_begin() const {
return MemoryMembers.begin();
}
MemoryMemberSet::const_iterator memory_end() const {
return MemoryMembers.end();
}
iterator_range<MemoryMemberSet::const_iterator> memory() const {
return make_range(memory_begin(), memory_end());
}
void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
unsigned getStoreCount() const { return StoreCount; }
void incStoreCount() { ++StoreCount; }
void decStoreCount() {
assert(StoreCount != 0 && "Store count went negative");
--StoreCount;
}
bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
bool isEquivalentTo(const CongruenceClass *Other) const {
if (!Other)
return false;
if (this == Other)
return true;
if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
Other->RepMemoryAccess))
return false;
if (DefiningExpr != Other->DefiningExpr)
if (!DefiningExpr || !Other->DefiningExpr ||
*DefiningExpr != *Other->DefiningExpr)
return false;
if (Members.size() != Other->Members.size())
return false;
return llvm::set_is_subset(Members, Other->Members);
}
private:
unsigned ID;
Value *RepLeader = nullptr;
std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Value *RepStoredValue = nullptr;
const MemoryAccess *RepMemoryAccess = nullptr;
const Expression *DefiningExpr = nullptr;
MemberSet Members;
MemoryMemberSet MemoryMembers;
int StoreCount = 0;
};
}
namespace llvm {
struct ExactEqualsExpression {
const Expression &E;
explicit ExactEqualsExpression(const Expression &E) : E(E) {}
hash_code getComputedHash() const { return E.getComputedHash(); }
bool operator==(const Expression &Other) const {
return E.exactlyEquals(Other);
}
};
template <> struct DenseMapInfo<const Expression *> {
static const Expression *getEmptyKey() {
auto Val = static_cast<uintptr_t>(-1);
Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
return reinterpret_cast<const Expression *>(Val);
}
static const Expression *getTombstoneKey() {
auto Val = static_cast<uintptr_t>(~1U);
Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
return reinterpret_cast<const Expression *>(Val);
}
static unsigned getHashValue(const Expression *E) {
return E->getComputedHash();
}
static unsigned getHashValue(const ExactEqualsExpression &E) {
return E.getComputedHash();
}
static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
if (RHS == getTombstoneKey() || RHS == getEmptyKey())
return false;
return LHS == *RHS;
}
static bool isEqual(const Expression *LHS, const Expression *RHS) {
if (LHS == RHS)
return true;
if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
LHS == getEmptyKey() || RHS == getEmptyKey())
return false;
if (LHS->getComputedHash() != RHS->getComputedHash())
return false;
return *LHS == *RHS;
}
};
}
namespace {
class NewGVN {
Function &F;
DominatorTree *DT = nullptr;
const TargetLibraryInfo *TLI = nullptr;
AliasAnalysis *AA = nullptr;
MemorySSA *MSSA = nullptr;
MemorySSAWalker *MSSAWalker = nullptr;
AssumptionCache *AC = nullptr;
const DataLayout &DL;
std::unique_ptr<PredicateInfo> PredInfo;
mutable BumpPtrAllocator ExpressionAllocator;
mutable ArrayRecycler<Value *> ArgRecycler;
mutable TarjanSCC SCCFinder;
const SimplifyQuery SQ;
unsigned int NumFuncArgs = 0;
DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
CongruenceClass *TOPClass = nullptr;
std::vector<CongruenceClass *> CongruenceClasses;
unsigned NextCongruenceNum = 0;
DenseMap<Value *, CongruenceClass *> ValueToClass;
DenseMap<Value *, const Expression *> ValueToExpression;
SmallPtrSet<const Instruction *, 8> PHINodeUses;
DenseMap<const Value *, bool> OpSafeForPHIOfOps;
DenseMap<const Value *, BasicBlock *> TempToBlock;
DenseMap<const Value *, PHINode *> RealToTemp;
mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
ExpressionToPhiOfOps;
DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
DenseSet<Instruction *> AllTempInstructions;
DenseMap<BasicBlock *, SparseBitVector<>> RevisitOnReachabilityChange;
mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
PredicateToUsers;
mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
MemoryToUsers;
DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
ExpressionClassMap ExpressionToClass;
DeadExpression *SingletonDeadExpression = nullptr;
SmallPtrSet<Value *, 8> LeaderChanges;
using BlockEdge = BasicBlockEdge;
DenseSet<BlockEdge> ReachableEdges;
SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
BitVector TouchedInstructions;
DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
mutable DenseMap<const IntrinsicInst *, const Value *> IntrinsicInstPred;
#ifndef NDEBUG
DenseMap<const Value *, unsigned> ProcessedCount;
#endif
DenseMap<const Value *, unsigned> InstrDFS;
SmallVector<Value *, 32> DFSToInstr;
SmallPtrSet<Instruction *, 8> InstructionsToErase;
public:
NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
const DataLayout &DL)
: F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), AC(AC), DL(DL),
PredInfo(std::make_unique<PredicateInfo>(F, *DT, *AC)),
SQ(DL, TLI, DT, AC, nullptr, false,
false) {}
bool runGVN();
private:
struct ExprResult {
const Expression *Expr;
Value *ExtraDep;
const PredicateBase *PredDep;
ExprResult(const Expression *Expr, Value *ExtraDep = nullptr,
const PredicateBase *PredDep = nullptr)
: Expr(Expr), ExtraDep(ExtraDep), PredDep(PredDep) {}
ExprResult(const ExprResult &) = delete;
ExprResult(ExprResult &&Other)
: Expr(Other.Expr), ExtraDep(Other.ExtraDep), PredDep(Other.PredDep) {
Other.Expr = nullptr;
Other.ExtraDep = nullptr;
Other.PredDep = nullptr;
}
ExprResult &operator=(const ExprResult &Other) = delete;
ExprResult &operator=(ExprResult &&Other) = delete;
~ExprResult() { assert(!ExtraDep && "unhandled ExtraDep"); }
operator bool() const { return Expr; }
static ExprResult none() { return {nullptr, nullptr, nullptr}; }
static ExprResult some(const Expression *Expr, Value *ExtraDep = nullptr) {
return {Expr, ExtraDep, nullptr};
}
static ExprResult some(const Expression *Expr,
const PredicateBase *PredDep) {
return {Expr, nullptr, PredDep};
}
static ExprResult some(const Expression *Expr, Value *ExtraDep,
const PredicateBase *PredDep) {
return {Expr, ExtraDep, PredDep};
}
};
ExprResult createExpression(Instruction *) const;
const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
Instruction *) const;
using ValPair = std::pair<Value *, BasicBlock *>;
PHIExpression *createPHIExpression(ArrayRef<ValPair>, const Instruction *,
BasicBlock *, bool &HasBackEdge,
bool &OriginalOpsConstant) const;
const DeadExpression *createDeadExpression() const;
const VariableExpression *createVariableExpression(Value *) const;
const ConstantExpression *createConstantExpression(Constant *) const;
const Expression *createVariableOrConstant(Value *V) const;
const UnknownExpression *createUnknownExpression(Instruction *) const;
const StoreExpression *createStoreExpression(StoreInst *,
const MemoryAccess *) const;
LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
const MemoryAccess *) const;
const CallExpression *createCallExpression(CallInst *,
const MemoryAccess *) const;
const AggregateValueExpression *
createAggregateValueExpression(Instruction *) const;
bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
CongruenceClasses.emplace_back(result);
return result;
}
CongruenceClass *createMemoryClass(MemoryAccess *MA) {
auto *CC = createCongruenceClass(nullptr, nullptr);
CC->setMemoryLeader(MA);
return CC;
}
CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
auto *CC = getMemoryClass(MA);
if (CC->getMemoryLeader() != MA)
CC = createMemoryClass(MA);
return CC;
}
CongruenceClass *createSingletonCongruenceClass(Value *Member) {
CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
CClass->insert(Member);
ValueToClass[Member] = CClass;
return CClass;
}
void initializeCongruenceClasses(Function &F);
const Expression *makePossiblePHIOfOps(Instruction *,
SmallPtrSetImpl<Value *> &);
Value *findLeaderForInst(Instruction *ValueOp,
SmallPtrSetImpl<Value *> &Visited,
MemoryAccess *MemAccess, Instruction *OrigInst,
BasicBlock *PredBB);
bool OpIsSafeForPHIOfOpsHelper(Value *V, const BasicBlock *PHIBlock,
SmallPtrSetImpl<const Value *> &Visited,
SmallVectorImpl<Instruction *> &Worklist);
bool OpIsSafeForPHIOfOps(Value *Op, const BasicBlock *PHIBlock,
SmallPtrSetImpl<const Value *> &);
void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
void removePhiOfOps(Instruction *I, PHINode *PHITemp);
void valueNumberMemoryPhi(MemoryPhi *);
void valueNumberInstruction(Instruction *);
ExprResult checkExprResults(Expression *, Instruction *, Value *) const;
ExprResult performSymbolicEvaluation(Value *,
SmallPtrSetImpl<Value *> &) const;
const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Instruction *,
MemoryAccess *) const;
const Expression *performSymbolicLoadEvaluation(Instruction *) const;
const Expression *performSymbolicStoreEvaluation(Instruction *) const;
ExprResult performSymbolicCallEvaluation(Instruction *) const;
void sortPHIOps(MutableArrayRef<ValPair> Ops) const;
const Expression *performSymbolicPHIEvaluation(ArrayRef<ValPair>,
Instruction *I,
BasicBlock *PHIBlock) const;
const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
ExprResult performSymbolicCmpEvaluation(Instruction *) const;
ExprResult performSymbolicPredicateInfoEvaluation(IntrinsicInst *) const;
bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Value *lookupOperandLeader(Value *) const;
CongruenceClass *getClassForExpression(const Expression *E) const;
void performCongruenceFinding(Instruction *, const Expression *);
void moveValueToNewCongruenceClass(Instruction *, const Expression *,
CongruenceClass *, CongruenceClass *);
void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
CongruenceClass *, CongruenceClass *);
Value *getNextValueLeader(CongruenceClass *) const;
const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
bool isMemoryAccessTOP(const MemoryAccess *) const;
unsigned int getRank(const Value *) const;
bool shouldSwapOperands(const Value *, const Value *) const;
bool shouldSwapOperandsForIntrinsic(const Value *, const Value *,
const IntrinsicInst *I) const;
void updateReachableEdge(BasicBlock *, BasicBlock *);
void processOutgoingEdges(Instruction *, BasicBlock *);
Value *findConditionEquivalence(Value *) const;
struct ValueDFS;
void convertClassToDFSOrdered(const CongruenceClass &,
SmallVectorImpl<ValueDFS> &,
DenseMap<const Value *, unsigned int> &,
SmallPtrSetImpl<Instruction *> &) const;
void convertClassToLoadsAndStores(const CongruenceClass &,
SmallVectorImpl<ValueDFS> &) const;
bool eliminateInstructions(Function &);
void replaceInstruction(Instruction *, Value *);
void markInstructionForDeletion(Instruction *);
void deleteInstructionsInBlock(BasicBlock *);
Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
const BasicBlock *) const;
template <typename Map, typename KeyType>
void touchAndErase(Map &, const KeyType &);
void markUsersTouched(Value *);
void markMemoryUsersTouched(const MemoryAccess *);
void markMemoryDefTouched(const MemoryAccess *);
void markPredicateUsersTouched(Instruction *);
void markValueLeaderChangeTouched(CongruenceClass *CC);
void markMemoryLeaderChangeTouched(CongruenceClass *CC);
void markPhiOfOpsChanged(const Expression *E);
void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
void addAdditionalUsers(Value *To, Value *User) const;
void addAdditionalUsers(ExprResult &Res, Instruction *User) const;
void iterateTouchedInstructions();
void cleanupTables();
std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
void updateProcessedCount(const Value *V);
void verifyMemoryCongruency() const;
void verifyIterationSettled(Function &F);
void verifyStoreExpressions() const;
bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
const MemoryAccess *, const MemoryAccess *) const;
BasicBlock *getBlockForValue(Value *V) const;
void deleteExpression(const Expression *E) const;
MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
MemoryPhi *getMemoryAccess(const BasicBlock *) const;
template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
unsigned InstrToDFSNum(const Value *V) const {
assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
return InstrDFS.lookup(V);
}
unsigned InstrToDFSNum(const MemoryAccess *MA) const {
return MemoryToDFSNum(MA);
}
Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
unsigned MemoryToDFSNum(const Value *MA) const {
assert(isa<MemoryAccess>(MA) &&
"This should not be used with instructions");
return isa<MemoryUseOrDef>(MA)
? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
: InstrDFS.lookup(MA);
}
bool isCycleFree(const Instruction *) const;
bool isBackedge(BasicBlock *From, BasicBlock *To) const;
int64_t StartingVNCounter = 0;
};
}
template <typename T>
static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
return false;
return LHS.MemoryExpression::equals(RHS);
}
bool LoadExpression::equals(const Expression &Other) const {
return equalsLoadStoreHelper(*this, Other);
}
bool StoreExpression::equals(const Expression &Other) const {
if (!equalsLoadStoreHelper(*this, Other))
return false;
if (const auto *S = dyn_cast<StoreExpression>(&Other))
if (getStoredValue() != S->getStoredValue())
return false;
return true;
}
bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
return From == To ||
RPOOrdering.lookup(DT->getNode(From)) >=
RPOOrdering.lookup(DT->getNode(To));
}
#ifndef NDEBUG
static std::string getBlockName(const BasicBlock *B) {
return DOTGraphTraits<DOTFuncInfo *>::getSimpleNodeLabel(B, nullptr);
}
#endif
MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
auto *Result = MSSA->getMemoryAccess(I);
return Result ? Result : TempToMemory.lookup(I);
}
MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
return MSSA->getMemoryAccess(BB);
}
BasicBlock *NewGVN::getBlockForValue(Value *V) const {
if (auto *I = dyn_cast<Instruction>(V)) {
auto *Parent = I->getParent();
if (Parent)
return Parent;
Parent = TempToBlock.lookup(V);
assert(Parent && "Every fake instruction should have a block");
return Parent;
}
auto *MP = dyn_cast<MemoryPhi>(V);
assert(MP && "Should have been an instruction or a MemoryPhi");
return MP->getBlock();
}
void NewGVN::deleteExpression(const Expression *E) const {
assert(isa<BasicExpression>(E));
auto *BE = cast<BasicExpression>(E);
const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
ExpressionAllocator.Deallocate(E);
}
static Value *getCopyOf(const Value *V) {
if (auto *II = dyn_cast<IntrinsicInst>(V))
if (II->getIntrinsicID() == Intrinsic::ssa_copy)
return II->getOperand(0);
return nullptr;
}
static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
return V == PN || getCopyOf(V) == PN;
}
static bool isCopyOfAPHI(const Value *V) {
auto *CO = getCopyOf(V);
return CO && isa<PHINode>(CO);
}
void NewGVN::sortPHIOps(MutableArrayRef<ValPair> Ops) const {
llvm::sort(Ops, [&](const ValPair &P1, const ValPair &P2) {
return BlockInstRange.lookup(P1.second).first <
BlockInstRange.lookup(P2.second).first;
});
}
static bool alwaysAvailable(Value *V) {
return isa<Constant>(V) || isa<Argument>(V);
}
PHIExpression *NewGVN::createPHIExpression(ArrayRef<ValPair> PHIOperands,
const Instruction *I,
BasicBlock *PHIBlock,
bool &HasBackedge,
bool &OriginalOpsConstant) const {
unsigned NumOps = PHIOperands.size();
auto *E = new (ExpressionAllocator) PHIExpression(NumOps, PHIBlock);
E->allocateOperands(ArgRecycler, ExpressionAllocator);
E->setType(PHIOperands.begin()->first->getType());
E->setOpcode(Instruction::PHI);
auto Filtered = make_filter_range(PHIOperands, [&](const ValPair &P) {
auto *BB = P.second;
if (auto *PHIOp = dyn_cast<PHINode>(I))
if (isCopyOfPHI(P.first, PHIOp))
return false;
if (!ReachableEdges.count({BB, PHIBlock}))
return false;
if (ValueToClass.lookup(P.first) == TOPClass)
return false;
OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
return lookupOperandLeader(P.first) != I;
});
std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
[&](const ValPair &P) -> Value * {
return lookupOperandLeader(P.first);
});
return E;
}
bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
bool AllConstant = true;
if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
E->setType(GEP->getSourceElementType());
else
E->setType(I->getType());
E->setOpcode(I->getOpcode());
E->allocateOperands(ArgRecycler, ExpressionAllocator);
std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
auto Operand = lookupOperandLeader(O);
AllConstant = AllConstant && isa<Constant>(Operand);
return Operand;
});
return AllConstant;
}
const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Value *Arg1, Value *Arg2,
Instruction *I) const {
auto *E = new (ExpressionAllocator) BasicExpression(2);
const SimplifyQuery Q = SQ.getWithInstruction(I);
E->setType(T);
E->setOpcode(Opcode);
E->allocateOperands(ArgRecycler, ExpressionAllocator);
if (Instruction::isCommutative(Opcode)) {
if (shouldSwapOperands(Arg1, Arg2))
std::swap(Arg1, Arg2);
}
E->op_push_back(lookupOperandLeader(Arg1));
E->op_push_back(lookupOperandLeader(Arg2));
Value *V = simplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), Q);
if (auto Simplified = checkExprResults(E, I, V)) {
addAdditionalUsers(Simplified, I);
return Simplified.Expr;
}
return E;
}
NewGVN::ExprResult NewGVN::checkExprResults(Expression *E, Instruction *I,
Value *V) const {
if (!V)
return ExprResult::none();
if (auto *C = dyn_cast<Constant>(V)) {
if (I)
LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
<< " constant " << *C << "\n");
NumGVNOpsSimplified++;
assert(isa<BasicExpression>(E) &&
"We should always have had a basic expression here");
deleteExpression(E);
return ExprResult::some(createConstantExpression(C));
} else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
if (I)
LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
<< " variable " << *V << "\n");
deleteExpression(E);
return ExprResult::some(createVariableExpression(V));
}
CongruenceClass *CC = ValueToClass.lookup(V);
if (CC) {
if (CC->getLeader() && CC->getLeader() != I) {
return ExprResult::some(createVariableOrConstant(CC->getLeader()), V);
}
if (CC->getDefiningExpr()) {
if (I)
LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
<< " expression " << *CC->getDefiningExpr() << "\n");
NumGVNOpsSimplified++;
deleteExpression(E);
return ExprResult::some(CC->getDefiningExpr(), V);
}
}
return ExprResult::none();
}
NewGVN::ExprResult NewGVN::createExpression(Instruction *I) const {
auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
const SimplifyQuery Q = SQ.getWithInstruction(I);
bool AllConstant = setBasicExpressionInfo(I, E);
if (I->isCommutative()) {
assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
E->swapOperands(0, 1);
}
if (auto *CI = dyn_cast<CmpInst>(I)) {
CmpInst::Predicate Predicate = CI->getPredicate();
if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
E->swapOperands(0, 1);
Predicate = CmpInst::getSwappedPredicate(Predicate);
}
E->setOpcode((CI->getOpcode() << 8) | Predicate);
assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
"Wrong types on cmp instruction");
assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Value *V =
simplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), Q);
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
} else if (isa<SelectInst>(I)) {
if (isa<Constant>(E->getOperand(0)) ||
E->getOperand(1) == E->getOperand(2)) {
assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
E->getOperand(2)->getType() == I->getOperand(2)->getType());
Value *V = simplifySelectInst(E->getOperand(0), E->getOperand(1),
E->getOperand(2), Q);
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
}
} else if (I->isBinaryOp()) {
Value *V =
simplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), Q);
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
} else if (auto *CI = dyn_cast<CastInst>(I)) {
Value *V =
simplifyCastInst(CI->getOpcode(), E->getOperand(0), CI->getType(), Q);
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
} else if (auto *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Value *V =
simplifyGEPInst(GEPI->getSourceElementType(), *E->op_begin(),
makeArrayRef(std::next(E->op_begin()), E->op_end()),
GEPI->isInBounds(), Q);
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
} else if (AllConstant) {
SmallVector<Constant *, 8> C;
for (Value *Arg : E->operands())
C.emplace_back(cast<Constant>(Arg));
if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
if (auto Simplified = checkExprResults(E, I, V))
return Simplified;
}
return ExprResult::some(E);
}
const AggregateValueExpression *
NewGVN::createAggregateValueExpression(Instruction *I) const {
if (auto *II = dyn_cast<InsertValueInst>(I)) {
auto *E = new (ExpressionAllocator)
AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
setBasicExpressionInfo(I, E);
E->allocateIntOperands(ExpressionAllocator);
std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
return E;
} else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
auto *E = new (ExpressionAllocator)
AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
setBasicExpressionInfo(EI, E);
E->allocateIntOperands(ExpressionAllocator);
std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
return E;
}
llvm_unreachable("Unhandled type of aggregate value operation");
}
const DeadExpression *NewGVN::createDeadExpression() const {
return SingletonDeadExpression;
}
const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
auto *E = new (ExpressionAllocator) VariableExpression(V);
E->setOpcode(V->getValueID());
return E;
}
const Expression *NewGVN::createVariableOrConstant(Value *V) const {
if (auto *C = dyn_cast<Constant>(V))
return createConstantExpression(C);
return createVariableExpression(V);
}
const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
auto *E = new (ExpressionAllocator) ConstantExpression(C);
E->setOpcode(C->getValueID());
return E;
}
const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
auto *E = new (ExpressionAllocator) UnknownExpression(I);
E->setOpcode(I->getOpcode());
return E;
}
const CallExpression *
NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
auto *E =
new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
setBasicExpressionInfo(CI, E);
return E;
}
bool NewGVN::someEquivalentDominates(const Instruction *Inst,
const Instruction *U) const {
auto *CC = ValueToClass.lookup(Inst);
if (!CC)
return false;
if (alwaysAvailable(CC->getLeader()))
return true;
if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
return true;
if (CC->getNextLeader().first &&
DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
return true;
return llvm::any_of(*CC, [&](const Value *Member) {
return Member != CC->getLeader() &&
DT->dominates(cast<Instruction>(Member), U);
});
}
Value *NewGVN::lookupOperandLeader(Value *V) const {
CongruenceClass *CC = ValueToClass.lookup(V);
if (CC) {
if (CC == TOPClass)
return PoisonValue::get(V->getType());
return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
}
return V;
}
const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
auto *CC = getMemoryClass(MA);
assert(CC->getMemoryLeader() &&
"Every MemoryAccess should be mapped to a congruence class with a "
"representative memory access");
return CC->getMemoryLeader();
}
bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
return getMemoryClass(MA) == TOPClass;
}
LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
LoadInst *LI,
const MemoryAccess *MA) const {
auto *E =
new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
E->allocateOperands(ArgRecycler, ExpressionAllocator);
E->setType(LoadType);
E->setOpcode(0);
E->op_push_back(PointerOp);
return E;
}
const StoreExpression *
NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
auto *E = new (ExpressionAllocator)
StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
E->allocateOperands(ArgRecycler, ExpressionAllocator);
E->setType(SI->getValueOperand()->getType());
E->setOpcode(0);
E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
return E;
}
const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
auto *SI = cast<StoreInst>(I);
auto *StoreAccess = getMemoryAccess(SI);
const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
if (EnableStoreRefinement)
StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
StoreRHS = lookupMemoryLeader(StoreRHS);
if (StoreRHS != StoreAccess->getDefiningAccess())
addMemoryUsers(StoreRHS, StoreAccess);
if (StoreRHS == StoreAccess)
StoreRHS = MSSA->getLiveOnEntryDef();
if (SI->isSimple()) {
const auto *LastStore = createStoreExpression(SI, StoreRHS);
const auto *LastCC = ExpressionToClass.lookup(LastStore);
if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
return LastStore;
if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
if ((lookupOperandLeader(LI->getPointerOperand()) ==
LastStore->getOperand(0)) &&
(lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
StoreRHS))
return LastStore;
deleteExpression(LastStore);
}
return createStoreExpression(SI, StoreAccess);
}
const Expression *
NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
LoadInst *LI, Instruction *DepInst,
MemoryAccess *DefiningAccess) const {
assert((!LI || LI->isSimple()) && "Not a simple load");
if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
if (LI->isAtomic() > DepSI->isAtomic() ||
LoadType == DepSI->getValueOperand()->getType())
return nullptr;
int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
if (Offset >= 0) {
if (auto *C = dyn_cast<Constant>(
lookupOperandLeader(DepSI->getValueOperand()))) {
if (Constant *Res =
getConstantStoreValueForLoad(C, Offset, LoadType, DL)) {
LLVM_DEBUG(dbgs() << "Coercing load from store " << *DepSI
<< " to constant " << *Res << "\n");
return createConstantExpression(Res);
}
}
}
} else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
if (LI->isAtomic() > DepLI->isAtomic())
return nullptr;
int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
if (Offset >= 0) {
if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
if (auto *PossibleConstant =
getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
LLVM_DEBUG(dbgs() << "Coercing load from load " << *LI
<< " to constant " << *PossibleConstant << "\n");
return createConstantExpression(PossibleConstant);
}
}
} else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
if (Offset >= 0) {
if (auto *PossibleConstant =
getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
LLVM_DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
<< " to constant " << *PossibleConstant << "\n");
return createConstantExpression(PossibleConstant);
}
}
}
if (LoadPtr != lookupOperandLeader(DepInst) &&
!AA->isMustAlias(LoadPtr, DepInst))
return nullptr;
if (isa<AllocaInst>(DepInst)) {
return createConstantExpression(UndefValue::get(LoadType));
}
else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
if (II->getIntrinsicID() == Intrinsic::lifetime_start)
return createConstantExpression(UndefValue::get(LoadType));
} else if (auto *InitVal =
getInitialValueOfAllocation(DepInst, TLI, LoadType))
return createConstantExpression(InitVal);
return nullptr;
}
const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
auto *LI = cast<LoadInst>(I);
if (!LI->isSimple())
return nullptr;
Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
if (isa<UndefValue>(LoadAddressLeader))
return createConstantExpression(PoisonValue::get(LI->getType()));
MemoryAccess *OriginalAccess = getMemoryAccess(I);
MemoryAccess *DefiningAccess =
MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
Instruction *DefiningInst = MD->getMemoryInst();
if (!ReachableBlocks.count(DefiningInst->getParent()))
return createConstantExpression(PoisonValue::get(LI->getType()));
if (const auto *CoercionResult =
performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
DefiningInst, DefiningAccess))
return CoercionResult;
}
}
const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
DefiningAccess);
if (LE->getMemoryLeader() != DefiningAccess)
addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
return LE;
}
NewGVN::ExprResult
NewGVN::performSymbolicPredicateInfoEvaluation(IntrinsicInst *I) const {
auto *PI = PredInfo->getPredicateInfoFor(I);
if (!PI)
return ExprResult::none();
LLVM_DEBUG(dbgs() << "Found predicate info from instruction !\n");
const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
if (!Constraint)
return ExprResult::none();
CmpInst::Predicate Predicate = Constraint->Predicate;
Value *CmpOp0 = I->getOperand(0);
Value *CmpOp1 = Constraint->OtherOp;
Value *FirstOp = lookupOperandLeader(CmpOp0);
Value *SecondOp = lookupOperandLeader(CmpOp1);
Value *AdditionallyUsedValue = CmpOp0;
if (shouldSwapOperandsForIntrinsic(FirstOp, SecondOp, I)) {
std::swap(FirstOp, SecondOp);
Predicate = CmpInst::getSwappedPredicate(Predicate);
AdditionallyUsedValue = CmpOp1;
}
if (Predicate == CmpInst::ICMP_EQ)
return ExprResult::some(createVariableOrConstant(FirstOp),
AdditionallyUsedValue, PI);
if (Predicate == CmpInst::FCMP_OEQ && isa<ConstantFP>(FirstOp) &&
!cast<ConstantFP>(FirstOp)->isZero())
return ExprResult::some(createConstantExpression(cast<Constant>(FirstOp)),
AdditionallyUsedValue, PI);
return ExprResult::none();
}
NewGVN::ExprResult NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
auto *CI = cast<CallInst>(I);
if (auto *II = dyn_cast<IntrinsicInst>(I)) {
if (auto *ReturnedValue = II->getReturnedArgOperand()) {
if (II->getIntrinsicID() == Intrinsic::ssa_copy)
if (auto Res = performSymbolicPredicateInfoEvaluation(II))
return Res;
return ExprResult::some(createVariableOrConstant(ReturnedValue));
}
}
if (AA->doesNotAccessMemory(CI)) {
return ExprResult::some(
createCallExpression(CI, TOPClass->getMemoryLeader()));
} else if (AA->onlyReadsMemory(CI)) {
if (auto *MA = MSSA->getMemoryAccess(CI)) {
auto *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(MA);
return ExprResult::some(createCallExpression(CI, DefiningAccess));
} else return ExprResult::some(
createCallExpression(CI, TOPClass->getMemoryLeader()));
}
return ExprResult::none();
}
CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
auto *Result = MemoryAccessToClass.lookup(MA);
assert(Result && "Should have found memory class");
return Result;
}
bool NewGVN::setMemoryClass(const MemoryAccess *From,
CongruenceClass *NewClass) {
assert(NewClass &&
"Every MemoryAccess should be getting mapped to a non-null class");
LLVM_DEBUG(dbgs() << "Setting " << *From);
LLVM_DEBUG(dbgs() << " equivalent to congruence class ");
LLVM_DEBUG(dbgs() << NewClass->getID()
<< " with current MemoryAccess leader ");
LLVM_DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
auto LookupResult = MemoryAccessToClass.find(From);
bool Changed = false;
if (LookupResult != MemoryAccessToClass.end()) {
auto *OldClass = LookupResult->second;
if (OldClass != NewClass) {
if (auto *MP = dyn_cast<MemoryPhi>(From)) {
OldClass->memory_erase(MP);
NewClass->memory_insert(MP);
if (OldClass->getMemoryLeader() == From) {
if (OldClass->definesNoMemory()) {
OldClass->setMemoryLeader(nullptr);
} else {
OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
LLVM_DEBUG(dbgs() << "Memory class leader change for class "
<< OldClass->getID() << " to "
<< *OldClass->getMemoryLeader()
<< " due to removal of a memory member " << *From
<< "\n");
markMemoryLeaderChangeTouched(OldClass);
}
}
}
LookupResult->second = NewClass;
Changed = true;
}
}
return Changed;
}
bool NewGVN::isCycleFree(const Instruction *I) const {
auto ICS = InstCycleState.lookup(I);
if (ICS == ICS_Unknown) {
SCCFinder.Start(I);
auto &SCC = SCCFinder.getComponentFor(I);
if (SCC.size() == 1)
InstCycleState.insert({I, ICS_CycleFree});
else {
bool AllPhis = llvm::all_of(SCC, [](const Value *V) {
return isa<PHINode>(V) || isCopyOfAPHI(V);
});
ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
for (auto *Member : SCC)
if (auto *MemberPhi = dyn_cast<PHINode>(Member))
InstCycleState.insert({MemberPhi, ICS});
}
}
if (ICS == ICS_Cycle)
return false;
return true;
}
const Expression *
NewGVN::performSymbolicPHIEvaluation(ArrayRef<ValPair> PHIOps,
Instruction *I,
BasicBlock *PHIBlock) const {
bool HasBackedge = false;
bool OriginalOpsConstant = true;
auto *E = cast<PHIExpression>(createPHIExpression(
PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
bool HasUndef = false, HasPoison = false;
auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
if (isa<PoisonValue>(Arg)) {
HasPoison = true;
return false;
}
if (isa<UndefValue>(Arg)) {
HasUndef = true;
return false;
}
return true;
});
if (Filtered.empty()) {
if (HasUndef) {
LLVM_DEBUG(
dbgs() << "PHI Node " << *I
<< " has no non-undef arguments, valuing it as undef\n");
return createConstantExpression(UndefValue::get(I->getType()));
}
if (HasPoison) {
LLVM_DEBUG(
dbgs() << "PHI Node " << *I
<< " has no non-poison arguments, valuing it as poison\n");
return createConstantExpression(PoisonValue::get(I->getType()));
}
LLVM_DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
deleteExpression(E);
return createDeadExpression();
}
Value *AllSameValue = *(Filtered.begin());
++Filtered.begin();
if (llvm::all_of(Filtered, [&](Value *Arg) { return Arg == AllSameValue; })) {
if (HasUndef && !isGuaranteedNotToBePoison(AllSameValue, AC, nullptr, DT))
return E;
if (HasPoison || HasUndef) {
if (HasBackedge && !OriginalOpsConstant &&
!isa<UndefValue>(AllSameValue) && !isCycleFree(I))
return E;
if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
if (!someEquivalentDominates(AllSameInst, I))
return E;
}
if (isa<Instruction>(AllSameValue) &&
InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
return E;
NumGVNPhisAllSame++;
LLVM_DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
<< "\n");
deleteExpression(E);
return createVariableOrConstant(AllSameValue);
}
return E;
}
const Expression *
NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
auto *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
return createBinaryExpression(WO->getBinaryOp(), EI->getType(),
WO->getLHS(), WO->getRHS(), I);
}
return createAggregateValueExpression(I);
}
NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
auto *CI = cast<CmpInst>(I);
auto Op0 = lookupOperandLeader(CI->getOperand(0));
auto Op1 = lookupOperandLeader(CI->getOperand(1));
auto OurPredicate = CI->getPredicate();
if (shouldSwapOperands(Op0, Op1)) {
std::swap(Op0, Op1);
OurPredicate = CI->getSwappedPredicate();
}
const PredicateBase *LastPredInfo = nullptr;
auto *CmpPI = PredInfo->getPredicateInfoFor(I);
if (isa_and_nonnull<PredicateAssume>(CmpPI))
return ExprResult::some(
createConstantExpression(ConstantInt::getTrue(CI->getType())));
if (Op0 == Op1) {
if (CI->isTrueWhenEqual())
return ExprResult::some(
createConstantExpression(ConstantInt::getTrue(CI->getType())));
else if (CI->isFalseWhenEqual())
return ExprResult::some(
createConstantExpression(ConstantInt::getFalse(CI->getType())));
}
for (const auto &Op : CI->operands()) {
auto *PI = PredInfo->getPredicateInfoFor(Op);
if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
if (PI == LastPredInfo)
continue;
LastPredInfo = PI;
if (!DT->dominates(PBranch->To, getBlockForValue(I)))
continue;
auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
if (!BranchCond)
continue;
auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
auto BranchPredicate = BranchCond->getPredicate();
if (shouldSwapOperands(BranchOp0, BranchOp1)) {
std::swap(BranchOp0, BranchOp1);
BranchPredicate = BranchCond->getSwappedPredicate();
}
if (BranchOp0 == Op0 && BranchOp1 == Op1) {
if (PBranch->TrueEdge) {
if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
OurPredicate)) {
return ExprResult::some(
createConstantExpression(ConstantInt::getTrue(CI->getType())),
PI);
}
if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
OurPredicate)) {
return ExprResult::some(
createConstantExpression(ConstantInt::getFalse(CI->getType())),
PI);
}
} else {
if (BranchPredicate == OurPredicate) {
return ExprResult::some(
createConstantExpression(ConstantInt::getFalse(CI->getType())),
PI);
} else if (BranchPredicate ==
CmpInst::getInversePredicate(OurPredicate)) {
return ExprResult::some(
createConstantExpression(ConstantInt::getTrue(CI->getType())),
PI);
}
}
}
}
}
return createExpression(I);
}
NewGVN::ExprResult
NewGVN::performSymbolicEvaluation(Value *V,
SmallPtrSetImpl<Value *> &Visited) const {
const Expression *E = nullptr;
if (auto *C = dyn_cast<Constant>(V))
E = createConstantExpression(C);
else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
E = createVariableExpression(V);
} else {
auto *I = cast<Instruction>(V);
switch (I->getOpcode()) {
case Instruction::ExtractValue:
case Instruction::InsertValue:
E = performSymbolicAggrValueEvaluation(I);
break;
case Instruction::PHI: {
SmallVector<ValPair, 3> Ops;
auto *PN = cast<PHINode>(I);
for (unsigned i = 0; i < PN->getNumOperands(); ++i)
Ops.push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
sortPHIOps(Ops);
E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
} break;
case Instruction::Call:
return performSymbolicCallEvaluation(I);
break;
case Instruction::Store:
E = performSymbolicStoreEvaluation(I);
break;
case Instruction::Load:
E = performSymbolicLoadEvaluation(I);
break;
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
return createExpression(I);
break;
case Instruction::ICmp:
case Instruction::FCmp:
return performSymbolicCmpEvaluation(I);
break;
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::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::Select:
case Instruction::ExtractElement:
case Instruction::InsertElement:
case Instruction::GetElementPtr:
return createExpression(I);
break;
case Instruction::ShuffleVector:
return ExprResult::none();
default:
return ExprResult::none();
}
}
return ExprResult::some(E);
}
template <typename Map, typename KeyType>
void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
const auto Result = M.find_as(Key);
if (Result != M.end()) {
for (const typename Map::mapped_type::value_type Mapped : Result->second)
TouchedInstructions.set(InstrToDFSNum(Mapped));
M.erase(Result);
}
}
void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
assert(User && To != User);
if (isa<Instruction>(To))
AdditionalUsers[To].insert(User);
}
void NewGVN::addAdditionalUsers(ExprResult &Res, Instruction *User) const {
if (Res.ExtraDep && Res.ExtraDep != User)
addAdditionalUsers(Res.ExtraDep, User);
Res.ExtraDep = nullptr;
if (Res.PredDep) {
if (const auto *PBranch = dyn_cast<PredicateBranch>(Res.PredDep))
PredicateToUsers[PBranch->Condition].insert(User);
else if (const auto *PAssume = dyn_cast<PredicateAssume>(Res.PredDep))
PredicateToUsers[PAssume->Condition].insert(User);
}
Res.PredDep = nullptr;
}
void NewGVN::markUsersTouched(Value *V) {
for (auto *User : V->users()) {
assert(isa<Instruction>(User) && "Use of value not within an instruction?");
TouchedInstructions.set(InstrToDFSNum(User));
}
touchAndErase(AdditionalUsers, V);
}
void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
LLVM_DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
MemoryToUsers[To].insert(U);
}
void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
TouchedInstructions.set(MemoryToDFSNum(MA));
}
void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
if (isa<MemoryUse>(MA))
return;
for (auto U : MA->users())
TouchedInstructions.set(MemoryToDFSNum(U));
touchAndErase(MemoryToUsers, MA);
}
void NewGVN::markPredicateUsersTouched(Instruction *I) {
touchAndErase(PredicateToUsers, I);
}
void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
for (auto M : CC->memory())
markMemoryDefTouched(M);
}
void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
for (auto M : *CC) {
if (auto *I = dyn_cast<Instruction>(M))
TouchedInstructions.set(InstrToDFSNum(I));
LeaderChanges.insert(M);
}
}
template <class T, class Range>
T *NewGVN::getMinDFSOfRange(const Range &R) const {
std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
for (const auto X : R) {
auto DFSNum = InstrToDFSNum(X);
if (DFSNum < MinDFS.second)
MinDFS = {X, DFSNum};
}
return MinDFS.first;
}
const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
if (CC->getStoreCount() > 0) {
if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
return getMemoryAccess(NL);
auto *V = getMinDFSOfRange<Value>(make_filter_range(
*CC, [&](const Value *V) { return isa<StoreInst>(V); }));
return getMemoryAccess(cast<StoreInst>(V));
}
assert(CC->getStoreCount() == 0);
if (CC->memory_size() == 1)
return *CC->memory_begin();
return getMinDFSOfRange<const MemoryPhi>(CC->memory());
}
Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
if (CC->size() == 1 || CC == TOPClass) {
return *(CC->begin());
} else if (CC->getNextLeader().first) {
++NumGVNAvoidedSortedLeaderChanges;
return CC->getNextLeader().first;
} else {
++NumGVNSortedLeaderChanges;
return getMinDFSOfRange<Value>(*CC);
}
}
void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
MemoryAccess *InstMA,
CongruenceClass *OldClass,
CongruenceClass *NewClass) {
assert((!InstMA || !OldClass->getMemoryLeader() ||
OldClass->getLeader() != I ||
MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
MemoryAccessToClass.lookup(InstMA)) &&
"Representative MemoryAccess mismatch");
if (!NewClass->getMemoryLeader()) {
assert(NewClass->size() == 1 ||
(isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
NewClass->setMemoryLeader(InstMA);
LLVM_DEBUG(dbgs() << "Memory class leader change for class "
<< NewClass->getID()
<< " due to new memory instruction becoming leader\n");
markMemoryLeaderChangeTouched(NewClass);
}
setMemoryClass(InstMA, NewClass);
if (OldClass->getMemoryLeader() == InstMA) {
if (!OldClass->definesNoMemory()) {
OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
LLVM_DEBUG(dbgs() << "Memory class leader change for class "
<< OldClass->getID() << " to "
<< *OldClass->getMemoryLeader()
<< " due to removal of old leader " << *InstMA << "\n");
markMemoryLeaderChangeTouched(OldClass);
} else
OldClass->setMemoryLeader(nullptr);
}
}
void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
CongruenceClass *OldClass,
CongruenceClass *NewClass) {
if (I == OldClass->getNextLeader().first)
OldClass->resetNextLeader();
OldClass->erase(I);
NewClass->insert(I);
if (NewClass->getLeader() != I)
NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
if (auto *SI = dyn_cast<StoreInst>(I)) {
OldClass->decStoreCount();
if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
if (auto *SE = dyn_cast<StoreExpression>(E)) {
NewClass->setStoredValue(SE->getStoredValue());
markValueLeaderChangeTouched(NewClass);
LLVM_DEBUG(dbgs() << "Changing leader of congruence class "
<< NewClass->getID() << " from "
<< *NewClass->getLeader() << " to " << *SI
<< " because store joined class\n");
NewClass->setLeader(SI);
}
}
NewClass->incStoreCount();
}
auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
if (InstMA)
moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
ValueToClass[I] = NewClass;
if (OldClass->empty() && OldClass != TOPClass) {
if (OldClass->getDefiningExpr()) {
LLVM_DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
<< " from table\n");
auto Iter = ExpressionToClass.find_as(
ExactEqualsExpression(*OldClass->getDefiningExpr()));
if (Iter != ExpressionToClass.end())
ExpressionToClass.erase(Iter);
#ifdef EXPENSIVE_CHECKS
assert(
(*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
"We erased the expression we just inserted, which should not happen");
#endif
}
} else if (OldClass->getLeader() == I) {
LLVM_DEBUG(dbgs() << "Value class leader change for class "
<< OldClass->getID() << "\n");
++NumGVNLeaderChanges;
if (OldClass->getStoreCount() == 0) {
if (OldClass->getStoredValue())
OldClass->setStoredValue(nullptr);
}
OldClass->setLeader(getNextValueLeader(OldClass));
OldClass->resetNextLeader();
markValueLeaderChangeTouched(OldClass);
}
}
void NewGVN::markPhiOfOpsChanged(const Expression *E) {
touchAndErase(ExpressionToPhiOfOps, E);
}
void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
CongruenceClass *IClass = ValueToClass.lookup(I);
assert(IClass && "Should have found a IClass");
assert(!IClass->isDead() && "Found a dead class");
CongruenceClass *EClass = nullptr;
if (const auto *VE = dyn_cast<VariableExpression>(E)) {
EClass = ValueToClass.lookup(VE->getVariableValue());
} else if (isa<DeadExpression>(E)) {
EClass = TOPClass;
}
if (!EClass) {
auto lookupResult = ExpressionToClass.insert({E, nullptr});
if (lookupResult.second) {
CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
auto place = lookupResult.first;
place->second = NewClass;
if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
NewClass->setLeader(CE->getConstantValue());
} else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
StoreInst *SI = SE->getStoreInst();
NewClass->setLeader(SI);
NewClass->setStoredValue(SE->getStoredValue());
} else {
NewClass->setLeader(I);
}
assert(!isa<VariableExpression>(E) &&
"VariableExpression should have been handled already");
EClass = NewClass;
LLVM_DEBUG(dbgs() << "Created new congruence class for " << *I
<< " using expression " << *E << " at "
<< NewClass->getID() << " and leader "
<< *(NewClass->getLeader()));
if (NewClass->getStoredValue())
LLVM_DEBUG(dbgs() << " and stored value "
<< *(NewClass->getStoredValue()));
LLVM_DEBUG(dbgs() << "\n");
} else {
EClass = lookupResult.first->second;
if (isa<ConstantExpression>(E))
assert((isa<Constant>(EClass->getLeader()) ||
(EClass->getStoredValue() &&
isa<Constant>(EClass->getStoredValue()))) &&
"Any class with a constant expression should have a "
"constant leader");
assert(EClass && "Somehow don't have an eclass");
assert(!EClass->isDead() && "We accidentally looked up a dead class");
}
}
bool ClassChanged = IClass != EClass;
bool LeaderChanged = LeaderChanges.erase(I);
if (ClassChanged || LeaderChanged) {
LLVM_DEBUG(dbgs() << "New class " << EClass->getID() << " for expression "
<< *E << "\n");
if (ClassChanged) {
moveValueToNewCongruenceClass(I, E, IClass, EClass);
markPhiOfOpsChanged(E);
}
markUsersTouched(I);
if (MemoryAccess *MA = getMemoryAccess(I))
markMemoryUsersTouched(MA);
if (auto *CI = dyn_cast<CmpInst>(I))
markPredicateUsersTouched(CI);
}
if (ClassChanged && isa<StoreInst>(I)) {
auto *OldE = ValueToExpression.lookup(I);
if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
if (Iter != ExpressionToClass.end())
ExpressionToClass.erase(Iter);
}
}
ValueToExpression[I] = E;
}
void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
if (ReachableEdges.insert({From, To}).second) {
if (ReachableBlocks.insert(To).second) {
LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
<< " marked reachable\n");
const auto &InstRange = BlockInstRange.lookup(To);
TouchedInstructions.set(InstRange.first, InstRange.second);
} else {
LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
<< " was reachable, but new edge {"
<< getBlockName(From) << "," << getBlockName(To)
<< "} to it found\n");
if (MemoryAccess *MemPhi = getMemoryAccess(To))
TouchedInstructions.set(InstrToDFSNum(MemPhi));
for (auto InstNum : RevisitOnReachabilityChange[To])
TouchedInstructions.set(InstNum);
}
}
}
Value *NewGVN::findConditionEquivalence(Value *Cond) const {
auto Result = lookupOperandLeader(Cond);
return isa<Constant>(Result) ? Result : nullptr;
}
void NewGVN::processOutgoingEdges(Instruction *TI, BasicBlock *B) {
Value *Cond;
BasicBlock *TrueSucc, *FalseSucc;
if (match(TI, m_Br(m_Value(Cond), TrueSucc, FalseSucc))) {
Value *CondEvaluated = findConditionEquivalence(Cond);
if (!CondEvaluated) {
if (auto *I = dyn_cast<Instruction>(Cond)) {
SmallPtrSet<Value *, 4> Visited;
auto Res = performSymbolicEvaluation(I, Visited);
if (const auto *CE = dyn_cast_or_null<ConstantExpression>(Res.Expr)) {
CondEvaluated = CE->getConstantValue();
addAdditionalUsers(Res, I);
} else {
Res.ExtraDep = nullptr;
}
} else if (isa<ConstantInt>(Cond)) {
CondEvaluated = Cond;
}
}
ConstantInt *CI;
if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
if (CI->isOne()) {
LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
<< " evaluated to true\n");
updateReachableEdge(B, TrueSucc);
} else if (CI->isZero()) {
LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
<< " evaluated to false\n");
updateReachableEdge(B, FalseSucc);
}
} else {
updateReachableEdge(B, TrueSucc);
updateReachableEdge(B, FalseSucc);
}
} else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Value *SwitchCond = SI->getCondition();
Value *CondEvaluated = findConditionEquivalence(SwitchCond);
if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
auto *CondVal = cast<ConstantInt>(CondEvaluated);
auto Case = *SI->findCaseValue(CondVal);
if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
updateReachableEdge(B, SI->getDefaultDest());
return;
}
BasicBlock *TargetBlock = Case.getCaseSuccessor();
updateReachableEdge(B, TargetBlock);
} else {
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
BasicBlock *TargetBlock = SI->getSuccessor(i);
updateReachableEdge(B, TargetBlock);
}
}
} else {
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
BasicBlock *TargetBlock = TI->getSuccessor(i);
updateReachableEdge(B, TargetBlock);
}
auto *MA = getMemoryAccess(TI);
if (MA && !isa<MemoryUse>(MA)) {
auto *CC = ensureLeaderOfMemoryClass(MA);
if (setMemoryClass(MA, CC))
markMemoryUsersTouched(MA);
}
}
}
void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
InstrDFS.erase(PHITemp);
TempToBlock.erase(PHITemp);
RealToTemp.erase(I);
}
void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
Instruction *ExistingValue) {
InstrDFS[Op] = InstrToDFSNum(ExistingValue);
AllTempInstructions.insert(Op);
TempToBlock[Op] = BB;
RealToTemp[ExistingValue] = Op;
for (auto *U : ExistingValue->users())
if (auto *UI = dyn_cast<Instruction>(U))
PHINodeUses.insert(UI);
}
static bool okayForPHIOfOps(const Instruction *I) {
if (!EnablePhiOfOps)
return false;
return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
isa<LoadInst>(I);
}
bool NewGVN::OpIsSafeForPHIOfOpsHelper(
Value *V, const BasicBlock *PHIBlock,
SmallPtrSetImpl<const Value *> &Visited,
SmallVectorImpl<Instruction *> &Worklist) {
if (!isa<Instruction>(V))
return true;
auto OISIt = OpSafeForPHIOfOps.find(V);
if (OISIt != OpSafeForPHIOfOps.end())
return OISIt->second;
if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
OpSafeForPHIOfOps.insert({V, true});
return true;
}
if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
OpSafeForPHIOfOps.insert({V, false});
return false;
}
auto *OrigI = cast<Instruction>(V);
if (OrigI->mayReadFromMemory())
return false;
for (auto *Op : OrigI->operand_values()) {
if (!isa<Instruction>(Op))
continue;
auto OISIt = OpSafeForPHIOfOps.find(OrigI);
if (OISIt != OpSafeForPHIOfOps.end()) {
if (!OISIt->second) {
OpSafeForPHIOfOps.insert({V, false});
return false;
}
continue;
}
if (!Visited.insert(Op).second)
continue;
Worklist.push_back(cast<Instruction>(Op));
}
return true;
}
bool NewGVN::OpIsSafeForPHIOfOps(Value *V, const BasicBlock *PHIBlock,
SmallPtrSetImpl<const Value *> &Visited) {
SmallVector<Instruction *, 4> Worklist;
if (!OpIsSafeForPHIOfOpsHelper(V, PHIBlock, Visited, Worklist))
return false;
while (!Worklist.empty()) {
auto *I = Worklist.pop_back_val();
if (!OpIsSafeForPHIOfOpsHelper(I, PHIBlock, Visited, Worklist))
return false;
}
OpSafeForPHIOfOps.insert({V, true});
return true;
}
Value *NewGVN::findLeaderForInst(Instruction *TransInst,
SmallPtrSetImpl<Value *> &Visited,
MemoryAccess *MemAccess, Instruction *OrigInst,
BasicBlock *PredBB) {
unsigned IDFSNum = InstrToDFSNum(OrigInst);
AllTempInstructions.insert(TransInst);
TempToBlock.insert({TransInst, PredBB});
InstrDFS.insert({TransInst, IDFSNum});
auto Res = performSymbolicEvaluation(TransInst, Visited);
const Expression *E = Res.Expr;
addAdditionalUsers(Res, OrigInst);
InstrDFS.erase(TransInst);
AllTempInstructions.erase(TransInst);
TempToBlock.erase(TransInst);
if (MemAccess)
TempToMemory.erase(TransInst);
if (!E)
return nullptr;
auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
if (!FoundVal) {
ExpressionToPhiOfOps[E].insert(OrigInst);
LLVM_DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
<< " in block " << getBlockName(PredBB) << "\n");
return nullptr;
}
if (auto *SI = dyn_cast<StoreInst>(FoundVal))
FoundVal = SI->getValueOperand();
return FoundVal;
}
const Expression *
NewGVN::makePossiblePHIOfOps(Instruction *I,
SmallPtrSetImpl<Value *> &Visited) {
if (!okayForPHIOfOps(I))
return nullptr;
if (!Visited.insert(I).second)
return nullptr;
if (!isCycleFree(I))
return nullptr;
SmallPtrSet<const Value *, 8> ProcessedPHIs;
auto *MemAccess = getMemoryAccess(I);
if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
MemAccess->getDefiningAccess()->getBlock() == I->getParent())
return nullptr;
SmallPtrSet<const Value *, 10> VisitedOps;
SmallVector<Value *, 4> Ops(I->operand_values());
BasicBlock *SamePHIBlock = nullptr;
PHINode *OpPHI = nullptr;
if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
return nullptr;
for (auto *Op : Ops) {
if (!isa<PHINode>(Op)) {
auto *ValuePHI = RealToTemp.lookup(Op);
if (!ValuePHI)
continue;
LLVM_DEBUG(dbgs() << "Found possible dependent phi of ops\n");
Op = ValuePHI;
}
OpPHI = cast<PHINode>(Op);
if (!SamePHIBlock) {
SamePHIBlock = getBlockForValue(OpPHI);
} else if (SamePHIBlock != getBlockForValue(OpPHI)) {
LLVM_DEBUG(
dbgs()
<< "PHIs for operands are not all in the same block, aborting\n");
return nullptr;
}
if (OpPHI->getNumOperands() == 1) {
OpPHI = nullptr;
continue;
}
}
if (!OpPHI)
return nullptr;
SmallVector<ValPair, 4> PHIOps;
SmallPtrSet<Value *, 4> Deps;
auto *PHIBlock = getBlockForValue(OpPHI);
RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
for (unsigned PredNum = 0; PredNum < OpPHI->getNumOperands(); ++PredNum) {
auto *PredBB = OpPHI->getIncomingBlock(PredNum);
Value *FoundVal = nullptr;
SmallPtrSet<Value *, 4> CurrentDeps;
if (ReachableEdges.count({PredBB, PHIBlock})) {
Instruction *ValueOp = I->clone();
if (MemAccess)
TempToMemory.insert({ValueOp, MemAccess});
bool SafeForPHIOfOps = true;
VisitedOps.clear();
for (auto &Op : ValueOp->operands()) {
auto *OrigOp = &*Op;
if (isa<PHINode>(Op)) {
Op = Op->DoPHITranslation(PHIBlock, PredBB);
if (Op != OrigOp && Op != I)
CurrentDeps.insert(Op);
} else if (auto *ValuePHI = RealToTemp.lookup(Op)) {
if (getBlockForValue(ValuePHI) == PHIBlock)
Op = ValuePHI->getIncomingValueForBlock(PredBB);
}
SafeForPHIOfOps =
SafeForPHIOfOps &&
(Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
}
FoundVal = !SafeForPHIOfOps ? nullptr
: findLeaderForInst(ValueOp, Visited,
MemAccess, I, PredBB);
ValueOp->deleteValue();
if (!FoundVal) {
if (SafeForPHIOfOps)
for (auto Dep : CurrentDeps)
addAdditionalUsers(Dep, I);
return nullptr;
}
Deps.insert(CurrentDeps.begin(), CurrentDeps.end());
} else {
LLVM_DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
<< getBlockName(PredBB)
<< " because the block is unreachable\n");
FoundVal = PoisonValue::get(I->getType());
RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
}
PHIOps.push_back({FoundVal, PredBB});
LLVM_DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
<< getBlockName(PredBB) << "\n");
}
for (auto Dep : Deps)
addAdditionalUsers(Dep, I);
sortPHIOps(PHIOps);
auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
LLVM_DEBUG(
dbgs()
<< "Not creating real PHI of ops because it simplified to existing "
"value or constant\n");
for (auto &O : PHIOps)
addAdditionalUsers(O.first, I);
return E;
}
auto *ValuePHI = RealToTemp.lookup(I);
bool NewPHI = false;
if (!ValuePHI) {
ValuePHI =
PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
addPhiOfOps(ValuePHI, PHIBlock, I);
NewPHI = true;
NumGVNPHIOfOpsCreated++;
}
if (NewPHI) {
for (auto PHIOp : PHIOps)
ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
} else {
TempToBlock[ValuePHI] = PHIBlock;
unsigned int i = 0;
for (auto PHIOp : PHIOps) {
ValuePHI->setIncomingValue(i, PHIOp.first);
ValuePHI->setIncomingBlock(i, PHIOp.second);
++i;
}
}
RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
LLVM_DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
<< "\n");
return E;
}
void NewGVN::initializeCongruenceClasses(Function &F) {
NextCongruenceNum = 0;
TOPClass = createCongruenceClass(nullptr, nullptr);
TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
createMemoryClass(MSSA->getLiveOnEntryDef());
for (auto DTN : nodes(DT)) {
BasicBlock *BB = DTN->getBlock();
auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
if (MemoryBlockDefs)
for (const auto &Def : *MemoryBlockDefs) {
MemoryAccessToClass[&Def] = TOPClass;
auto *MD = dyn_cast<MemoryDef>(&Def);
if (!MD) {
const MemoryPhi *MP = cast<MemoryPhi>(&Def);
TOPClass->memory_insert(MP);
MemoryPhiState.insert({MP, MPS_TOP});
}
if (MD && isa<StoreInst>(MD->getMemoryInst()))
TOPClass->incStoreCount();
}
for (auto &I : *BB) {
if (isa<PHINode>(&I))
for (auto *U : I.users())
if (auto *UInst = dyn_cast<Instruction>(U))
if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
PHINodeUses.insert(UInst);
if (I.isTerminator() && I.getType()->isVoidTy())
continue;
TOPClass->insert(&I);
ValueToClass[&I] = TOPClass;
}
}
for (auto &FA : F.args())
createSingletonCongruenceClass(&FA);
}
void NewGVN::cleanupTables() {
for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
LLVM_DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
<< " has " << CongruenceClasses[i]->size()
<< " members\n");
delete CongruenceClasses[i];
CongruenceClasses[i] = nullptr;
}
SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
AllTempInstructions.end());
AllTempInstructions.clear();
for (auto *I : TempInst) {
I->dropAllReferences();
}
while (!TempInst.empty()) {
auto *I = TempInst.pop_back_val();
I->deleteValue();
}
ValueToClass.clear();
ArgRecycler.clear(ExpressionAllocator);
ExpressionAllocator.Reset();
CongruenceClasses.clear();
ExpressionToClass.clear();
ValueToExpression.clear();
RealToTemp.clear();
AdditionalUsers.clear();
ExpressionToPhiOfOps.clear();
TempToBlock.clear();
TempToMemory.clear();
PHINodeUses.clear();
OpSafeForPHIOfOps.clear();
ReachableBlocks.clear();
ReachableEdges.clear();
#ifndef NDEBUG
ProcessedCount.clear();
#endif
InstrDFS.clear();
InstructionsToErase.clear();
DFSToInstr.clear();
BlockInstRange.clear();
TouchedInstructions.clear();
MemoryAccessToClass.clear();
PredicateToUsers.clear();
MemoryToUsers.clear();
RevisitOnReachabilityChange.clear();
IntrinsicInstPred.clear();
}
std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
unsigned Start) {
unsigned End = Start;
if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
InstrDFS[MemPhi] = End++;
DFSToInstr.emplace_back(MemPhi);
}
for (auto &I : *B) {
if (isInstructionTriviallyDead(&I, TLI)) {
InstrDFS[&I] = 0;
LLVM_DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
markInstructionForDeletion(&I);
continue;
}
if (isa<PHINode>(&I))
RevisitOnReachabilityChange[B].set(End);
InstrDFS[&I] = End++;
DFSToInstr.emplace_back(&I);
}
return std::make_pair(Start, End);
}
void NewGVN::updateProcessedCount(const Value *V) {
#ifndef NDEBUG
if (ProcessedCount.count(V) == 0) {
ProcessedCount.insert({V, 1});
} else {
++ProcessedCount[V];
assert(ProcessedCount[V] < 100 &&
"Seem to have processed the same Value a lot");
}
#endif
}
void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
const BasicBlock *PHIBlock = MP->getBlock();
auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
return cast<MemoryAccess>(U) != MP &&
!isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
});
if (Filtered.begin() == Filtered.end()) {
if (setMemoryClass(MP, TOPClass))
markMemoryUsersTouched(MP);
return;
}
auto LookupFunc = [&](const Use &U) {
return lookupMemoryLeader(cast<MemoryAccess>(U));
};
auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
const auto *AllSameValue = *MappedBegin;
++MappedBegin;
bool AllEqual = std::all_of(
MappedBegin, MappedEnd,
[&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
if (AllEqual)
LLVM_DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue
<< "\n");
else
LLVM_DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
CongruenceClass *CC =
AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
auto OldState = MemoryPhiState.lookup(MP);
assert(OldState != MPS_Invalid && "Invalid memory phi state");
auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
MemoryPhiState[MP] = NewState;
if (setMemoryClass(MP, CC) || OldState != NewState)
markMemoryUsersTouched(MP);
}
void NewGVN::valueNumberInstruction(Instruction *I) {
LLVM_DEBUG(dbgs() << "Processing instruction " << *I << "\n");
if (!I->isTerminator()) {
const Expression *Symbolized = nullptr;
SmallPtrSet<Value *, 2> Visited;
if (DebugCounter::shouldExecute(VNCounter)) {
auto Res = performSymbolicEvaluation(I, Visited);
Symbolized = Res.Expr;
addAdditionalUsers(Res, I);
if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
!isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
auto *PHIE = makePossiblePHIOfOps(I, Visited);
if (PHIE) {
Symbolized = PHIE;
} else if (auto *Op = RealToTemp.lookup(I)) {
removePhiOfOps(I, Op);
}
}
} else {
InstrDFS[I] = 0;
}
if (Symbolized == nullptr)
Symbolized = createUnknownExpression(I);
performCongruenceFinding(I, Symbolized);
} else {
if (!I->getType()->isVoidTy()) {
auto *Symbolized = createUnknownExpression(I);
performCongruenceFinding(I, Symbolized);
}
processOutgoingEdges(I, I->getParent());
}
}
bool NewGVN::singleReachablePHIPath(
SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
const MemoryAccess *Second) const {
if (First == Second)
return true;
if (MSSA->isLiveOnEntryDef(First))
return false;
if (!Visited.insert(First).second)
return true;
const auto *EndDef = First;
for (auto *ChainDef : optimized_def_chain(First)) {
if (ChainDef == Second)
return true;
if (MSSA->isLiveOnEntryDef(ChainDef))
return false;
EndDef = ChainDef;
}
auto *MP = cast<MemoryPhi>(EndDef);
auto ReachableOperandPred = [&](const Use &U) {
return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
};
auto FilteredPhiArgs =
make_filter_range(MP->operands(), ReachableOperandPred);
SmallVector<const Value *, 32> OperandList;
llvm::copy(FilteredPhiArgs, std::back_inserter(OperandList));
bool Okay = is_splat(OperandList);
if (Okay)
return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
Second);
return false;
}
void NewGVN::verifyMemoryCongruency() const {
#ifndef NDEBUG
for (const auto *CC : CongruenceClasses) {
if (CC == TOPClass || CC->isDead())
continue;
if (CC->getStoreCount() != 0) {
assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
"Any class with a store as a leader should have a "
"representative stored value");
assert(CC->getMemoryLeader() &&
"Any congruence class with a store should have a "
"representative access");
}
if (CC->getMemoryLeader())
assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
"Representative MemoryAccess does not appear to be reverse "
"mapped properly");
for (auto M : CC->memory())
assert(MemoryAccessToClass.lookup(M) == CC &&
"Memory member does not appear to be reverse mapped properly");
}
auto ReachableAccessPred =
[&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
bool Result = ReachableBlocks.count(Pair.first->getBlock());
if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
MemoryToDFSNum(Pair.first) == 0)
return false;
if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
return !isInstructionTriviallyDead(MemDef->getMemoryInst());
if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
for (auto &U : MemPHI->incoming_values()) {
if (auto *I = dyn_cast<Instruction>(&*U)) {
if (!isInstructionTriviallyDead(I))
return true;
}
}
return false;
}
return true;
};
auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
for (auto KV : Filtered) {
if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
if (FirstMUD && SecondMUD) {
SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
"The instructions for these memory operations should have "
"been in the same congruence class or reachable through"
"a single argument phi");
}
} else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
auto ReachableOperandPred = [&](const Use &U) {
return ReachableEdges.count(
{FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
isa<MemoryDef>(U);
};
auto FilteredPhiArgs =
make_filter_range(FirstMP->operands(), ReachableOperandPred);
SmallVector<const CongruenceClass *, 16> PhiOpClasses;
std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
std::back_inserter(PhiOpClasses), [&](const Use &U) {
const MemoryDef *MD = cast<MemoryDef>(U);
return ValueToClass.lookup(MD->getMemoryInst());
});
assert(is_splat(PhiOpClasses) &&
"All MemoryPhi arguments should be in the same class");
}
}
#endif
}
void NewGVN::verifyIterationSettled(Function &F) {
#ifndef NDEBUG
LLVM_DEBUG(dbgs() << "Beginning iteration verification\n");
if (DebugCounter::isCounterSet(VNCounter))
DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
std::map<const Value *, CongruenceClass> BeforeIteration;
for (auto &KV : ValueToClass) {
if (auto *I = dyn_cast<Instruction>(KV.first))
if (InstrToDFSNum(I) == 0)
continue;
BeforeIteration.insert({KV.first, *KV.second});
}
TouchedInstructions.set();
TouchedInstructions.reset(0);
iterateTouchedInstructions();
DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
EqualClasses;
for (const auto &KV : ValueToClass) {
if (auto *I = dyn_cast<Instruction>(KV.first))
if (InstrToDFSNum(I) == 0)
continue;
auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
auto *AfterCC = KV.second;
if (!EqualClasses.count({BeforeCC, AfterCC})) {
assert(BeforeCC->isEquivalentTo(AfterCC) &&
"Value number changed after main loop completed!");
EqualClasses.insert({BeforeCC, AfterCC});
}
}
#endif
}
void NewGVN::verifyStoreExpressions() const {
#ifndef NDEBUG
std::set<
std::pair<const Value *,
std::tuple<const Value *, const CongruenceClass *, Value *>>>
StoreExpressionSet;
for (const auto &KV : ExpressionToClass) {
if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
auto Res = StoreExpressionSet.insert(
{SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
SE->getStoredValue())});
bool Okay = Res.second;
if (!Okay)
Okay = (std::get<1>(Res.first->second) == KV.second) &&
(lookupOperandLeader(std::get<2>(Res.first->second)) ==
lookupOperandLeader(SE->getStoredValue()));
assert(Okay && "Stored expression conflict exists in expression table");
auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
assert(ValueExpr && ValueExpr->equals(*SE) &&
"StoreExpression in ExpressionToClass is not latest "
"StoreExpression for value");
}
}
#endif
}
void NewGVN::iterateTouchedInstructions() {
uint64_t Iterations = 0;
int FirstInstr = TouchedInstructions.find_first();
if (FirstInstr == -1)
return;
const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
while (TouchedInstructions.any()) {
++Iterations;
for (unsigned InstrNum : TouchedInstructions.set_bits()) {
if (InstrNum == 0) {
TouchedInstructions.reset(InstrNum);
continue;
}
Value *V = InstrFromDFSNum(InstrNum);
const BasicBlock *CurrBlock = getBlockForValue(V);
if (CurrBlock != LastBlock) {
LastBlock = CurrBlock;
bool BlockReachable = ReachableBlocks.count(CurrBlock);
const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
if (!BlockReachable) {
TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
LLVM_DEBUG(dbgs() << "Skipping instructions in block "
<< getBlockName(CurrBlock)
<< " because it is unreachable\n");
continue;
}
updateProcessedCount(CurrBlock);
}
TouchedInstructions.reset(InstrNum);
if (auto *MP = dyn_cast<MemoryPhi>(V)) {
LLVM_DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
valueNumberMemoryPhi(MP);
} else if (auto *I = dyn_cast<Instruction>(V)) {
valueNumberInstruction(I);
} else {
llvm_unreachable("Should have been a MemoryPhi or Instruction");
}
updateProcessedCount(V);
}
}
NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
}
bool NewGVN::runGVN() {
if (DebugCounter::isCounterSet(VNCounter))
StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
bool Changed = false;
NumFuncArgs = F.arg_size();
MSSAWalker = MSSA->getWalker();
SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
unsigned ICount = 1;
DFSToInstr.emplace_back(nullptr);
ReversePostOrderTraversal<Function *> RPOT(&F);
unsigned Counter = 0;
for (auto &B : RPOT) {
auto *Node = DT->getNode(B);
assert(Node && "RPO and Dominator tree should have same reachability");
RPOOrdering[Node] = ++Counter;
}
for (auto &B : RPOT) {
auto *Node = DT->getNode(B);
if (Node->getNumChildren() > 1)
llvm::sort(*Node, [&](const DomTreeNode *A, const DomTreeNode *B) {
return RPOOrdering[A] < RPOOrdering[B];
});
}
for (auto DTN : depth_first(DT->getRootNode())) {
BasicBlock *B = DTN->getBlock();
const auto &BlockRange = assignDFSNumbers(B, ICount);
BlockInstRange.insert({B, BlockRange});
ICount += BlockRange.second - BlockRange.first;
}
initializeCongruenceClasses(F);
TouchedInstructions.resize(ICount);
ExpressionToClass.reserve(ICount);
const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
TouchedInstructions.set(InstRange.first, InstRange.second);
LLVM_DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
<< " marked reachable\n");
ReachableBlocks.insert(&F.getEntryBlock());
iterateTouchedInstructions();
verifyMemoryCongruency();
verifyIterationSettled(F);
verifyStoreExpressions();
Changed |= eliminateInstructions(F);
for (Instruction *ToErase : InstructionsToErase) {
if (!ToErase->use_empty())
ToErase->replaceAllUsesWith(PoisonValue::get(ToErase->getType()));
assert(ToErase->getParent() &&
"BB containing ToErase deleted unexpectedly!");
ToErase->eraseFromParent();
}
Changed |= !InstructionsToErase.empty();
auto UnreachableBlockPred = [&](const BasicBlock &BB) {
return !ReachableBlocks.count(&BB);
};
for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
LLVM_DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
<< " is unreachable\n");
deleteInstructionsInBlock(&BB);
Changed = true;
}
cleanupTables();
return Changed;
}
struct NewGVN::ValueDFS {
int DFSIn = 0;
int DFSOut = 0;
int LocalNum = 0;
PointerIntPair<Value *, 1, bool> Def;
Use *U = nullptr;
bool operator<(const ValueDFS &Other) const {
return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Other.U);
}
};
void NewGVN::convertClassToDFSOrdered(
const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
DenseMap<const Value *, unsigned int> &UseCounts,
SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
for (auto D : Dense) {
BasicBlock *BB = getBlockForValue(D);
assert(BB && "Should have figured out a basic block for value");
ValueDFS VDDef;
DomTreeNode *DomNode = DT->getNode(BB);
VDDef.DFSIn = DomNode->getDFSNumIn();
VDDef.DFSOut = DomNode->getDFSNumOut();
if (auto *SI = dyn_cast<StoreInst>(D)) {
auto Leader = lookupOperandLeader(SI->getValueOperand());
if (alwaysAvailable(Leader)) {
VDDef.Def.setPointer(Leader);
} else {
VDDef.Def.setPointer(SI->getValueOperand());
VDDef.Def.setInt(true);
}
} else {
VDDef.Def.setPointer(D);
}
assert(isa<Instruction>(D) &&
"The dense set member should always be an instruction");
Instruction *Def = cast<Instruction>(D);
VDDef.LocalNum = InstrToDFSNum(D);
DFSOrderedSet.push_back(VDDef);
if (auto *PN = RealToTemp.lookup(Def)) {
auto *PHIE =
dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
if (PHIE) {
VDDef.Def.setInt(false);
VDDef.Def.setPointer(PN);
VDDef.LocalNum = 0;
DFSOrderedSet.push_back(VDDef);
}
}
unsigned int UseCount = 0;
for (auto &U : Def->uses()) {
if (auto *I = dyn_cast<Instruction>(U.getUser())) {
if (InstructionsToErase.count(I))
continue;
ValueDFS VDUse;
BasicBlock *IBlock;
if (auto *P = dyn_cast<PHINode>(I)) {
IBlock = P->getIncomingBlock(U);
VDUse.LocalNum = InstrDFS.size() + 1;
} else {
IBlock = getBlockForValue(I);
VDUse.LocalNum = InstrToDFSNum(I);
}
if (!ReachableBlocks.contains(IBlock))
continue;
DomTreeNode *DomNode = DT->getNode(IBlock);
VDUse.DFSIn = DomNode->getDFSNumIn();
VDUse.DFSOut = DomNode->getDFSNumOut();
VDUse.U = &U;
++UseCount;
DFSOrderedSet.emplace_back(VDUse);
}
}
if (UseCount == 0)
ProbablyDead.insert(Def);
else
UseCounts[Def] = UseCount;
}
}
void NewGVN::convertClassToLoadsAndStores(
const CongruenceClass &Dense,
SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
for (auto D : Dense) {
if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
continue;
BasicBlock *BB = getBlockForValue(D);
ValueDFS VD;
DomTreeNode *DomNode = DT->getNode(BB);
VD.DFSIn = DomNode->getDFSNumIn();
VD.DFSOut = DomNode->getDFSNumOut();
VD.Def.setPointer(D);
if (auto *I = dyn_cast<Instruction>(D))
VD.LocalNum = InstrToDFSNum(I);
else
llvm_unreachable("Should have been an instruction");
LoadsAndStores.emplace_back(VD);
}
}
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
patchReplacementInstruction(I, Repl);
I->replaceAllUsesWith(Repl);
}
void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
++NumGVNBlocksDeleted;
auto StartPoint = BB->rbegin();
++StartPoint;
for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
Instruction &Inst = *I++;
if (!Inst.use_empty())
Inst.replaceAllUsesWith(PoisonValue::get(Inst.getType()));
if (isa<LandingPadInst>(Inst))
continue;
salvageKnowledge(&Inst, AC);
Inst.eraseFromParent();
++NumGVNInstrDeleted;
}
Type *Int8Ty = Type::getInt8Ty(BB->getContext());
new StoreInst(PoisonValue::get(Int8Ty),
Constant::getNullValue(Int8Ty->getPointerTo()),
BB->getTerminator());
}
void NewGVN::markInstructionForDeletion(Instruction *I) {
LLVM_DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
InstructionsToErase.insert(I);
}
void NewGVN::replaceInstruction(Instruction *I, Value *V) {
LLVM_DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
patchAndReplaceAllUsesWith(I, V);
markInstructionForDeletion(I);
}
namespace {
class ValueDFSStack {
public:
Value *back() const { return ValueStack.back(); }
std::pair<int, int> dfs_back() const { return DFSStack.back(); }
void push_back(Value *V, int DFSIn, int DFSOut) {
ValueStack.emplace_back(V);
DFSStack.emplace_back(DFSIn, DFSOut);
}
bool empty() const { return DFSStack.empty(); }
bool isInScope(int DFSIn, int DFSOut) const {
if (empty())
return false;
return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
}
void popUntilDFSScope(int DFSIn, int DFSOut) {
assert(ValueStack.size() == DFSStack.size() &&
"Mismatch between ValueStack and DFSStack");
while (
!DFSStack.empty() &&
!(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
DFSStack.pop_back();
ValueStack.pop_back();
}
}
private:
SmallVector<Value *, 8> ValueStack;
SmallVector<std::pair<int, int>, 8> DFSStack;
};
}
CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
if (auto *VE = dyn_cast<VariableExpression>(E))
return ValueToClass.lookup(VE->getVariableValue());
else if (isa<DeadExpression>(E))
return TOPClass;
return ExpressionToClass.lookup(E);
}
Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
const Instruction *OrigInst,
const BasicBlock *BB) const {
if (auto *CE = dyn_cast<ConstantExpression>(E))
return CE->getConstantValue();
if (auto *VE = dyn_cast<VariableExpression>(E)) {
auto *V = VE->getVariableValue();
if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
return VE->getVariableValue();
}
auto *CC = getClassForExpression(E);
if (!CC)
return nullptr;
if (alwaysAvailable(CC->getLeader()))
return CC->getLeader();
for (auto Member : *CC) {
auto *MemberInst = dyn_cast<Instruction>(Member);
if (MemberInst == OrigInst)
continue;
if (!MemberInst)
return Member;
if (DT->dominates(getBlockForValue(MemberInst), BB))
return Member;
}
return nullptr;
}
bool NewGVN::eliminateInstructions(Function &F) {
bool AnythingReplaced = false;
DT->updateDFSNumbers();
auto ReplaceUnreachablePHIArgs = [&](PHINode *PHI, BasicBlock *BB) {
for (auto &Operand : PHI->incoming_values())
if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
LLVM_DEBUG(dbgs() << "Replacing incoming value of " << PHI
<< " for block "
<< getBlockName(PHI->getIncomingBlock(Operand))
<< " with poison due to it being unreachable\n");
Operand.set(PoisonValue::get(PHI->getType()));
}
};
DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
for (auto &KV : ReachableEdges)
ReachablePredCount[KV.getEnd()]++;
for (auto &BBPair : RevisitOnReachabilityChange) {
for (auto InstNum : BBPair.second) {
auto *Inst = InstrFromDFSNum(InstNum);
auto *PHI = dyn_cast<PHINode>(Inst);
PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
if (!PHI)
continue;
auto *BB = BBPair.first;
if (ReachablePredCount.lookup(BB) != PHI->getNumIncomingValues())
ReplaceUnreachablePHIArgs(PHI, BB);
}
}
DenseMap<const Value *, unsigned int> UseCounts;
for (auto *CC : reverse(CongruenceClasses)) {
LLVM_DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
<< "\n");
SmallVector<ValueDFS, 8> PossibleDeadStores;
SmallPtrSet<Instruction *, 8> ProbablyDead;
if (CC->isDead() || CC->empty())
continue;
if (CC == TOPClass) {
for (auto M : *CC) {
auto *VTE = ValueToExpression.lookup(M);
if (VTE && isa<DeadExpression>(VTE))
markInstructionForDeletion(cast<Instruction>(M));
assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
InstructionsToErase.count(cast<Instruction>(M))) &&
"Everything in TOP should be unreachable or dead at this "
"point");
}
continue;
}
assert(CC->getLeader() && "We should have had a leader");
Value *Leader =
CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
if (alwaysAvailable(Leader)) {
CongruenceClass::MemberSet MembersLeft;
for (auto M : *CC) {
Value *Member = M;
if (Member == Leader || !isa<Instruction>(Member) ||
Member->getType()->isVoidTy()) {
MembersLeft.insert(Member);
continue;
}
LLVM_DEBUG(dbgs() << "Found replacement " << *(Leader) << " for "
<< *Member << "\n");
auto *I = cast<Instruction>(Member);
assert(Leader != I && "About to accidentally remove our leader");
replaceInstruction(I, Leader);
AnythingReplaced = true;
}
CC->swap(MembersLeft);
} else {
if (CC->size() != 1 || RealToTemp.count(Leader)) {
ValueDFSStack EliminationStack;
SmallVector<ValueDFS, 8> DFSOrderedSet;
convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
llvm::sort(DFSOrderedSet);
for (auto &VD : DFSOrderedSet) {
int MemberDFSIn = VD.DFSIn;
int MemberDFSOut = VD.DFSOut;
Value *Def = VD.Def.getPointer();
bool FromStore = VD.Def.getInt();
Use *U = VD.U;
if (Def && Def->getType()->isVoidTy())
continue;
auto *DefInst = dyn_cast_or_null<Instruction>(Def);
if (DefInst && AllTempInstructions.count(DefInst)) {
auto *PN = cast<PHINode>(DefInst);
AllTempInstructions.erase(PN);
auto *DefBlock = getBlockForValue(Def);
LLVM_DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
<< " into block "
<< getBlockName(getBlockForValue(Def)) << "\n");
PN->insertBefore(&DefBlock->front());
Def = PN;
NumGVNPHIOfOpsEliminations++;
}
if (EliminationStack.empty()) {
LLVM_DEBUG(dbgs() << "Elimination Stack is empty\n");
} else {
LLVM_DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
<< EliminationStack.dfs_back().first << ","
<< EliminationStack.dfs_back().second << ")\n");
}
LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
<< MemberDFSOut << ")\n");
bool ShouldPush = Def && EliminationStack.empty();
bool OutOfScope =
!EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
if (OutOfScope || ShouldPush) {
EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
bool ShouldPush = Def && EliminationStack.empty();
if (ShouldPush) {
EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
}
}
if (Def) {
if (!EliminationStack.empty() && Def != EliminationStack.back() &&
isa<Instruction>(Def) && !FromStore)
markInstructionForDeletion(cast<Instruction>(Def));
continue;
}
assert(isa<Instruction>(U->get()) &&
"Current def should have been an instruction");
assert(isa<Instruction>(U->getUser()) &&
"Current user should have been an instruction");
Instruction *InstUse = cast<Instruction>(U->getUser());
if (InstructionsToErase.count(InstUse)) {
auto &UseCount = UseCounts[U->get()];
if (--UseCount == 0) {
ProbablyDead.insert(cast<Instruction>(U->get()));
}
}
if (EliminationStack.empty())
continue;
Value *DominatingLeader = EliminationStack.back();
auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
bool isSSACopy = II && II->getIntrinsicID() == Intrinsic::ssa_copy;
if (isSSACopy)
DominatingLeader = II->getOperand(0);
if (U->get() == DominatingLeader)
continue;
LLVM_DEBUG(dbgs()
<< "Found replacement " << *DominatingLeader << " for "
<< *U->get() << " in " << *(U->getUser()) << "\n");
auto *ReplacedInst = cast<Instruction>(U->get());
auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
if (!PI || DominatingLeader != PI->OriginalOp)
patchReplacementInstruction(ReplacedInst, DominatingLeader);
U->set(DominatingLeader);
auto &LeaderUseCount = UseCounts[DominatingLeader];
if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
ProbablyDead.erase(cast<Instruction>(DominatingLeader));
if (isSSACopy) {
unsigned &IIUseCount = UseCounts[II];
if (--IIUseCount == 0)
ProbablyDead.insert(II);
}
++LeaderUseCount;
AnythingReplaced = true;
}
}
}
for (auto *I : ProbablyDead)
if (wouldInstructionBeTriviallyDead(I))
markInstructionForDeletion(I);
CongruenceClass::MemberSet MembersLeft;
for (auto *Member : *CC)
if (!isa<Instruction>(Member) ||
!InstructionsToErase.count(cast<Instruction>(Member)))
MembersLeft.insert(Member);
CC->swap(MembersLeft);
if (CC->getStoreCount() > 0) {
convertClassToLoadsAndStores(*CC, PossibleDeadStores);
llvm::sort(PossibleDeadStores);
ValueDFSStack EliminationStack;
for (auto &VD : PossibleDeadStores) {
int MemberDFSIn = VD.DFSIn;
int MemberDFSOut = VD.DFSOut;
Instruction *Member = cast<Instruction>(VD.Def.getPointer());
if (EliminationStack.empty() ||
!EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
if (EliminationStack.empty()) {
EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
continue;
}
}
if (isa<LoadInst>(Member))
continue;
assert(!EliminationStack.empty());
Instruction *Leader = cast<Instruction>(EliminationStack.back());
(void)Leader;
assert(DT->dominates(Leader->getParent(), Member->getParent()));
LLVM_DEBUG(dbgs() << "Marking dead store " << *Member
<< " that is dominated by " << *Leader << "\n");
markInstructionForDeletion(Member);
CC->erase(Member);
++NumGVNDeadStores;
}
}
}
return AnythingReplaced;
}
unsigned int NewGVN::getRank(const Value *V) const {
if (isa<ConstantExpr>(V))
return 3;
if (isa<PoisonValue>(V))
return 1;
if (isa<UndefValue>(V))
return 2;
if (isa<Constant>(V))
return 0;
if (auto *A = dyn_cast<Argument>(V))
return 4 + A->getArgNo();
unsigned Result = InstrToDFSNum(V);
if (Result > 0)
return 5 + NumFuncArgs + Result;
return ~0;
}
bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
}
bool NewGVN::shouldSwapOperandsForIntrinsic(const Value *A, const Value *B,
const IntrinsicInst *I) const {
auto LookupResult = IntrinsicInstPred.find(I);
if (shouldSwapOperands(A, B)) {
if (LookupResult == IntrinsicInstPred.end())
IntrinsicInstPred.insert({I, B});
else
LookupResult->second = B;
return true;
}
if (LookupResult != IntrinsicInstPred.end()) {
auto *SeenPredicate = LookupResult->second;
if (SeenPredicate) {
if (SeenPredicate == B)
return true;
else
LookupResult->second = nullptr;
}
}
return false;
}
namespace {
class NewGVNLegacyPass : public FunctionPass {
public:
static char ID;
NewGVNLegacyPass() : FunctionPass(ID) {
initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
private:
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<MemorySSAWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
};
}
bool NewGVNLegacyPass::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
&getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
&getAnalysis<AAResultsWrapperPass>().getAAResults(),
&getAnalysis<MemorySSAWrapperPass>().getMSSA(),
F.getParent()->getDataLayout())
.runGVN();
}
char NewGVNLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
false)
FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &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 &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
bool Changed =
NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
.runGVN();
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<DominatorTreeAnalysis>();
return PA;
}