#include "llvm/Transforms/Scalar/ConstantHoisting.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.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/Operator.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/BlockFrequency.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SizeOpts.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <tuple>
#include <utility>
using namespace llvm;
using namespace consthoist;
#define DEBUG_TYPE "consthoist"
STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
STATISTIC(NumConstantsRebased, "Number of constants rebased");
static cl::opt<bool> ConstHoistWithBlockFrequency(
"consthoist-with-block-frequency", cl::init(true), cl::Hidden,
cl::desc("Enable the use of the block frequency analysis to reduce the "
"chance to execute const materialization more frequently than "
"without hoisting."));
static cl::opt<bool> ConstHoistGEP(
"consthoist-gep", cl::init(false), cl::Hidden,
cl::desc("Try hoisting constant gep expressions"));
static cl::opt<unsigned>
MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
cl::desc("Do not rebase if number of dependent constants of a Base is less "
"than this number."),
cl::init(0), cl::Hidden);
namespace {
class ConstantHoistingLegacyPass : public FunctionPass {
public:
static char ID;
ConstantHoistingLegacyPass() : FunctionPass(ID) {
initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &Fn) override;
StringRef getPassName() const override { return "Constant Hoisting"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
if (ConstHoistWithBlockFrequency)
AU.addRequired<BlockFrequencyInfoWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<ProfileSummaryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
}
private:
ConstantHoistingPass Impl;
};
}
char ConstantHoistingLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
"Constant Hoisting", false, false)
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
"Constant Hoisting", false, false)
FunctionPass *llvm::createConstantHoistingPass() {
return new ConstantHoistingLegacyPass();
}
bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
if (skipFunction(Fn))
return false;
LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
bool MadeChange =
Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
ConstHoistWithBlockFrequency
? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
: nullptr,
Fn.getEntryBlock(),
&getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
if (MadeChange) {
LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
<< Fn.getName() << '\n');
LLVM_DEBUG(dbgs() << Fn);
}
LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
return MadeChange;
}
Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
unsigned Idx) const {
if (Idx != ~0U) {
Value *Opnd = Inst->getOperand(Idx);
if (auto CastInst = dyn_cast<Instruction>(Opnd))
if (CastInst->isCast())
return CastInst;
}
if (!isa<PHINode>(Inst) && !Inst->isEHPad())
return Inst;
assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
BasicBlock *InsertionBlock = nullptr;
if (Idx != ~0U && isa<PHINode>(Inst)) {
InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
if (!InsertionBlock->isEHPad()) {
return InsertionBlock->getTerminator();
}
} else {
InsertionBlock = Inst->getParent();
}
auto *IDom = DT->getNode(InsertionBlock)->getIDom();
while (IDom->getBlock()->isEHPad()) {
assert(Entry != IDom->getBlock() && "eh pad in entry block");
IDom = IDom->getIDom();
}
return IDom->getBlock()->getTerminator();
}
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
BasicBlock *Entry,
SetVector<BasicBlock *> &BBs) {
assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
SmallPtrSet<BasicBlock *, 8> Path;
SmallPtrSet<BasicBlock *, 16> Candidates;
for (auto BB : BBs) {
if (!DT.isReachableFromEntry(BB))
continue;
Path.clear();
BasicBlock *Node = BB;
bool isCandidate = false;
do {
Path.insert(Node);
if (Node == Entry || Candidates.count(Node)) {
isCandidate = true;
break;
}
assert(DT.getNode(Node)->getIDom() &&
"Entry doens't dominate current Node");
Node = DT.getNode(Node)->getIDom()->getBlock();
} while (!BBs.count(Node));
if (!isCandidate)
continue;
Candidates.insert(Path.begin(), Path.end());
}
unsigned Idx = 0;
SmallVector<BasicBlock *, 16> Orders;
Orders.push_back(Entry);
while (Idx != Orders.size()) {
BasicBlock *Node = Orders[Idx++];
for (auto ChildDomNode : DT.getNode(Node)->children()) {
if (Candidates.count(ChildDomNode->getBlock()))
Orders.push_back(ChildDomNode->getBlock());
}
}
using InsertPtsCostPair =
std::pair<SetVector<BasicBlock *>, BlockFrequency>;
DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
InsertPtsMap.reserve(Orders.size() + 1);
for (BasicBlock *Node : llvm::reverse(Orders)) {
bool NodeInBBs = BBs.count(Node);
auto &InsertPts = InsertPtsMap[Node].first;
BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
if (Node == Entry) {
BBs.clear();
if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
(InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
BBs.insert(Entry);
else
BBs.insert(InsertPts.begin(), InsertPts.end());
break;
}
BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
auto &ParentInsertPts = InsertPtsMap[Parent].first;
BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
if (NodeInBBs ||
(!Node->isEHPad() &&
(InsertPtsFreq > BFI.getBlockFreq(Node) ||
(InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
ParentInsertPts.insert(Node);
ParentPtsFreq += BFI.getBlockFreq(Node);
} else {
ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
ParentPtsFreq += InsertPtsFreq;
}
}
}
SetVector<Instruction *> ConstantHoistingPass::findConstantInsertionPoint(
const ConstantInfo &ConstInfo) const {
assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
SetVector<BasicBlock *> BBs;
SetVector<Instruction *> InsertPts;
for (auto const &RCI : ConstInfo.RebasedConstants)
for (auto const &U : RCI.Uses)
BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
if (BBs.count(Entry)) {
InsertPts.insert(&Entry->front());
return InsertPts;
}
if (BFI) {
findBestInsertionSet(*DT, *BFI, Entry, BBs);
for (auto BB : BBs) {
BasicBlock::iterator InsertPt = BB->begin();
for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
;
InsertPts.insert(&*InsertPt);
}
return InsertPts;
}
while (BBs.size() >= 2) {
BasicBlock *BB, *BB1, *BB2;
BB1 = BBs.pop_back_val();
BB2 = BBs.pop_back_val();
BB = DT->findNearestCommonDominator(BB1, BB2);
if (BB == Entry) {
InsertPts.insert(&Entry->front());
return InsertPts;
}
BBs.insert(BB);
}
assert((BBs.size() == 1) && "Expected only one element.");
Instruction &FirstInst = (*BBs.begin())->front();
InsertPts.insert(findMatInsertPt(&FirstInst));
return InsertPts;
}
void ConstantHoistingPass::collectConstantCandidates(
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
ConstantInt *ConstInt) {
InstructionCost Cost;
if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
ConstInt->getValue(), ConstInt->getType(),
TargetTransformInfo::TCK_SizeAndLatency);
else
Cost = TTI->getIntImmCostInst(
Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
TargetTransformInfo::TCK_SizeAndLatency, Inst);
if (Cost > TargetTransformInfo::TCC_Basic) {
ConstCandMapType::iterator Itr;
bool Inserted;
ConstPtrUnionType Cand = ConstInt;
std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
if (Inserted) {
ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
Itr->second = ConstIntCandVec.size() - 1;
}
ConstIntCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
<< "Collect constant " << *ConstInt << " from " << *Inst
<< " with cost " << Cost << '\n';
else dbgs() << "Collect constant " << *ConstInt
<< " indirectly from " << *Inst << " via "
<< *Inst->getOperand(Idx) << " with cost " << Cost
<< '\n';);
}
}
void ConstantHoistingPass::collectConstantCandidates(
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
ConstantExpr *ConstExpr) {
if (ConstExpr->getType()->isVectorTy())
return;
GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
if (!BaseGV)
return;
PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
APInt Offset(DL->getTypeSizeInBits(PtrIntTy), 0, true);
auto *GEPO = cast<GEPOperator>(ConstExpr);
if (!GEPO->isInBounds())
return;
if (!GEPO->accumulateConstantOffset(*DL, Offset))
return;
if (!Offset.isIntN(32))
return;
InstructionCost Cost =
TTI->getIntImmCostInst(Instruction::Add, 1, Offset, PtrIntTy,
TargetTransformInfo::TCK_SizeAndLatency, Inst);
ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
ConstCandMapType::iterator Itr;
bool Inserted;
ConstPtrUnionType Cand = ConstExpr;
std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
if (Inserted) {
ExprCandVec.push_back(ConstantCandidate(
ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
ConstExpr));
Itr->second = ExprCandVec.size() - 1;
}
ExprCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
}
void ConstantHoistingPass::collectConstantCandidates(
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
Value *Opnd = Inst->getOperand(Idx);
if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
return;
}
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
if (!CastInst->isCast())
return;
if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
return;
}
}
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
if (ConstHoistGEP && isa<GEPOperator>(ConstExpr))
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
if (!ConstExpr->isCast())
return;
if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
return;
}
}
}
void ConstantHoistingPass::collectConstantCandidates(
ConstCandMapType &ConstCandMap, Instruction *Inst) {
if (Inst->isCast())
return;
for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
if (canReplaceOperandWithVariable(Inst, Idx)) {
collectConstantCandidates(ConstCandMap, Inst, Idx);
}
} }
void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
ConstCandMapType ConstCandMap;
for (BasicBlock &BB : Fn) {
if (!DT->isReachableFromEntry(&BB))
continue;
for (Instruction &Inst : BB)
collectConstantCandidates(ConstCandMap, &Inst);
}
}
static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
Optional<APInt> Res = None;
unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
V1.getBitWidth() : V2.getBitWidth();
uint64_t LimVal1 = V1.getLimitedValue();
uint64_t LimVal2 = V2.getLimitedValue();
if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
return Res;
uint64_t Diff = LimVal1 - LimVal2;
return APInt(BW, Diff, true);
}
unsigned
ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
ConstCandVecType::iterator E,
ConstCandVecType::iterator &MaxCostItr) {
unsigned NumUses = 0;
bool OptForSize = Entry->getParent()->hasOptSize() ||
llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI,
PGSOQueryType::IRPass);
if (!OptForSize || std::distance(S,E) > 100) {
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
NumUses += ConstCand->Uses.size();
if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
MaxCostItr = ConstCand;
}
return NumUses;
}
LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
InstructionCost MaxCost = -1;
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
auto Value = ConstCand->ConstInt->getValue();
Type *Ty = ConstCand->ConstInt->getType();
InstructionCost Cost = 0;
NumUses += ConstCand->Uses.size();
LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
<< "\n");
for (auto User : ConstCand->Uses) {
unsigned Opcode = User.Inst->getOpcode();
unsigned OpndIdx = User.OpndIdx;
Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
TargetTransformInfo::TCK_SizeAndLatency);
LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
for (auto C2 = S; C2 != E; ++C2) {
Optional<APInt> Diff = calculateOffsetDiff(
C2->ConstInt->getValue(),
ConstCand->ConstInt->getValue());
if (Diff) {
const InstructionCost ImmCosts =
TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.value(), Ty);
Cost -= ImmCosts;
LLVM_DEBUG(dbgs() << "Offset " << Diff.value() << " "
<< "has penalty: " << ImmCosts << "\n"
<< "Adjusted cost: " << Cost << "\n");
}
}
}
LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
if (Cost > MaxCost) {
MaxCost = Cost;
MaxCostItr = ConstCand;
LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
<< "\n");
}
}
return NumUses;
}
void ConstantHoistingPass::findAndMakeBaseConstant(
ConstCandVecType::iterator S, ConstCandVecType::iterator E,
SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
auto MaxCostItr = S;
unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
if (NumUses <= 1)
return;
ConstantInt *ConstInt = MaxCostItr->ConstInt;
ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
ConstantInfo ConstInfo;
ConstInfo.BaseInt = ConstInt;
ConstInfo.BaseExpr = ConstExpr;
Type *Ty = ConstInt->getType();
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
Type *ConstTy =
ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
ConstInfo.RebasedConstants.push_back(
RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
}
ConstInfoVec.push_back(std::move(ConstInfo));
}
void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
ConstCandVecType &ConstCandVec = BaseGV ?
ConstGEPCandMap[BaseGV] : ConstIntCandVec;
ConstInfoVecType &ConstInfoVec = BaseGV ?
ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
const ConstantCandidate &RHS) {
if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
return LHS.ConstInt->getType()->getBitWidth() <
RHS.ConstInt->getType()->getBitWidth();
return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
});
auto MinValItr = ConstCandVec.begin();
for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
CC != E; ++CC) {
if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Type *MemUseValTy = nullptr;
for (auto &U : CC->Uses) {
auto *UI = U.Inst;
if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
MemUseValTy = LI->getType();
break;
} else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
MemUseValTy = SI->getValueOperand()->getType();
break;
}
}
}
APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
if ((Diff.getBitWidth() <= 64) &&
TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
(!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
nullptr, Diff.getSExtValue(),
true, 0)))
continue;
}
findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
MinValItr = CC;
}
findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
}
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
if (auto PHI = dyn_cast<PHINode>(Inst)) {
BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
for (unsigned i = 0; i < Idx; ++i) {
if (PHI->getIncomingBlock(i) == IncomingBB) {
Value *IncomingVal = PHI->getIncomingValue(i);
Inst->setOperand(Idx, IncomingVal);
return false;
}
}
}
Inst->setOperand(Idx, Mat);
return true;
}
void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
Constant *Offset,
Type *Ty,
const ConstantUser &ConstUser) {
Instruction *Mat = Base;
if (!Offset && Ty && Ty != Base->getType())
Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
if (Offset) {
Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
ConstUser.OpndIdx);
if (Ty) {
PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
cast<PointerType>(Ty)->getAddressSpace());
Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
Mat = GetElementPtrInst::Create(Type::getInt8Ty(*Ctx), Base,
Offset, "mat_gep", InsertionPt);
Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
} else
Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
"const_mat", InsertionPt);
LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
<< " + " << *Offset << ") in BB "
<< Mat->getParent()->getName() << '\n'
<< *Mat << '\n');
Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
}
Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
if (isa<ConstantInt>(Opnd)) {
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
Mat->eraseFromParent();
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
assert(CastInst->isCast() && "Expected an cast instruction!");
Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
if (!ClonedCastInst) {
ClonedCastInst = CastInst->clone();
ClonedCastInst->setOperand(0, Mat);
ClonedCastInst->insertAfter(CastInst);
ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
<< "To : " << *ClonedCastInst << '\n');
}
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
if (isa<GEPOperator>(ConstExpr)) {
updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
return;
}
assert(ConstExpr->isCast() && "ConstExpr should be a cast");
Instruction *ConstExprInst = ConstExpr->getAsInstruction(
findMatInsertPt(ConstUser.Inst, ConstUser.OpndIdx));
ConstExprInst->setOperand(0, Mat);
ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
<< "From : " << *ConstExpr << '\n');
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
ConstExprInst->eraseFromParent();
if (Offset)
Mat->eraseFromParent();
}
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
}
bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
bool MadeChange = false;
SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
for (auto const &ConstInfo : ConstInfoVec) {
SetVector<Instruction *> IPSet = findConstantInsertionPoint(ConstInfo);
if (IPSet.empty())
continue;
unsigned UsesNum = 0;
unsigned ReBasesNum = 0;
unsigned NotRebasedNum = 0;
for (Instruction *IP : IPSet) {
unsigned Uses = 0;
using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
SmallVector<RebasedUse, 4> ToBeRebased;
for (auto const &RCI : ConstInfo.RebasedConstants) {
for (auto const &U : RCI.Uses) {
Uses++;
BasicBlock *OrigMatInsertBB =
findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
if (IPSet.size() == 1 ||
DT->dominates(IP->getParent(), OrigMatInsertBB))
ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
}
}
UsesNum = Uses;
if (ToBeRebased.size() < MinNumOfDependentToRebase) {
NotRebasedNum += ToBeRebased.size();
continue;
}
Instruction *Base = nullptr;
if (ConstInfo.BaseExpr) {
assert(BaseGV && "A base constant expression must have an base GV");
Type *Ty = ConstInfo.BaseExpr->getType();
Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
} else {
IntegerType *Ty = ConstInfo.BaseInt->getType();
Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
}
Base->setDebugLoc(IP->getDebugLoc());
LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
<< ") to BB " << IP->getParent()->getName() << '\n'
<< *Base << '\n');
for (auto const &R : ToBeRebased) {
Constant *Off = std::get<0>(R);
Type *Ty = std::get<1>(R);
ConstantUser U = std::get<2>(R);
emitBaseConstants(Base, Off, Ty, U);
ReBasesNum++;
Base->setDebugLoc(DILocation::getMergedLocation(
Base->getDebugLoc(), U.Inst->getDebugLoc()));
}
assert(!Base->use_empty() && "The use list is empty!?");
assert(isa<Instruction>(Base->user_back()) &&
"All uses should be instructions.");
}
(void)UsesNum;
(void)ReBasesNum;
(void)NotRebasedNum;
assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
"Not all uses are rebased");
NumConstantsHoisted++;
NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
MadeChange = true;
}
return MadeChange;
}
void ConstantHoistingPass::deleteDeadCastInst() const {
for (auto const &I : ClonedCastMap)
if (I.first->use_empty())
I.first->eraseFromParent();
}
bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
DominatorTree &DT, BlockFrequencyInfo *BFI,
BasicBlock &Entry, ProfileSummaryInfo *PSI) {
this->TTI = &TTI;
this->DT = &DT;
this->BFI = BFI;
this->DL = &Fn.getParent()->getDataLayout();
this->Ctx = &Fn.getContext();
this->Entry = &Entry;
this->PSI = PSI;
collectConstantCandidates(Fn);
if (!ConstIntCandVec.empty())
findBaseConstants(nullptr);
for (const auto &MapEntry : ConstGEPCandMap)
if (!MapEntry.second.empty())
findBaseConstants(MapEntry.first);
bool MadeChange = false;
if (!ConstIntInfoVec.empty())
MadeChange = emitBaseConstants(nullptr);
for (const auto &MapEntry : ConstGEPInfoMap)
if (!MapEntry.second.empty())
MadeChange |= emitBaseConstants(MapEntry.first);
deleteDeadCastInst();
cleanup();
return MadeChange;
}
PreservedAnalyses ConstantHoistingPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
auto BFI = ConstHoistWithBlockFrequency
? &AM.getResult<BlockFrequencyAnalysis>(F)
: nullptr;
auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}