37#define DEBUG_TYPE "machine-combiner"
39STATISTIC(NumInstCombined,
"Number of machineinst combined");
43 cl::desc(
"Incremental depth computation will be used for basic "
44 "blocks with more instructions."),
cl::init(500));
47 cl::desc(
"Dump all substituted intrs"),
50#ifdef EXPENSIVE_CHECKS
52 "machine-combiner-verify-pattern-order",
cl::Hidden,
54 "Verify that the generated patterns are ordered by increasing latency"),
58 "machine-combiner-verify-pattern-order",
cl::Hidden,
60 "Verify that the generated patterns are ordered by increasing latency"),
119 std::pair<unsigned, unsigned>
130char MachineCombiner::ID = 0;
134 "Machine InstCombiner",
false,
false)
140void MachineCombiner::getAnalysisUsage(
AnalysisUsage &AU)
const {
141 AU.setPreservesCFG();
156 DefInstr =
MRI->getUniqueVRegDef(MO.
getReg());
158 if (DefInstr && DefInstr->
isPHI())
166 return MI->isTransient();
172 if (!
MI->isFullCopy()) {
174 if (
MI->getOperand(0).getSubReg() || Src.isPhysical() || Dst.isPhysical())
177 auto SrcSub =
MI->getOperand(1).getSubReg();
178 auto SrcRC =
MRI->getRegClass(Src);
179 auto DstRC =
MRI->getRegClass(Dst);
180 return TRI->getMatchingSuperRegClass(SrcRC, DstRC, SrcSub) !=
nullptr;
183 if (Src.isPhysical() && Dst.isPhysical())
186 if (Src.isVirtual() && Dst.isVirtual()) {
187 auto SrcRC =
MRI->getRegClass(Src);
188 auto DstRC =
MRI->getRegClass(Dst);
189 return SrcRC->hasSuperClassEq(DstRC) || SrcRC->hasSubClassEq(DstRC);
196 auto DstRC =
MRI->getRegClass(Dst);
197 return DstRC->contains(Src);
217 for (
auto *InstrPtr : InsInstrs) {
225 unsigned DepthOp = 0;
226 unsigned LatencyOp = 0;
229 if (II != InstrIdxForVirtReg.
end()) {
231 assert(II->second < InstrDepth.
size() &&
"Bad Index");
234 "There must be a definition for a new virtual register");
235 DepthOp = InstrDepth[II->second];
237 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.
getReg());
238 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
242 if (DefInstr && (
TII->getMachineCombinerTraceStrategy() !=
243 MachineTraceStrategy::TS_Local ||
246 if (!isTransientMI(DefInstr))
247 LatencyOp = TSchedModel.computeOperandLatency(
249 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.
getReg()));
252 IDepth = std::max(IDepth, DepthOp + LatencyOp);
256 unsigned NewRootIdx = InsInstrs.size() - 1;
257 return InstrDepth[NewRootIdx];
272 unsigned NewRootLatency = 0;
283 if (RI ==
MRI->reg_end())
286 unsigned LatencyOp = 0;
288 LatencyOp = TSchedModel.computeOperandLatency(
292 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
294 NewRootLatency = std::max(NewRootLatency, LatencyOp);
296 return NewRootLatency;
311 case MachineCombinerPattern::REASSOC_AX_BY:
312 case MachineCombinerPattern::REASSOC_AX_YB:
313 case MachineCombinerPattern::REASSOC_XA_BY:
314 case MachineCombinerPattern::REASSOC_XA_YB:
315 case MachineCombinerPattern::REASSOC_XY_AMM_BMM:
316 case MachineCombinerPattern::REASSOC_XMM_AMM_BMM:
317 case MachineCombinerPattern::SUBADD_OP1:
318 case MachineCombinerPattern::SUBADD_OP2:
319 case MachineCombinerPattern::FMADD_AX:
320 case MachineCombinerPattern::FMADD_XA:
321 case MachineCombinerPattern::FMSUB:
322 case MachineCombinerPattern::FNMSUB:
324 case MachineCombinerPattern::REASSOC_XY_BCA:
325 case MachineCombinerPattern::REASSOC_XY_BAC:
336std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
340 assert(!InsInstrs.
empty() &&
"Only support sequences that insert instrs.");
341 unsigned NewRootLatency = 0;
344 for (
unsigned i = 0; i < InsInstrs.
size() - 1; i++)
345 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
348 unsigned RootLatency = 0;
349 for (
auto *
I : DelInstrs)
350 RootLatency += TSchedModel.computeInstrLatency(
I);
352 return {NewRootLatency, RootLatency};
355bool MachineCombiner::reduceRegisterPressure(
372bool MachineCombiner::improvesCriticalPathLen(
379 bool SlackIsAccurate) {
381 unsigned NewRootDepth =
382 getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace, *
MBB);
385 LLVM_DEBUG(
dbgs() <<
" Dependence data for " << *Root <<
"\tNewRootDepth: "
386 << NewRootDepth <<
"\tRootDepth: " << RootDepth);
396 ?
dbgs() <<
"\t and it does it\n"
397 :
dbgs() <<
"\t but it does NOT do it\n");
398 return NewRootDepth < RootDepth;
406 unsigned NewRootLatency, RootLatency;
407 std::tie(NewRootLatency, RootLatency) =
408 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
411 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
412 unsigned OldCycleCount =
413 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
415 <<
"\tRootLatency: " << RootLatency <<
"\n\tRootSlack: "
416 << RootSlack <<
" SlackIsAccurate=" << SlackIsAccurate
417 <<
"\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
418 <<
"\n\tRootDepth + RootLatency + RootSlack = "
421 ?
dbgs() <<
"\n\t It IMPROVES PathLen because"
422 :
dbgs() <<
"\n\t It DOES NOT improve PathLen because");
424 <<
", OldCycleCount = " << OldCycleCount <<
"\n");
426 return NewCycleCount <= OldCycleCount;
430void MachineCombiner::instr2instrSC(
433 for (
auto *InstrPtr : Instrs) {
434 unsigned Opc = InstrPtr->getOpcode();
435 unsigned Idx =
TII->get(Opc).getSchedClass();
442bool MachineCombiner::preservesResourceLen(
446 if (!TSchedModel.hasInstrSchedModel())
452 SmallVector <const MachineBasicBlock *, 1> MBBarr;
460 instr2instrSC(InsInstrs, InsInstrsSC);
461 instr2instrSC(DelInstrs, DelInstrsSC);
467 unsigned ResLenAfterCombine =
471 << ResLenBeforeCombine
472 <<
" and after: " << ResLenAfterCombine <<
"\n";);
474 ResLenAfterCombine <=
475 ResLenBeforeCombine +
TII->getExtendResourceLenLimit()
476 ?
dbgs() <<
"\t\t As result it IMPROVES/PRESERVES Resource Length\n"
477 :
dbgs() <<
"\t\t As result it DOES NOT improve/preserve Resource "
480 return ResLenAfterCombine <=
481 ResLenBeforeCombine +
TII->getExtendResourceLenLimit();
513 for (
auto *InstrPtr : InsInstrs)
516 for (
auto *InstrPtr : DelInstrs) {
517 InstrPtr->eraseFromParent();
519 for (
auto *
I = RegUnits.
begin();
I != RegUnits.
end();) {
520 if (
I->MI == InstrPtr)
527 if (IncrementalUpdate)
528 for (
auto *InstrPtr : InsInstrs)
538void MachineCombiner::verifyPatternOrder(
541 long PrevLatencyDiff = std::numeric_limits<long>::max();
542 (void)PrevLatencyDiff;
543 for (
auto P : Patterns) {
547 TII->genAlternativeCodeSequence(Root,
P, InsInstrs, DelInstrs,
552 if (InsInstrs.
empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
555 unsigned NewRootLatency, RootLatency;
556 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
557 Root, InsInstrs, DelInstrs, TraceEnsemble->getTrace(
MBB));
558 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
559 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
560 "Current pattern is better than previous pattern.");
561 PrevLatencyDiff = CurrentLatencyDiff;
573 bool Changed =
false;
576 bool IncrementalUpdate =
false;
578 decltype(BlockIter) LastUpdate;
582 TraceEnsemble = Traces->getEnsemble(
TII->getMachineCombinerTraceStrategy());
589 bool DoRegPressureReduce =
590 TII->shouldReduceRegisterPressure(
MBB, &RegClassInfo);
592 while (BlockIter !=
MBB->
end()) {
593 auto &
MI = *BlockIter++;
622 if (!
TII->getMachineCombinerPatterns(
MI, Patterns, DoRegPressureReduce))
626 verifyPatternOrder(
MBB,
MI, Patterns);
628 for (
const auto P : Patterns) {
632 TII->genAlternativeCodeSequence(
MI,
P, InsInstrs, DelInstrs,
637 if (InsInstrs.
empty())
641 dbgs() <<
"\tFor the Pattern (" << (int)
P
642 <<
") these instructions could be removed\n";
643 for (
auto const *InstrPtr : DelInstrs)
644 InstrPtr->print(
dbgs(),
false,
false,
646 dbgs() <<
"\tThese instructions could replace the removed ones\n";
647 for (
auto const *InstrPtr : InsInstrs)
648 InstrPtr->print(
dbgs(),
false,
false,
652 if (IncrementalUpdate && LastUpdate != BlockIter) {
654 TraceEnsemble->updateDepths(LastUpdate, BlockIter, RegUnits);
655 LastUpdate = BlockIter;
658 if (DoRegPressureReduce &&
663 IncrementalUpdate =
true;
664 LastUpdate = BlockIter;
666 if (reduceRegisterPressure(
MI,
MBB, InsInstrs, DelInstrs,
P)) {
669 RegUnits,
TII,
P, IncrementalUpdate);
679 if (
ML &&
TII->isThroughputPattern(
P)) {
680 LLVM_DEBUG(
dbgs() <<
"\t Replacing due to throughput pattern in loop\n");
682 RegUnits,
TII,
P, IncrementalUpdate);
686 }
else if (OptForSize && InsInstrs.size() < DelInstrs.size()) {
688 << InsInstrs.size() <<
" < "
689 << DelInstrs.size() <<
")\n");
691 RegUnits,
TII,
P, IncrementalUpdate);
702 Traces->verifyAnalysis();
703 if (improvesCriticalPathLen(
MBB, &
MI, BlockTrace, InsInstrs, DelInstrs,
704 InstrIdxForVirtReg,
P,
705 !IncrementalUpdate) &&
706 preservesResourceLen(
MBB, BlockTrace, InsInstrs, DelInstrs)) {
709 IncrementalUpdate =
true;
710 LastUpdate = BlockIter;
714 RegUnits,
TII,
P, IncrementalUpdate);
723 for (
auto *InstrPtr : InsInstrs)
726 InstrIdxForVirtReg.
clear();
730 if (Changed && IncrementalUpdate)
731 Traces->invalidate(
MBB);
737 TII = STI->getInstrInfo();
738 TRI = STI->getRegisterInfo();
739 SchedModel = STI->getSchedModel();
740 TSchedModel.init(STI);
742 MLI = &getAnalysis<MachineLoopInfo>();
743 Traces = &getAnalysis<MachineTraceMetrics>();
744 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
745 MBFI = (PSI && PSI->hasProfileSummary()) ?
746 &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
748 TraceEnsemble =
nullptr;
750 RegClassInfo.runOnMachineFunction(MF);
753 if (!
TII->useMachineCombiner()) {
756 <<
" Skipping pass: Target does not support machine combiner\n");
760 bool Changed =
false;
764 Changed |= combineInstructions(&
MBB);
unsigned const MachineRegisterInfo * MRI
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Gets latency information for Inst, based on DC information.
const HexagonInstrInfo * TII
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
static CombinerObjective getCombinerObjective(MachineCombinerPattern P)
static cl::opt< bool > VerifyPatternOrder("machine-combiner-verify-pattern-order", cl::Hidden, cl::desc("Verify that the generated patterns are ordered by increasing latency"), cl::init(false))
static cl::opt< unsigned > inc_threshold("machine-combiner-inc-threshold", cl::Hidden, cl::desc("Incremental depth computation will be used for basic " "blocks with more instructions."), cl::init(500))
static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI, SmallVector< MachineInstr *, 16 > InsInstrs, SmallVector< MachineInstr *, 16 > DelInstrs, MachineTraceMetrics::Ensemble *TraceEnsemble, SparseSet< LiveRegUnit > &RegUnits, const TargetInstrInfo *TII, MachineCombinerPattern Pattern, bool IncrementalUpdate)
Inserts InsInstrs and deletes DelInstrs.
static cl::opt< bool > dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden, cl::desc("Dump all substituted intrs"), cl::init(false))
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
@ MustReduceRegisterPressure
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
iterator find(const_arg_type_t< KeyT > Val)
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
The core instruction combiner logic.
This is an alternative analysis pass to MachineBlockFrequencyInfo.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void deleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
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.
int findRegisterUseOperandIdx(Register Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
const MachineBasicBlock * getParent() const
int findRegisterDefOperandIdx(Register Reg, bool isDead=false, bool Overlap=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
iterator_range< mop_iterator > operands()
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A trace ensemble is a collection of traces selected using the same strategy, for example 'minimum res...
void invalidate(const MachineBasicBlock *MBB)
Invalidate traces through BadMBB.
void updateDepth(TraceBlockInfo &TBI, const MachineInstr &, SparseSet< LiveRegUnit > &RegUnits)
Updates the depth of an machine instruction, given RegUnits.
A trace represents a plausible sequence of executed basic blocks that passes through the current basi...
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
bool isDepInTrace(const MachineInstr &DefMI, const MachineInstr &UseMI) const
A dependence is useful if the basic block of the defining instruction is part of the trace of the use...
unsigned getResourceLength(ArrayRef< const MachineBasicBlock * > Extrablocks=std::nullopt, ArrayRef< const MCSchedClassDesc * > ExtraInstrs=std::nullopt, ArrayRef< const MCSchedClassDesc * > RemoveInstrs=std::nullopt) const
Return the resource length of the trace.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
const_iterator begin() const
const_iterator end() const
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
StringRef - Represent a constant reference to a string, i.e.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
TargetSubtargetInfo - Generic base class for all target subtargets.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
char & MachineCombinerID
This pass performs instruction combining using trace metrics to estimate critical-path and resource d...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MachineCombinerPattern
These are instruction patterns matched by the machine combiner pass.
void initializeMachineCombinerPass(PassRegistry &)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Machine model for scheduling, bundling, and heuristics.
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...