36 #define DEBUG_TYPE "machine-combiner" 38 STATISTIC(NumInstCombined,
"Number of machineinst combined");
42 cl::desc(
"Incremental depth computation will be used for basic " 43 "blocks with more instructions."),
cl::init(500));
46 cl::desc(
"Dump all substituted intrs"),
49 #ifdef EXPENSIVE_CHECKS 51 "machine-combiner-verify-pattern-order",
cl::Hidden,
53 "Verify that the generated patterns are ordered by increasing latency"),
57 "machine-combiner-verify-pattern-order",
cl::Hidden,
59 "Verify that the generated patterns are ordered by increasing latency"),
88 StringRef getPassName()
const override {
return "Machine InstCombiner"; }
91 bool doSubstitute(
unsigned NewSize,
unsigned OldSize,
bool OptForSize);
112 std::pair<unsigned, unsigned>
127 "Machine InstCombiner",
false,
false)
133 void MachineCombiner::getAnalysisUsage(
AnalysisUsage &AU)
const {
134 AU.setPreservesCFG();
149 DefInstr =
MRI->getUniqueVRegDef(MO.
getReg());
151 if (DefInstr && DefInstr->
isPHI())
169 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
170 "Missing machine model\n");
175 for (
auto *InstrPtr : InsInstrs) {
183 unsigned DepthOp = 0;
184 unsigned LatencyOp = 0;
187 if (II != InstrIdxForVirtReg.
end()) {
189 assert(II->second < InstrDepth.
size() &&
"Bad Index");
192 "There must be a definition for a new virtual register");
193 DepthOp = InstrDepth[II->second];
194 int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.
getReg());
195 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.
getReg());
196 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
202 LatencyOp = TSchedModel.computeOperandLatency(
204 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.
getReg()));
207 IDepth =
std::max(IDepth, DepthOp + LatencyOp);
211 unsigned NewRootIdx = InsInstrs.size() - 1;
212 return InstrDepth[NewRootIdx];
226 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
227 "Missing machine model\n");
230 unsigned NewRootLatency = 0;
241 if (RI ==
MRI->reg_end())
244 unsigned LatencyOp = 0;
246 LatencyOp = TSchedModel.computeOperandLatency(
250 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
252 NewRootLatency =
std::max(NewRootLatency, LatencyOp);
254 return NewRootLatency;
282 std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
286 assert(!InsInstrs.
empty() &&
"Only support sequences that insert instrs.");
287 unsigned NewRootLatency = 0;
290 for (
unsigned i = 0; i < InsInstrs.
size() - 1; i++)
291 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
292 NewRootLatency +=
getLatency(&MI, NewRoot, BlockTrace);
294 unsigned RootLatency = 0;
295 for (
auto I : DelInstrs)
296 RootLatency += TSchedModel.computeInstrLatency(
I);
298 return {NewRootLatency, RootLatency};
306 bool MachineCombiner::improvesCriticalPathLen(
313 bool SlackIsAccurate) {
314 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
315 "Missing machine model\n");
317 unsigned NewRootDepth =
getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
320 LLVM_DEBUG(
dbgs() <<
" Dependence data for " << *Root <<
"\tNewRootDepth: " 321 << NewRootDepth <<
"\tRootDepth: " << RootDepth);
331 ?
dbgs() <<
"\t and it does it\n" 332 :
dbgs() <<
"\t but it does NOT do it\n");
333 return NewRootDepth < RootDepth;
341 unsigned NewRootLatency, RootLatency;
342 std::tie(NewRootLatency, RootLatency) =
343 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
346 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
347 unsigned OldCycleCount =
348 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
350 <<
"\tRootLatency: " << RootLatency <<
"\n\tRootSlack: " 351 << RootSlack <<
" SlackIsAccurate=" << SlackIsAccurate
352 <<
"\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
353 <<
"\n\tRootDepth + RootLatency + RootSlack = " 356 ?
dbgs() <<
"\n\t It IMPROVES PathLen because" 357 :
dbgs() <<
"\n\t It DOES NOT improve PathLen because");
359 <<
", OldCycleCount = " << OldCycleCount <<
"\n");
361 return NewCycleCount <= OldCycleCount;
365 void MachineCombiner::instr2instrSC(
368 for (
auto *InstrPtr : Instrs) {
369 unsigned Opc = InstrPtr->getOpcode();
370 unsigned Idx =
TII->get(Opc).getSchedClass();
377 bool MachineCombiner::preservesResourceLen(
381 if (!TSchedModel.hasInstrSchedModel())
395 instr2instrSC(InsInstrs, InsInstrsSC);
396 instr2instrSC(DelInstrs, DelInstrsSC);
402 unsigned ResLenAfterCombine =
406 << ResLenBeforeCombine
407 <<
" and after: " << ResLenAfterCombine <<
"\n";);
409 ResLenAfterCombine <= ResLenBeforeCombine
410 ?
dbgs() <<
"\t\t As result it IMPROVES/PRESERVES Resource Length\n" 411 :
dbgs() <<
"\t\t As result it DOES NOT improve/preserve Resource " 414 return ResLenAfterCombine <= ResLenBeforeCombine;
419 bool MachineCombiner::doSubstitute(
unsigned NewSize,
unsigned OldSize,
421 if (OptForSize && (NewSize < OldSize))
423 if (!TSchedModel.hasInstrSchedModelOrItineraries())
444 bool IncrementalUpdate) {
445 for (
auto *InstrPtr : InsInstrs)
448 for (
auto *InstrPtr : DelInstrs) {
449 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
451 for (
auto I = RegUnits.
begin();
I != RegUnits.
end(); ) {
452 if (
I->MI == InstrPtr)
459 if (IncrementalUpdate)
460 for (
auto *InstrPtr : InsInstrs)
470 void MachineCombiner::verifyPatternOrder(
474 (void)PrevLatencyDiff;
475 for (
auto P : Patterns) {
479 TII->genAlternativeCodeSequence(Root,
P, InsInstrs, DelInstrs,
484 if (InsInstrs.
empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
487 unsigned NewRootLatency, RootLatency;
488 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
489 Root, InsInstrs, DelInstrs, MinInstr->getTrace(MBB));
490 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
491 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
492 "Current pattern is better than previous pattern.");
493 PrevLatencyDiff = CurrentLatencyDiff;
505 bool Changed =
false;
508 bool IncrementalUpdate =
false;
509 auto BlockIter = MBB->
begin();
510 decltype(BlockIter) LastUpdate;
521 while (BlockIter != MBB->
end()) {
522 auto &MI = *BlockIter++;
551 if (!
TII->getMachineCombinerPatterns(MI, Patterns))
555 verifyPatternOrder(MBB, MI, Patterns);
557 for (
auto P : Patterns) {
561 TII->genAlternativeCodeSequence(MI,
P, InsInstrs, DelInstrs,
563 unsigned NewInstCount = InsInstrs.
size();
564 unsigned OldInstCount = DelInstrs.
size();
572 dbgs() <<
"\tFor the Pattern (" << (int)
P 573 <<
") these instructions could be removed\n";
574 for (
auto const *InstrPtr : DelInstrs)
575 InstrPtr->print(
dbgs(),
false,
false,
577 dbgs() <<
"\tThese instructions could replace the removed ones\n";
578 for (
auto const *InstrPtr : InsInstrs)
579 InstrPtr->print(
dbgs(),
false,
false,
583 bool SubstituteAlways =
false;
584 if (ML &&
TII->isThroughputPattern(
P))
585 SubstituteAlways =
true;
587 if (IncrementalUpdate) {
589 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
590 LastUpdate = BlockIter;
597 if (SubstituteAlways ||
598 doSubstitute(NewInstCount, OldInstCount, OptForSize)) {
600 RegUnits, IncrementalUpdate);
611 Traces->verifyAnalysis();
612 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
613 InstrIdxForVirtReg,
P,
614 !IncrementalUpdate) &&
615 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
618 IncrementalUpdate =
true;
619 LastUpdate = BlockIter;
623 RegUnits, IncrementalUpdate);
632 for (
auto *InstrPtr : InsInstrs)
635 InstrIdxForVirtReg.
clear();
639 if (Changed && IncrementalUpdate)
640 Traces->invalidate(MBB);
646 TII = STI->getInstrInfo();
647 TRI = STI->getRegisterInfo();
648 SchedModel = STI->getSchedModel();
649 TSchedModel.init(STI);
651 MLI = &getAnalysis<MachineLoopInfo>();
652 Traces = &getAnalysis<MachineTraceMetrics>();
653 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
654 MBFI = (PSI && PSI->hasProfileSummary()) ?
655 &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
661 if (!
TII->useMachineCombiner()) {
664 <<
" Skipping pass: Target does not support machine combiner\n");
668 bool Changed =
false;
672 Changed |= combineInstructions(&MBB);
char & MachineCombinerID
This pass performs instruction combining using trace metrics to estimate critical-path and resource d...
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...
void push_back(const T &Elt)
Analysis providing profile information.
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...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A trace ensemble is a collection of traces selected using the same strategy, for example 'minimum res...
iterator_range< mop_iterator > operands()
void updateDepth(TraceBlockInfo &TBI, const MachineInstr &, SparseSet< LiveRegUnit > &RegUnits)
Updates the depth of an machine instruction, given RegUnits.
#define INITIALIZE_PASS_DEPENDENCY(depName)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
The core instruction combiner logic.
Select the trace through a block that has the fewest instructions.
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
COFF::MachineTypes Machine
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Gets latency information for Inst, based on DC information.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
TargetInstrInfo - Interface to description of machine instruction set.
static CombinerObjective getCombinerObjective(MachineCombinerPattern P)
static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI, SmallVector< MachineInstr *, 16 > InsInstrs, SmallVector< MachineInstr *, 16 > DelInstrs, MachineTraceMetrics::Ensemble *MinInstr, SparseSet< LiveRegUnit > &RegUnits, bool IncrementalUpdate)
Inserts InsInstrs and deletes DelInstrs.
iterator find(const_arg_type_t< KeyT > Val)
void invalidate(const MachineBasicBlock *MBB)
Invalidate traces through BadMBB.
initializer< Ty > init(const Ty &Val)
static cl::opt< bool > dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden, cl::desc("Dump all substituted intrs"), cl::init(false))
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Summarize the scheduling resources required for an instruction of a particular scheduling class...
This is an alternative analysis pass to MachineBlockFrequencyInfo.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
Represent the analysis usage information of a pass.
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
MachineCombinerPattern
These are instruction patterns matched by the machine combiner pass.
void DeleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A trace represents a plausible sequence of executed basic blocks that passes through the current basi...
const_iterator end() const
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Align max(MaybeAlign Lhs, Align Rhs)
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static unsigned getDepth(const SmallVectorImpl< const MachineBasicBlock *> &Stack, const MachineBasicBlock *MBB)
const_iterator begin() const
CHAIN = SC CHAIN, Imm128 - System call.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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))
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...
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...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
SparseSet - Fast set implmentation for objects that can be identified by small unsigned keys...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner", false, false) INITIALIZE_PASS_END(MachineCombiner
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned getResourceLength(ArrayRef< const MachineBasicBlock *> Extrablocks=None, ArrayRef< const MCSchedClassDesc *> ExtraInstrs=None, ArrayRef< const MCSchedClassDesc *> RemoveInstrs=None) const
Return the resource length of the trace.
void initializeMachineCombinerPass(PassRegistry &)
StringRef - Represent a constant reference to a string, i.e.
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...
Register getReg() const
getReg - Returns the register number.
unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
Machine model for scheduling, bundling, and heuristics.
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))
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...