53 #define DEBUG_TYPE "consthoist"
55 STATISTIC(NumConstantsHoisted,
"Number of constants hoisted");
56 STATISTIC(NumConstantsRebased,
"Number of constants rebased");
60 cl::desc(
"Enable the use of the block frequency analysis to reduce the "
61 "chance to execute const materialization more frequently than "
62 "without hoisting."));
73 bool runOnFunction(
Function &Fn)
override;
75 StringRef getPassName()
const override {
return "Constant Hoisting"; }
94 "Constant Hoisting",
false,
false)
102 return new ConstantHoistingLegacyPass();
106 bool ConstantHoistingLegacyPass::runOnFunction(
Function &Fn) {
107 if (skipFunction(Fn))
110 DEBUG(
dbgs() <<
"********** Begin Constant Hoisting **********\n");
114 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
115 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
117 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
122 DEBUG(
dbgs() <<
"********** Function after Constant Hoisting: "
126 DEBUG(
dbgs() <<
"********** End Constant Hoisting **********\n");
134 unsigned Idx)
const {
139 if (
auto CastInst = dyn_cast<Instruction>(Opnd))
145 if (!isa<PHINode>(Inst) && !Inst->
isEHPad())
150 assert(Entry != Inst->
getParent() &&
"PHI or landing pad in entry block!");
151 if (Idx != ~0U && isa<PHINode>(Inst))
152 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
157 auto IDom = DT->getNode(Inst->
getParent())->getIDom();
158 while (IDom->getBlock()->isEHPad()) {
159 assert(Entry != IDom->getBlock() &&
"eh pad in entry block");
160 IDom = IDom->getIDom();
163 return IDom->getBlock()->getTerminator();
172 assert(!BBs.
count(Entry) &&
"Assume Entry is not in BBs");
179 for (
auto BB : BBs) {
185 bool isCandidate =
false;
188 if (Node == Entry || Candidates.
count(Node)) {
193 "Entry doens't dominate current Node");
194 Node = DT.
getNode(Node)->getIDom()->getBlock();
195 }
while (!BBs.count(Node));
203 Candidates.
insert(Path.begin(), Path.end());
211 while (Idx != Orders.
size()) {
213 for (
auto ChildDomNode : DT.
getNode(Node)->getChildren()) {
214 if (Candidates.
count(ChildDomNode->getBlock()))
215 Orders.
push_back(ChildDomNode->getBlock());
226 for (
auto RIt = Orders.
rbegin(); RIt != Orders.
rend(); RIt++) {
228 bool NodeInBBs = BBs.count(Node);
239 BBs.insert(InsertPts.
begin(), InsertPts.
end());
258 ParentInsertPts.
insert(Node);
262 ParentPtsFreq += InsertPtsFreq;
275 for (
auto const &U : RCI.Uses)
276 BBs.
insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
278 if (BBs.count(Entry)) {
279 InsertPts.
insert(&Entry->front());
285 for (
auto BB : BBs) {
287 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
289 InsertPts.
insert(&*InsertPt);
294 while (BBs.size() >= 2) {
297 BB2 = *std::next(BBs.begin());
298 BB = DT->findNearestCommonDominator(BB1, BB2);
300 InsertPts.
insert(&Entry->front());
307 assert((BBs.size() == 1) &&
"Expected only one element.");
309 InsertPts.
insert(findMatInsertPt(&FirstInst));
320 void ConstantHoistingPass::collectConstantCandidates(
321 ConstCandMapType &ConstCandMap,
Instruction *Inst,
unsigned Idx,
326 if (
auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
327 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
335 ConstCandMapType::iterator Itr;
337 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
340 Itr->second = ConstCandVec.size() - 1;
342 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
344 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
345 << " with cost " << Cost << '\n';
347 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
348 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
357 ConstCandMapType &ConstCandMap,
Instruction *Inst,
unsigned Idx) {
358 Value *Opnd = Inst->getOperand(Idx);
361 if (
auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
362 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
367 if (
auto CastInst = dyn_cast<Instruction>(Opnd)) {
376 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
382 if (
auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
384 if (!ConstExpr->isCast())
387 if (
auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
390 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
399 void ConstantHoistingPass::collectConstantCandidates(
400 ConstCandMapType &ConstCandMap,
Instruction *Inst) {
412 collectConstantCandidates(ConstCandMap, Inst, Idx);
419 void ConstantHoistingPass::collectConstantCandidates(
Function &Fn) {
420 ConstCandMapType ConstCandMap;
423 collectConstantCandidates(ConstCandMap, &Inst);
438 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
441 uint64_t Diff = LimVal1 - LimVal2;
442 return APInt(BW, Diff,
true);
469 ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
470 ConstCandVecType::iterator
E,
471 ConstCandVecType::iterator &MaxCostItr) {
472 unsigned NumUses = 0;
474 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
475 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
476 NumUses += ConstCand->Uses.size();
477 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
478 MaxCostItr = ConstCand;
483 DEBUG(
dbgs() <<
"== Maximize constants in range ==\n");
485 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
486 auto Value = ConstCand->ConstInt->getValue();
487 Type *Ty = ConstCand->ConstInt->getType();
489 NumUses += ConstCand->Uses.size();
490 DEBUG(
dbgs() <<
"= Constant: " << ConstCand->ConstInt->getValue() <<
"\n");
492 for (
auto User : ConstCand->Uses) {
493 unsigned Opcode =
User.Inst->getOpcode();
494 unsigned OpndIdx =
User.OpndIdx;
495 Cost += TTI->getIntImmCost(Opcode, OpndIdx,
Value, Ty);
496 DEBUG(
dbgs() <<
"Cost: " << Cost <<
"\n");
498 for (
auto C2 = S; C2 !=
E; ++C2) {
500 C2->ConstInt->getValue(),
501 ConstCand->ConstInt->getValue());
504 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.
getValue(), Ty);
507 <<
"has penalty: " << ImmCosts <<
"\n"
508 <<
"Adjusted cost: " << Cost <<
"\n");
512 DEBUG(
dbgs() <<
"Cumulative cost: " << Cost <<
"\n");
513 if (Cost > MaxCost) {
515 MaxCostItr = ConstCand;
516 DEBUG(
dbgs() <<
"New candidate: " << MaxCostItr->ConstInt->getValue()
525 void ConstantHoistingPass::findAndMakeBaseConstant(
526 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
528 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
539 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
540 APInt Diff = ConstCand->ConstInt->getValue() -
546 ConstantVec.push_back(std::move(ConstInfo));
551 void ConstantHoistingPass::findBaseConstants() {
553 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
557 RHS.ConstInt->getType()->getBitWidth();
563 auto MinValItr = ConstCandVec.begin();
564 for (
auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
566 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
568 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
575 findAndMakeBaseConstant(MinValItr, CC);
580 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
590 if (
auto PHI = dyn_cast<PHINode>(Inst)) {
597 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
598 for (
unsigned i = 0; i < Idx; ++i) {
599 if (PHI->getIncomingBlock(i) == IncomingBB) {
600 Value *IncomingVal = PHI->getIncomingValue(i);
621 "const_mat", InsertionPt);
624 <<
" + " << *Offset <<
") in BB "
631 if (isa<ConstantInt>(Opnd)) {
640 if (
auto CastInst = dyn_cast<Instruction>(Opnd)) {
645 if (!ClonedCastInst) {
648 ClonedCastInst->insertAfter(
CastInst);
652 <<
"To : " << *ClonedCastInst <<
'\n');
662 if (
auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
663 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
671 DEBUG(
dbgs() <<
"Create instruction: " << *ConstExprInst <<
'\n'
672 <<
"From : " << *ConstExpr <<
'\n');
686 bool ConstantHoistingPass::emitBaseConstants() {
687 bool MadeChange =
false;
688 for (
auto const &ConstInfo : ConstantVec) {
693 unsigned UsesNum = 0;
694 unsigned ReBasesNum = 0;
700 <<
") to BB " <<
IP->getParent()->getName() <<
'\n'
706 for (
auto const &U : RCI.Uses) {
709 findMatInsertPt(U.Inst, U.OpndIdx)->
getParent();
712 if (IPSet.size() == 1 ||
713 DT->dominates(Base->
getParent(), OrigMatInsertBB)) {
714 emitBaseConstants(Base, RCI.Offset, U);
724 "All uses should be instructions.");
730 assert(UsesNum == ReBasesNum &&
"Not all uses are rebased");
732 NumConstantsHoisted++;
745 void ConstantHoistingPass::deleteDeadCastInst()
const {
746 for (
auto const &
I : ClonedCastMap)
747 if (
I.first->use_empty())
748 I.first->eraseFromParent();
758 this->Entry = &Entry;
760 collectConstantCandidates(Fn);
763 if (ConstCandVec.empty())
771 if (ConstantVec.empty())
776 bool MadeChange = emitBaseConstants();
779 deleteDeadCastInst();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI, BasicBlock *Entry, SmallPtrSet< BasicBlock *, 8 > &BBs)
Given BBs as input, find another set of BBs which collectively dominates BBs and have the minimal sum...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A base constant and all its rebased constants.
STATISTIC(NumFunctions,"Total number of functions")
bool ult(const APInt &RHS) const
Unsigned less than comparison.
void initializeConstantHoistingLegacyPassPass(PassRegistry &)
virtual void releaseMemory()
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
unsigned getNumOperands() const
Keeps track of a constant candidate and its uses.
Analysis pass providing the TargetTransformInfo.
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
bool isEHPad() const
Return true if this basic block is an exception handling block.
const Function * getParent() const
Return the enclosing method, or null if none.
Analysis pass which computes a DominatorTree.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This represents a constant that has been rebased with respect to a base constant. ...
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Legacy analysis pass which computes BlockFrequencyInfo.
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."))
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
LLVM_NODISCARD bool empty() const
const T & getValue() const LLVM_LVALUE_FUNCTION
This class represents a no-op cast from one type to another.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
ConstantInt * BaseConstant
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important base class in LLVM.
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
int64_t getSExtValue() const
Get sign extended value.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again...
Class to represent integer types.
LLVM_NODISCARD bool empty() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Keeps track of the user of a constant and the operand index where the constant is used...
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const BasicBlock & getEntryBlock() const
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Class for arbitrary precision integers.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass,"consthoist","Constant Hoisting", false, false) INITIALIZE_PASS_END(ConstantHoistingLegacyPass
Represents analyses that only rely on functions' control flow.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
void preserveSet()
Mark an analysis set as preserved.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT, BlockFrequencyInfo *BFI, BasicBlock &Entry)
Optimize expensive integer constants in the given function.
static llvm::Optional< APInt > calculateOffsetDiff(const APInt &V1, const APInt &V2)
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
RebasedConstantListType RebasedConstants
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
const BasicBlock * getParent() const
FunctionPass * createConstantHoistingPass()
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.