52#define DEBUG_TYPE "machine-cse"
54STATISTIC(NumCoalesces,
"Number of copies coalesced");
55STATISTIC(NumCSEs,
"Number of common subexpression eliminated");
56STATISTIC(NumPREs,
"Number of partial redundant expression"
57 " transformed to fully redundant");
59 "Number of physreg referencing common subexpr eliminated");
61 "Number of cross-MBB physreg referencing CS eliminated");
62STATISTIC(NumCommutes,
"Number of copies coalesced after commuting");
67 const CodeGenOptions &Opts;
77 : Opts(Opts), DT(DT), MBFI(MBFI) {}
83 ScopedHashTableVal<MachineInstr *, unsigned>>;
85 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
90 unsigned LookAheadLimit = 0;
91 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
92 DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
98 bool PerformTrivialCopyPropagation(MachineInstr *
MI, MachineBasicBlock *
MBB);
99 bool isPhysDefTriviallyDead(MCRegister
Reg,
102 bool hasLivePhysRegDefUses(
const MachineInstr *
MI,
103 const MachineBasicBlock *
MBB,
104 SmallSet<MCRegister, 8> &PhysRefs,
105 PhysDefVector &PhysDefs,
bool &PhysUseDef)
const;
106 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *
MI,
107 const SmallSet<MCRegister, 8> &PhysRefs,
108 const PhysDefVector &PhysDefs,
bool &NonLocal)
const;
109 bool isCSECandidate(MachineInstr *
MI);
112 void EnterScope(MachineBasicBlock *
MBB);
113 void ExitScope(MachineBasicBlock *
MBB);
114 bool ProcessBlockCSE(MachineBasicBlock *
MBB);
116 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren);
119 bool isPRECandidate(MachineInstr *
MI, SmallSet<MCRegister, 8> &PhysRefs);
120 bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *
MBB);
121 bool PerformSimplePRE(MachineDominatorTree *DT);
124 bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
125 MachineBasicBlock *
MBB, MachineBasicBlock *MBB1);
126 void releaseMemory();
133 MachineCSELegacy() : MachineFunctionPass(ID) {}
137 void getAnalysisUsage(AnalysisUsage &AU)
const override {
141 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
144 MachineFunctionProperties getRequiredProperties()
const override {
145 return MachineFunctionProperties().setIsSSA();
150char MachineCSELegacy::ID = 0;
155 "Machine Common Subexpression Elimination",
false,
false)
164bool MachineCSEImpl::PerformTrivialCopyPropagation(
MachineInstr *
MI,
168 Register Reg = MO.getReg();
169 if (!Reg.isVirtual())
171 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
172 MachineInstr *DefMI = MRI->getVRegDef(Reg);
173 if (!DefMI || !DefMI->isCopy())
175 Register SrcReg = DefMI->getOperand(1).getReg();
176 if (!SrcReg.isVirtual())
190 if (DefMI->getOperand(1).getSubReg())
192 if (!MRI->constrainRegAttrs(SrcReg, Reg))
194 LLVM_DEBUG(dbgs() <<
"Coalescing: " << *DefMI);
195 LLVM_DEBUG(dbgs() <<
"*** to: " << *MI);
204 DefMI->changeDebugValuesDefReg(SrcReg);
206 DefMI->eraseFromParent();
215bool MachineCSEImpl::isPhysDefTriviallyDead(
218 unsigned LookAheadLeft = LookAheadLimit;
219 while (LookAheadLeft) {
227 bool SeenDef =
false;
228 for (
const MachineOperand &MO :
I->operands()) {
229 if (MO.isRegMask() && MO.clobbersPhysReg(
Reg))
231 if (!MO.isReg() || !MO.getReg())
233 if (!
TRI->regsOverlap(MO.getReg(),
Reg))
265 return TRI.isCallerPreservedPhysReg(
Reg, MF) ||
266 TII.isIgnorableUse(
MI, OpIdx) ||
267 (
MRI.reservedRegsFrozen() &&
MRI.isConstantPhysReg(
Reg));
274bool MachineCSEImpl::hasLivePhysRegDefUses(
const MachineInstr *
MI,
275 const MachineBasicBlock *
MBB,
276 SmallSet<MCRegister, 8> &PhysRefs,
277 PhysDefVector &PhysDefs,
278 bool &PhysUseDef)
const {
280 for (
const MachineOperand &MO :
MI->all_uses()) {
288 MI->getOperandNo(&MO), *
MI->getMF(),
290 for (MCRegAliasIterator AI(
Reg,
TRI,
true); AI.isValid(); ++AI)
299 const MachineOperand &MO = MOP.value();
314 PhysDefs.emplace_back(MOP.index(),
Reg);
318 for (
const auto &Def : PhysDefs)
319 for (MCRegAliasIterator AI(
Def.second,
TRI,
true); AI.isValid(); ++AI)
322 return !PhysRefs.
empty();
325bool MachineCSEImpl::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *
MI,
326 const SmallSet<MCRegister, 8> &PhysRefs,
327 const PhysDefVector &PhysDefs,
328 bool &NonLocal)
const {
333 const MachineBasicBlock *CSMBB = CSMI->
getParent();
335 bool CrossMBB =
false;
340 for (
const auto &PhysDef : PhysDefs) {
351 unsigned LookAheadLeft = LookAheadLimit;
352 while (LookAheadLeft) {
354 while (
I !=
E &&
I != EE &&
I->isDebugInstr())
358 assert(CrossMBB &&
"Reaching end-of-MBB without finding MI?");
370 for (
const MachineOperand &MO :
I->operands()) {
391bool MachineCSEImpl::isCSECandidate(MachineInstr *
MI) {
392 if (
MI->isPosition() ||
MI->isPHI() ||
MI->isImplicitDef() ||
MI->isKill() ||
393 MI->isInlineAsm() ||
MI->isDebugInstr() ||
MI->isJumpTableDebugInfo() ||
398 if (
MI->isCopyLike())
402 if (
MI->mayStore() ||
MI->isCall() ||
MI->isTerminator() ||
403 MI->mayRaiseFPException() ||
MI->hasUnmodeledSideEffects())
410 if (!
MI->isDereferenceableInvariantLoad())
419 if (
MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
429 MachineBasicBlock *CSBB,
431 if (Opts.machine_cse_aggressive)
438 bool MayIncreasePressure =
true;
440 MayIncreasePressure =
false;
441 SmallPtrSet<MachineInstr*, 8> CSUses;
447 if (++NumOfUses > Opts.machine_cse_csuses_threshold) {
448 MayIncreasePressure =
true;
452 if (!MayIncreasePressure)
455 MayIncreasePressure =
true;
460 if (!MayIncreasePressure)
return true;
466 MachineBasicBlock *BB =
MI->getParent();
473 bool HasVRegUse =
false;
474 for (
const MachineOperand &MO :
MI->all_uses()) {
481 bool HasNonCopyUse =
false;
484 if (!
MI.isCopyLike()) {
485 HasNonCopyUse =
true;
497 HasPHI |=
UseMI.isPHI();
505void MachineCSEImpl::EnterScope(MachineBasicBlock *
MBB) {
507 ScopeType *
Scope =
new ScopeType(VNT);
511void MachineCSEImpl::ExitScope(MachineBasicBlock *
MBB) {
513 auto SI = ScopeMap.find(
MBB);
514 assert(SI != ScopeMap.end());
519bool MachineCSEImpl::ProcessBlockCSE(MachineBasicBlock *
MBB) {
523 SmallVector<unsigned, 2> ImplicitDefsToUpdate;
526 if (!isCSECandidate(&
MI))
529 bool FoundCSE = VNT.
count(&
MI);
532 if (PerformTrivialCopyPropagation(&
MI,
MBB)) {
545 bool Commuted =
false;
546 if (!FoundCSE &&
MI.isCommutable()) {
547 if (MachineInstr *NewMI =
TII->commuteInstruction(
MI)) {
549 FoundCSE = VNT.
count(NewMI);
552 NewMI->eraseFromParent();
554 }
else if (!FoundCSE)
556 (void)
TII->commuteInstruction(
MI);
563 bool CrossMBBPhysDef =
false;
564 SmallSet<MCRegister, 8> PhysRefs;
565 PhysDefVector PhysDefs;
566 bool PhysUseDef =
false;
568 hasLivePhysRegDefUses(&
MI,
MBB, PhysRefs, PhysDefs, PhysUseDef)) {
578 MachineInstr *CSMI = Exps[CSVN];
579 if (PhysRegDefsReach(CSMI, &
MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
592 MachineInstr *CSMI = Exps[CSVN];
594 LLVM_DEBUG(
dbgs() <<
"*** Found a common subexpression: " << *CSMI);
605 if (
MI.isConvergent() &&
MI.getParent() != CSMI->
getParent()) {
606 LLVM_DEBUG(
dbgs() <<
"*** Convergent MI and subexpression exist in "
607 "different BBs, avoid CSE!\n");
615 unsigned NumDefs =
MI.getNumDefs();
617 for (
unsigned i = 0, e =
MI.getNumOperands(); NumDefs && i != e; ++i) {
618 MachineOperand &MO =
MI.getOperand(i);
634 if (OldReg == NewReg) {
640 "Do not CSE physical register defs!");
642 if (!isProfitableToCSE(NewReg, OldReg, CSMI->
getParent(), &
MI)) {
653 dbgs() <<
"*** Not the same register constraints, avoid CSE!\n");
664 for (
const std::pair<Register, Register> &CSEPair : CSEPairs) {
669 assert(Def !=
nullptr &&
"CSEd register has no unique definition?");
670 Def->clearRegisterDeads(NewReg);
676 for (
unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
678 for (
const auto &PhysDef : PhysDefs)
679 if (!
MI.getOperand(PhysDef.first).isDead())
695 for (
auto ImplicitDef : ImplicitDefs)
696 if (MachineOperand *MO =
II->findRegisterUseOperand(
697 ImplicitDef,
TRI,
true))
701 ClearKills(CSMI,
MI);
707 if (CrossMBBPhysDef) {
710 while (!PhysDefs.empty()) {
711 auto LiveIn = PhysDefs.pop_back_val();
718 MI.eraseFromParent();
720 if (!PhysRefs.
empty())
730 ImplicitDefsToUpdate.clear();
731 ImplicitDefs.clear();
740void MachineCSEImpl::ExitScopeIfDone(
742 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren) {
743 if (OpenChildren[Node])
747 ExitScope(
Node->getBlock());
751 unsigned Left = --OpenChildren[Parent];
754 ExitScope(Parent->getBlock());
762 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
771 size_t WorkListSize = WorkList.
size();
773 OpenChildren[
Node] = WorkList.
size() - WorkListSize;
774 }
while (!WorkList.
empty());
779 MachineBasicBlock *
MBB =
Node->getBlock();
783 ExitScopeIfDone(Node, OpenChildren);
792bool MachineCSEImpl::isPRECandidate(MachineInstr *
MI,
793 SmallSet<MCRegister, 8> &PhysRefs) {
794 if (!isCSECandidate(
MI) ||
795 MI->isNotDuplicable() ||
798 MI->getNumDefs() != 1 ||
799 MI->getNumExplicitDefs() != 1)
802 for (
const MachineOperand &MO :
MI->operands()) {
814bool MachineCSEImpl::ProcessBlockPRE(MachineDominatorTree *DT,
815 MachineBasicBlock *
MBB) {
818 SmallSet<MCRegister, 8> PhysRefs;
819 if (!isPRECandidate(&
MI, PhysRefs))
826 auto *MBB1 = It->second;
829 "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
831 if (!CMBB->isLegalToHoistInto())
834 if (!isProfitableToHoistInto(CMBB,
MBB, MBB1))
841 if (BB !=
nullptr && BB1 !=
nullptr &&
851 if (
MI.isConvergent() && CMBB !=
MBB)
857 PhysDefVector PhysDefs;
858 if (!PhysRefs.
empty() &&
859 !PhysRegDefsReach(&*(CMBB->getFirstTerminator()), &
MI, PhysRefs,
864 "First operand of instr with one explicit def must be this def");
867 if (!isProfitableToCSE(NewReg, VReg, CMBB, &
MI))
869 MachineInstr &NewMI =
870 TII->duplicate(*CMBB, CMBB->getFirstTerminator(),
MI);
894bool MachineCSEImpl::PerformSimplePRE(MachineDominatorTree *DT) {
904 MachineBasicBlock *
MBB =
Node->getBlock();
907 }
while (!BBs.
empty());
912bool MachineCSEImpl::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
913 MachineBasicBlock *
MBB,
914 MachineBasicBlock *MBB1) {
919 "CandidateBB should dominate MBB1");
924void MachineCSEImpl::releaseMemory() {
934 LookAheadLimit =
TII->getMachineCSELookAheadLimit();
935 bool ChangedPRE, ChangedCSE;
936 ChangedPRE = PerformSimplePRE(DT);
939 return ChangedPRE || ChangedCSE;
964 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
966 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static bool isCallerPreservedOrConstPhysReg(MCRegister Reg, const MachineInstr &MI, unsigned OpIdx, const MachineFunction &MF, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
bool isAsCheapAsAMove(const MachineInstr &MI) const override
Wrapper class representing physical registers. Should be passed by value.
An RAII based helper class to modify MachineFunctionProperties when running pass.
unsigned pred_size() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
pred_iterator pred_begin()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI Register cloneVirtualRegister(Register VReg, StringRef Name="")
Create and return a new virtual register in the function with the same attributes as the given regist...
LLVM_ABI bool constrainRegAttrs(Register Reg, Register ConstrainingReg, unsigned MinNumRegs=0)
Constrain the register class or the register bank of the virtual register Reg (and low-level type) to...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
size_type count(const K &Key) const
Return 1 if the specified key is in the table, 0 otherwise.
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< MachineInstr *, unsigned, MachineInstrExpressionTrait, AllocatorTy > ScopeTy
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< DefNode * > Def
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)