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"),
107 unsigned Pattern,
bool SlackIsAccurate);
118 std::pair<unsigned, unsigned>
130char MachineCombiner::ID = 0;
134 "Machine InstCombiner",
false,
false)
140void MachineCombiner::getAnalysisUsage(
AnalysisUsage &AU)
const {
141 AU.setPreservesCFG();
157 DefInstr =
MRI->getUniqueVRegDef(MO.
getReg());
164 return MI->isTransient();
170 if (!
MI->isFullCopy()) {
172 if (
MI->getOperand(0).getSubReg() || Src.isPhysical() || Dst.isPhysical())
175 auto SrcSub =
MI->getOperand(1).getSubReg();
176 auto SrcRC =
MRI->getRegClass(Src);
177 auto DstRC =
MRI->getRegClass(Dst);
178 return TRI->getMatchingSuperRegClass(SrcRC, DstRC, SrcSub) !=
nullptr;
181 if (Src.isPhysical() && Dst.isPhysical())
184 if (Src.isVirtual() && Dst.isVirtual()) {
185 auto SrcRC =
MRI->getRegClass(Src);
186 auto DstRC =
MRI->getRegClass(Dst);
187 return SrcRC->hasSuperClassEq(DstRC) || SrcRC->hasSubClassEq(DstRC);
194 auto DstRC =
MRI->getRegClass(Dst);
195 return DstRC->contains(Src);
215 for (
auto *InstrPtr : InsInstrs) {
221 unsigned DepthOp = 0;
222 unsigned LatencyOp = 0;
225 if (
II != InstrIdxForVirtReg.
end()) {
230 "There must be a definition for a new virtual register");
231 DepthOp = InstrDepth[
II->second];
235 InstrPtr->findRegisterUseOperandIdx(MO.
getReg(),
nullptr);
236 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
240 if (DefInstr && (
TII->getMachineCombinerTraceStrategy() !=
241 MachineTraceStrategy::TS_Local ||
244 if (!isTransientMI(DefInstr))
245 LatencyOp = TSchedModel.computeOperandLatency(
250 InstrPtr->findRegisterUseOperandIdx(MO.
getReg(),
254 IDepth = std::max(IDepth, DepthOp + LatencyOp);
258 unsigned NewRootIdx = InsInstrs.size() - 1;
259 return InstrDepth[NewRootIdx];
274 unsigned NewRootLatency = 0;
283 if (RI ==
MRI->reg_end())
286 unsigned LatencyOp = 0;
288 LatencyOp = TSchedModel.computeOperandLatency(
294 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
296 NewRootLatency = std::max(NewRootLatency, LatencyOp);
298 return NewRootLatency;
305 case MachineCombinerPattern::REASSOC_AX_BY:
306 case MachineCombinerPattern::REASSOC_AX_YB:
307 case MachineCombinerPattern::REASSOC_XA_BY:
308 case MachineCombinerPattern::REASSOC_XA_YB:
309 return CombinerObjective::MustReduceDepth;
319std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
323 assert(!InsInstrs.
empty() &&
"Only support sequences that insert instrs.");
324 unsigned NewRootLatency = 0;
327 for (
unsigned i = 0; i < InsInstrs.
size() - 1; i++)
328 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
331 unsigned RootLatency = 0;
332 for (
auto *
I : DelInstrs)
333 RootLatency += TSchedModel.computeInstrLatency(
I);
335 return {NewRootLatency, RootLatency};
338bool MachineCombiner::reduceRegisterPressure(
354bool MachineCombiner::improvesCriticalPathLen(
360 bool SlackIsAccurate) {
362 unsigned NewRootDepth =
363 getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace, *
MBB);
366 LLVM_DEBUG(
dbgs() <<
" Dependence data for " << *Root <<
"\tNewRootDepth: "
367 << NewRootDepth <<
"\tRootDepth: " << RootDepth);
374 if (getCombinerObjective(
Pattern) == CombinerObjective::MustReduceDepth) {
377 ?
dbgs() <<
"\t and it does it\n"
378 :
dbgs() <<
"\t but it does NOT do it\n");
379 return NewRootDepth < RootDepth;
387 unsigned NewRootLatency, RootLatency;
388 if (
TII->accumulateInstrSeqToRootLatency(*Root)) {
389 std::tie(NewRootLatency, RootLatency) =
390 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
392 NewRootLatency = TSchedModel.computeInstrLatency(InsInstrs.
back());
393 RootLatency = TSchedModel.computeInstrLatency(Root);
397 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
398 unsigned OldCycleCount =
399 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
401 <<
"\tRootLatency: " << RootLatency <<
"\n\tRootSlack: "
402 << RootSlack <<
" SlackIsAccurate=" << SlackIsAccurate
403 <<
"\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
404 <<
"\n\tRootDepth + RootLatency + RootSlack = "
407 ?
dbgs() <<
"\n\t It IMPROVES PathLen because"
408 :
dbgs() <<
"\n\t It DOES NOT improve PathLen because");
410 <<
", OldCycleCount = " << OldCycleCount <<
"\n");
412 return NewCycleCount <= OldCycleCount;
416void MachineCombiner::instr2instrSC(
419 for (
auto *InstrPtr : Instrs) {
420 unsigned Opc = InstrPtr->getOpcode();
421 unsigned Idx =
TII->get(Opc).getSchedClass();
428bool MachineCombiner::preservesResourceLen(
432 if (!TSchedModel.hasInstrSchedModel())
438 SmallVector <const MachineBasicBlock *, 1> MBBarr;
446 instr2instrSC(InsInstrs, InsInstrsSC);
447 instr2instrSC(DelInstrs, DelInstrsSC);
453 unsigned ResLenAfterCombine =
457 << ResLenBeforeCombine
458 <<
" and after: " << ResLenAfterCombine <<
"\n";);
460 ResLenAfterCombine <=
461 ResLenBeforeCombine +
TII->getExtendResourceLenLimit()
462 ?
dbgs() <<
"\t\t As result it IMPROVES/PRESERVES Resource Length\n"
463 :
dbgs() <<
"\t\t As result it DOES NOT improve/preserve Resource "
466 return ResLenAfterCombine <=
467 ResLenBeforeCombine +
TII->getExtendResourceLenLimit();
490 bool IncrementalUpdate) {
500 for (
auto *InstrPtr : InsInstrs)
503 for (
auto *InstrPtr : DelInstrs) {
504 InstrPtr->eraseFromParent();
506 for (
auto *
I = RegUnits.
begin();
I != RegUnits.
end();) {
507 if (
I->MI == InstrPtr)
514 if (IncrementalUpdate)
515 for (
auto *InstrPtr : InsInstrs)
528 long PrevLatencyDiff = std::numeric_limits<long>::max();
529 (void)PrevLatencyDiff;
530 for (
auto P : Patterns) {
534 TII->genAlternativeCodeSequence(Root,
P, InsInstrs, DelInstrs,
539 if (InsInstrs.
empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
542 unsigned NewRootLatency, RootLatency;
543 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
544 Root, InsInstrs, DelInstrs, TraceEnsemble->getTrace(
MBB));
545 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
546 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
547 "Current pattern is better than previous pattern.");
548 PrevLatencyDiff = CurrentLatencyDiff;
560 bool Changed =
false;
563 bool IncrementalUpdate =
false;
565 decltype(BlockIter) LastUpdate;
569 TraceEnsemble = Traces->getEnsemble(
TII->getMachineCombinerTraceStrategy());
576 bool DoRegPressureReduce =
577 TII->shouldReduceRegisterPressure(
MBB, &RegClassInfo);
579 while (BlockIter !=
MBB->
end()) {
580 auto &
MI = *BlockIter++;
609 if (!
TII->getMachineCombinerPatterns(
MI, Patterns, DoRegPressureReduce))
613 verifyPatternOrder(
MBB,
MI, Patterns);
615 for (
const auto P : Patterns) {
619 TII->genAlternativeCodeSequence(
MI,
P, InsInstrs, DelInstrs,
624 if (InsInstrs.
empty())
628 dbgs() <<
"\tFor the Pattern (" << (int)
P
629 <<
") these instructions could be removed\n";
630 for (
auto const *InstrPtr : DelInstrs)
631 InstrPtr->print(
dbgs(),
false,
false,
633 dbgs() <<
"\tThese instructions could replace the removed ones\n";
634 for (
auto const *InstrPtr : InsInstrs)
635 InstrPtr->print(
dbgs(),
false,
false,
639 if (IncrementalUpdate && LastUpdate != BlockIter) {
641 TraceEnsemble->updateDepths(LastUpdate, BlockIter, RegUnits);
642 LastUpdate = BlockIter;
645 if (DoRegPressureReduce &&
646 getCombinerObjective(
P) ==
647 CombinerObjective::MustReduceRegisterPressure) {
650 IncrementalUpdate =
true;
651 LastUpdate = BlockIter;
653 if (reduceRegisterPressure(
MI,
MBB, InsInstrs, DelInstrs,
P)) {
656 RegUnits,
TII,
P, IncrementalUpdate);
666 if (
ML &&
TII->isThroughputPattern(
P)) {
667 LLVM_DEBUG(
dbgs() <<
"\t Replacing due to throughput pattern in loop\n");
669 RegUnits,
TII,
P, IncrementalUpdate);
673 }
else if (OptForSize && InsInstrs.size() < DelInstrs.size()) {
675 << InsInstrs.size() <<
" < "
676 << DelInstrs.size() <<
")\n");
678 RegUnits,
TII,
P, IncrementalUpdate);
689 Traces->verifyAnalysis();
690 if (improvesCriticalPathLen(
MBB, &
MI, BlockTrace, InsInstrs, DelInstrs,
691 InstrIdxForVirtReg,
P,
692 !IncrementalUpdate) &&
693 preservesResourceLen(
MBB, BlockTrace, InsInstrs, DelInstrs)) {
696 IncrementalUpdate =
true;
697 LastUpdate = BlockIter;
701 RegUnits,
TII,
P, IncrementalUpdate);
710 for (
auto *InstrPtr : InsInstrs)
713 InstrIdxForVirtReg.
clear();
717 if (Changed && IncrementalUpdate)
718 Traces->invalidate(
MBB);
724 TII = STI->getInstrInfo();
725 TRI = STI->getRegisterInfo();
726 SchedModel = STI->getSchedModel();
727 TSchedModel.init(STI);
729 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
730 Traces = &getAnalysis<MachineTraceMetrics>();
731 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
732 MBFI = (PSI && PSI->hasProfileSummary()) ?
733 &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
735 TraceEnsemble =
nullptr;
737 RegClassInfo.runOnMachineFunction(MF);
740 if (!
TII->useMachineCombiner()) {
743 <<
" Skipping pass: Target does not support machine combiner\n");
747 bool Changed =
false;
751 Changed |= combineInstructions(&
MBB);
unsigned const MachineRegisterInfo * MRI
COFF::MachineTypes Machine
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 void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, MachineTraceMetrics::Ensemble *TraceEnsemble, SparseSet< LiveRegUnit > &RegUnits, const TargetInstrInfo *TII, unsigned Pattern, bool IncrementalUpdate)
Inserts InsInstrs and deletes DelInstrs.
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 cl::opt< bool > dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden, cl::desc("Dump all substituted intrs"), cl::init(false))
unsigned const TargetRegisterInfo * TRI
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)
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...
Analysis pass which computes a MachineDominatorTree.
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.
const MachineBasicBlock * getParent() const
int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
iterator_range< filtered_mop_iterator > all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
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.
constexpr 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.
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
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 ...