74 #define DEBUG_TYPE "consthoist" 76 STATISTIC(NumConstantsHoisted,
"Number of constants hoisted");
77 STATISTIC(NumConstantsRebased,
"Number of constants rebased");
81 cl::desc(
"Enable the use of the block frequency analysis to reduce the " 82 "chance to execute const materialization more frequently than " 83 "without hoisting."));
98 StringRef getPassName()
const override {
return "Constant Hoisting"; }
119 "Constant Hoisting",
false,
false)
127 return new ConstantHoistingLegacyPass();
132 if (skipFunction(Fn))
135 LLVM_DEBUG(
dbgs() <<
"********** Begin Constant Hoisting **********\n");
139 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
140 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
142 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
147 LLVM_DEBUG(
dbgs() <<
"********** Function after Constant Hoisting: " 151 LLVM_DEBUG(
dbgs() <<
"********** End Constant Hoisting **********\n");
158 unsigned Idx)
const {
163 if (
auto CastInst = dyn_cast<Instruction>(Opnd))
169 if (!isa<PHINode>(Inst) && !Inst->
isEHPad())
174 assert(Entry != Inst->
getParent() &&
"PHI or landing pad in entry block!");
175 if (Idx != ~0U && isa<PHINode>(Inst))
176 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
181 auto IDom = DT->getNode(Inst->
getParent())->getIDom();
182 while (IDom->getBlock()->isEHPad()) {
183 assert(Entry != IDom->getBlock() &&
"eh pad in entry block");
184 IDom = IDom->getIDom();
187 return IDom->getBlock()->getTerminator();
196 assert(!BBs.
count(Entry) &&
"Assume Entry is not in BBs");
203 for (
auto BB : BBs) {
209 bool isCandidate =
false;
212 if (Node == Entry || Candidates.
count(Node)) {
217 "Entry doens't dominate current Node");
219 }
while (!BBs.count(Node));
227 Candidates.
insert(Path.begin(), Path.end());
235 while (Idx != Orders.
size()) {
238 if (Candidates.
count(ChildDomNode->getBlock()))
239 Orders.
push_back(ChildDomNode->getBlock());
244 using InsertPtsCostPair =
251 for (
auto RIt = Orders.
rbegin(); RIt != Orders.
rend(); RIt++) {
253 bool NodeInBBs = BBs.count(Node);
255 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
264 BBs.insert(InsertPts.
begin(), InsertPts.
end());
272 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
283 ParentInsertPts.
insert(Node);
287 ParentPtsFreq += InsertPtsFreq;
300 for (
auto const &U : RCI.Uses)
301 BBs.
insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
303 if (BBs.count(Entry)) {
304 InsertPts.
insert(&Entry->front());
310 for (
auto BB : BBs) {
312 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
314 InsertPts.
insert(&*InsertPt);
319 while (BBs.size() >= 2) {
322 BB2 = *std::next(BBs.begin());
323 BB = DT->findNearestCommonDominator(BB1, BB2);
325 InsertPts.
insert(&Entry->front());
332 assert((BBs.size() == 1) &&
"Expected only one element.");
334 InsertPts.
insert(findMatInsertPt(&FirstInst));
344 void ConstantHoistingPass::collectConstantCandidates(
345 ConstCandMapType &ConstCandMap,
Instruction *Inst,
unsigned Idx,
350 if (
auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
351 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
359 ConstCandMapType::iterator Itr;
361 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
364 Itr->second = ConstCandVec.size() - 1;
366 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
368 <<
"Collect constant " << *ConstInt <<
" from " << *Inst
369 <<
" with cost " << Cost <<
'\n';
370 else dbgs() <<
"Collect constant " << *ConstInt
371 <<
" indirectly from " << *Inst <<
" via " 372 << *Inst->
getOperand(Idx) <<
" with cost " << Cost
378 void ConstantHoistingPass::collectConstantCandidates(
379 ConstCandMapType &ConstCandMap,
Instruction *Inst,
unsigned Idx) {
383 if (
auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
384 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
389 if (
auto CastInst = dyn_cast<Instruction>(Opnd)) {
398 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
404 if (
auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
406 if (!ConstExpr->isCast())
409 if (
auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
412 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
420 void ConstantHoistingPass::collectConstantCandidates(
421 ConstCandMapType &ConstCandMap,
Instruction *Inst) {
433 collectConstantCandidates(ConstCandMap, Inst, Idx);
440 void ConstantHoistingPass::collectConstantCandidates(
Function &Fn) {
441 ConstCandMapType ConstCandMap;
444 collectConstantCandidates(ConstCandMap, &Inst);
458 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
461 uint64_t Diff = LimVal1 - LimVal2;
462 return APInt(BW, Diff,
true);
489 ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
490 ConstCandVecType::iterator
E,
491 ConstCandVecType::iterator &MaxCostItr) {
492 unsigned NumUses = 0;
494 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
495 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
496 NumUses += ConstCand->Uses.size();
497 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
498 MaxCostItr = ConstCand;
505 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
506 auto Value = ConstCand->ConstInt->getValue();
507 Type *Ty = ConstCand->ConstInt->getType();
509 NumUses += ConstCand->Uses.size();
510 LLVM_DEBUG(
dbgs() <<
"= Constant: " << ConstCand->ConstInt->getValue()
513 for (
auto User : ConstCand->Uses) {
514 unsigned Opcode =
User.Inst->getOpcode();
515 unsigned OpndIdx =
User.OpndIdx;
516 Cost += TTI->getIntImmCost(Opcode, OpndIdx,
Value, Ty);
519 for (
auto C2 = S; C2 !=
E; ++C2) {
521 C2->ConstInt->getValue(),
522 ConstCand->ConstInt->getValue());
525 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.
getValue(), Ty);
528 <<
"has penalty: " << ImmCosts <<
"\n" 529 <<
"Adjusted cost: " << Cost <<
"\n");
534 if (Cost > MaxCost) {
536 MaxCostItr = ConstCand;
537 LLVM_DEBUG(
dbgs() <<
"New candidate: " << MaxCostItr->ConstInt->getValue()
546 void ConstantHoistingPass::findAndMakeBaseConstant(
547 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
549 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
560 for (
auto ConstCand = S; ConstCand !=
E; ++ConstCand) {
561 APInt Diff = ConstCand->ConstInt->getValue() -
567 ConstantVec.push_back(std::move(ConstInfo));
572 void ConstantHoistingPass::findBaseConstants() {
574 llvm::sort(ConstCandVec.begin(), ConstCandVec.end(),
578 RHS.ConstInt->getType()->getBitWidth();
584 auto MinValItr = ConstCandVec.begin();
585 for (
auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
587 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
589 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
596 findAndMakeBaseConstant(MinValItr, CC);
601 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
611 if (
auto PHI = dyn_cast<PHINode>(Inst)) {
618 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
619 for (
unsigned i = 0; i < Idx; ++i) {
620 if (PHI->getIncomingBlock(i) == IncomingBB) {
621 Value *IncomingVal = PHI->getIncomingValue(i);
642 "const_mat", InsertionPt);
645 <<
" + " << *Offset <<
") in BB " 653 if (isa<ConstantInt>(Opnd)) {
662 if (
auto CastInst = dyn_cast<Instruction>(Opnd)) {
667 if (!ClonedCastInst) {
670 ClonedCastInst->insertAfter(
CastInst);
674 <<
"To : " << *ClonedCastInst <<
'\n');
684 if (
auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
685 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
693 LLVM_DEBUG(
dbgs() <<
"Create instruction: " << *ConstExprInst <<
'\n' 694 <<
"From : " << *ConstExpr <<
'\n');
708 bool ConstantHoistingPass::emitBaseConstants() {
709 bool MadeChange =
false;
710 for (
auto const &ConstInfo : ConstantVec) {
715 unsigned UsesNum = 0;
716 unsigned ReBasesNum = 0;
725 <<
") to BB " << IP->getParent()->
getName() <<
'\n' 731 for (
auto const &U : RCI.Uses) {
734 findMatInsertPt(U.Inst, U.OpndIdx)->
getParent();
737 if (IPSet.size() == 1 ||
738 DT->dominates(Base->
getParent(), OrigMatInsertBB)) {
739 emitBaseConstants(Base, RCI.Offset, U);
751 "All uses should be instructions.");
756 assert(UsesNum == ReBasesNum &&
"Not all uses are rebased");
758 NumConstantsHoisted++;
771 void ConstantHoistingPass::deleteDeadCastInst()
const {
772 for (
auto const &
I : ClonedCastMap)
773 if (
I.first->use_empty())
774 I.first->eraseFromParent();
784 this->Entry = &Entry;
786 collectConstantCandidates(Fn);
789 if (ConstCandVec.empty())
797 if (ConstantVec.empty())
802 bool MadeChange = emitBaseConstants();
805 deleteDeadCastInst();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist", "Constant Hoisting", false, false) INITIALIZE_PASS_END(ConstantHoistingLegacyPass
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.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
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...
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.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
This represents a constant that has been rebased with respect to a base constant. ...
unsigned getBitWidth() const
Return the number of bits in the APInt.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This is the base class for all instructions that perform data casts.
Legacy analysis pass which computes BlockFrequencyInfo.
This file implements a class to represent arbitrary precision integral constant values and operations...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
int64_t getSExtValue() const
Get sign extended value.
const T & getValue() const LLVM_LVALUE_FUNCTION
This class represents a no-op cast from one type to another.
const std::vector< DomTreeNodeBase * > & getChildren() const
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
ConstantInt * BaseConstant
const BasicBlock & getEntryBlock() const
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static bool runOnFunction(Function &F, bool PostInlining)
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...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant 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.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Class to represent integer types.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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."))
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void sort(IteratorTy Start, IteratorTy End)
Keeps track of the user of a constant and the operand index where the constant is used...
static const DILocation * getMergedLocation(const DILocation *LocA, const DILocation *LocB, bool GenerateLocation=NoGeneratedLocation)
When two instructions are combined into a single instruction we also need to combine the original loc...
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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...
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:
static Optional< APInt > calculateOffsetDiff(const APInt &V1, const APInt &V2)
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
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.
Represents analyses that only rely on functions' control flow.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_NODISCARD bool empty() const
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...
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT, BlockFrequencyInfo *BFI, BasicBlock &Entry)
Optimize expensive integer constants in the given function.
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isEHPad() const
Return true if this basic block is an exception handling block.
LLVM Value Representation.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
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.
const BasicBlock * getParent() const
FunctionPass * createConstantHoistingPass()