79#define DEBUG_TYPE "x86-cmov-conversion"
81STATISTIC(NumOfSkippedCmovGroups,
"Number of unsupported CMOV-groups");
82STATISTIC(NumOfCmovGroupCandidate,
"Number of CMOV-group candidates");
83STATISTIC(NumOfLoopCandidate,
"Number of CMOV-conversion profitable loops");
84STATISTIC(NumOfOptimizedCmovGroups,
"Number of optimized CMOV-groups");
89 cl::desc(
"Enable the X86 cmov-to-branch optimization."),
94 cl::desc(
"Minimum gain per loop (in cycles) threshold."),
98 "x86-cmov-converter-force-mem-operand",
99 cl::desc(
"Convert cmovs to branches whenever they have memory operands."),
103 "x86-cmov-converter-force-all",
104 cl::desc(
"Convert all cmovs to branches."),
110class X86CmovConversionImpl {
114 bool runOnMachineFunction(MachineFunction &MF);
117 MachineRegisterInfo *MRI =
nullptr;
118 const TargetInstrInfo *TII =
nullptr;
119 const TargetRegisterInfo *TRI =
nullptr;
120 const TargetSubtargetInfo *STI =
nullptr;
121 MachineLoopInfo *MLI =
nullptr;
122 TargetSchedModel TSchedModel;
125 using CmovGroup = SmallVector<MachineInstr *, 2>;
126 using CmovGroups = SmallVector<CmovGroup, 2>;
135 CmovGroups &CmovInstGroups,
136 bool IncludeLoads =
false);
145 CmovGroups &CmovInstGroups);
150 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group)
const;
155 X86CmovConversionLegacy() : MachineFunctionPass(ID) {}
157 StringRef getPassName()
const override {
return "X86 cmov Conversion"; }
158 bool runOnMachineFunction(MachineFunction &MF)
override;
159 void getAnalysisUsage(AnalysisUsage &AU)
const override;
167char X86CmovConversionLegacy::ID = 0;
169void X86CmovConversionLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
175bool X86CmovConversionImpl::runOnMachineFunction(MachineFunction &MF) {
191 TSchedModel.
init(STI);
199 CmovGroups AllCmovGroups;
201 if (collectCmovCandidates(Blocks, AllCmovGroups,
true)) {
202 for (
auto &Group : AllCmovGroups) {
212 convertCmovInstsToBranches(Group);
247 for (
int i = 0; i < (int)
Loops.size(); ++i)
250 for (MachineLoop *CurrLoop :
Loops) {
252 if (!CurrLoop->getSubLoops().empty())
256 CmovGroups CmovInstGroups;
258 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
261 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
266 for (
auto &Group : CmovInstGroups)
267 convertCmovInstsToBranches(Group);
273bool X86CmovConversionImpl::collectCmovCandidates(
297 for (
auto *
MBB : Blocks) {
304 bool FoundNonCMOVInst =
false;
306 bool SkipGroup =
false;
308 for (
auto &
I : *
MBB) {
310 if (
I.isDebugInstr())
317 !
I.getFlag(MachineInstr::MIFlag::Unpredictable) &&
318 (IncludeLoads || !
I.mayLoad())) {
325 FoundNonCMOVInst =
false;
331 if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
338 else if (CC != MemOpCC)
346 [&](MachineInstr &UseI) {
347 return UseI.getOpcode() == X86::SUBREG_TO_REG;
359 FoundNonCMOVInst =
true;
362 if (
I.definesRegister(X86::EFLAGS,
nullptr)) {
366 CmovInstGroups.push_back(Group);
368 ++NumOfSkippedCmovGroups;
377 CmovInstGroups.push_back(Group);
379 ++NumOfSkippedCmovGroups;
382 NumOfCmovGroupCandidate += CmovInstGroups.
size();
383 return !CmovInstGroups.empty();
395 divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
396 divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
399bool X86CmovConversionImpl::checkForProfitableCmovCandidates(
408 static const unsigned LoopIterations = 2;
409 DenseMap<MachineInstr *, DepthInfo> DepthMap;
410 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
411 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
413 DenseMap<Register, MachineInstr *> RegDefMaps[RegTypeNum];
416 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
419 DepthMap[
nullptr] = {0, 0};
421 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
422 for (
auto &Group : CmovInstGroups)
448 for (DepthInfo &MaxDepth : LoopDepth) {
449 for (
auto *
MBB : Blocks) {
451 RegDefMaps[PhyRegType].
clear();
452 for (MachineInstr &
MI : *
MBB) {
454 if (
MI.isDebugInstr())
456 unsigned MIDepth = 0;
457 unsigned MIDepthOpt = 0;
458 bool IsCMOV = CmovInstructions.
count(&
MI);
459 for (
auto &MO :
MI.uses()) {
461 if (!MO.isReg() || !MO.isUse())
465 if (MachineInstr *
DefMI = RDM.lookup(
Reg)) {
466 OperandToDefMap[&MO] =
DefMI;
468 MIDepth = std::max(MIDepth,
Info.Depth);
470 MIDepthOpt = std::max(MIDepthOpt,
Info.OptDepth);
476 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(1))].OptDepth,
477 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(2))].OptDepth);
480 for (
auto &MO :
MI.operands()) {
481 if (!MO.isReg() || !MO.isDef())
487 unsigned Latency = TSchedModel.computeInstrLatency(&
MI);
489 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
490 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
495 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
496 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
528 bool WorthOptLoop =
false;
529 if (Diff[1] == Diff[0])
530 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
531 else if (Diff[1] > Diff[0])
533 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].
Depth - LoopDepth[0].
Depth) &&
534 (Diff[1] * 8 >= LoopDepth[1].Depth);
539 ++NumOfLoopCandidate;
553 CmovGroups TempGroups;
555 for (
auto &Group : TempGroups) {
556 bool WorthOpGroup =
true;
557 for (
auto *
MI : Group) {
563 unsigned Op = UIs.begin()->getOpcode();
564 if (
Op == X86::MOV64rm ||
Op == X86::MOV32rm) {
565 WorthOpGroup =
false;
571 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(4))].Depth;
573 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(1))].Depth,
574 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(2))].Depth);
575 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
576 WorthOpGroup =
false;
582 CmovInstGroups.push_back(Group);
585 return !CmovInstGroups.empty();
589 if (
MI->killsRegister(X86::EFLAGS,
nullptr))
598 for (
auto I = std::next(ItrMI),
E = BB->
end();
I !=
E; ++
I) {
599 if (
I->readsRegister(X86::EFLAGS,
nullptr))
601 if (
I->definesRegister(X86::EFLAGS,
nullptr))
607 if (Succ->isLiveIn(X86::EFLAGS))
619 "Last instruction in a CMOV group must be a CMOV instruction");
622 for (
auto I =
First->getIterator(),
E =
Last->getIterator();
I !=
E;
I++) {
623 if (
I->isDebugInstr())
629 for (
auto *
MI : DBGInstructions)
630 MBB->insertAfter(
Last,
MI->removeFromParent());
633void X86CmovConversionImpl::convertCmovInstsToBranches(
634 SmallVectorImpl<MachineInstr *> &Group)
const {
635 assert(!Group.
empty() &&
"No CMOV instructions to convert");
636 ++NumOfOptimizedCmovGroups;
672 MachineInstr &
MI = *Group.
front();
673 MachineInstr *LastCMOV = Group.
back();
687 MachineBasicBlock *
MBB =
MI.getParent();
692 MachineBasicBlock *FalseMBB =
F->CreateMachineBasicBlock(BB);
693 MachineBasicBlock *SinkMBB =
F->CreateMachineBasicBlock(BB);
694 F->insert(It, FalseMBB);
695 F->insert(It, SinkMBB);
719 MachineInstrBuilder MIB;
730 DenseMap<Register, Register> FalseBBRegRewriteTable;
740 auto FRIt = FalseBBRegRewriteTable.
find(FalseReg);
741 if (FRIt == FalseBBRegRewriteTable.
end())
743 FalseReg = FRIt->second;
745 FalseBBRegRewriteTable[
MI.getOperand(0).getReg()] = FalseReg;
753 "Can only handle memory-operand cmov instructions with a condition "
754 "opposite to the selected branch direction.");
782 unsigned OldDebugInstrNum =
MI.peekDebugInstrNum();
783 SmallVector<MachineInstr *, 4> NewMIs;
788 assert(Unfolded &&
"Should never fail to unfold a loading cmov!");
794 "Last new instruction isn't the expected CMOV!");
797 if (&*MIItBegin == &
MI)
800 if (OldDebugInstrNum)
801 NewCMOV->setDebugInstrNum(OldDebugInstrNum);
805 for (
auto *NewMI : NewMIs) {
807 FalseMBB->
insert(FalseInsertionPoint, NewMI);
809 for (
auto &MOp : NewMI->uses()) {
812 auto It = FalseBBRegRewriteTable.
find(MOp.getReg());
813 if (It == FalseBBRegRewriteTable.
end())
816 MOp.setReg(It->second);
822 MOp.setIsKill(
false);
828 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
837 DenseMap<Register, std::pair<Register, Register>> RegRewriteTable;
840 Register DestReg = MIIt->getOperand(0).getReg();
841 Register Op1Reg = MIIt->getOperand(1).getReg();
842 Register Op2Reg = MIIt->getOperand(2).getReg();
850 auto Op1Itr = RegRewriteTable.
find(Op1Reg);
851 if (Op1Itr != RegRewriteTable.
end())
852 Op1Reg = Op1Itr->second.first;
854 auto Op2Itr = RegRewriteTable.
find(Op2Reg);
855 if (Op2Itr != RegRewriteTable.
end())
856 Op2Reg = Op2Itr->second.second;
861 MIB =
BuildMI(*SinkMBB, SinkInsertionPoint,
DL,
TII->get(X86::PHI), DestReg)
872 if (
unsigned InstrNum = MIIt->peekDebugInstrNum())
876 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
881 if (MIItBegin != MIItEnd)
882 F->getProperties().resetNoPHIs();
889 L->addBasicBlockToLoop(FalseMBB, *MLI);
890 L->addBasicBlockToLoop(SinkMBB, *MLI);
895 "X86 cmov Conversion",
false,
false)
901 return new X86CmovConversionLegacy();
904bool X86CmovConversionLegacy::runOnMachineFunction(
MachineFunction &MF) {
907 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
908 X86CmovConversionImpl Impl(MLI);
909 return Impl.runOnMachineFunction(MF);
916 X86CmovConversionImpl Impl(MLI);
917 bool Changed = Impl.runOnMachineFunction(MF);
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static cl::opt< unsigned > GainCycleThreshold("select-opti-loop-cycle-gain-threshold", cl::desc("Minimum gain per loop (in cycles) threshold."), cl::init(4), cl::Hidden)
This file defines the SmallPtrSet 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)
static cl::opt< bool > DisableSelectOptimize("disable-select-optimize", cl::init(true), cl::Hidden, cl::desc("Disable the select-optimization pass from running"))
Disable the select optimization pass.
static cl::opt< bool > ForceAll("x86-cmov-converter-force-all", cl::desc("Convert all cmovs to branches."), cl::init(false), cl::Hidden)
static bool checkEFLAGSLive(MachineInstr *MI)
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth)
static cl::opt< unsigned > GainCycleThreshold("x86-cmov-converter-threshold", cl::desc("Minimum gain per loop (in cycles) threshold."), cl::init(4), cl::Hidden)
static cl::opt< bool > ForceMemOperand("x86-cmov-converter-force-mem-operand", cl::desc("Convert cmovs to branches whenever they have memory operands."), cl::init(true), cl::Hidden)
static void packCmovGroup(MachineInstr *First, MachineInstr *Last)
Given /p First CMOV instruction and /p Last CMOV instruction representing a group of CMOV instruction...
static cl::opt< bool > EnableCmovConverter("x86-cmov-converter", cl::desc("Enable the X86 cmov-to-branch optimization."), cl::init(true), cl::Hidden)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
FunctionPass class - This class is used to implement most global optimizations.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
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 instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
LLVM_ABI void dump() const
Analysis pass that exposes the MachineLoopInfo for a machine function.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual unsigned getMispredictionPenalty() const
Return the number of extra cycles the processor takes to recover from a branch misprediction.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
self_iterator getIterator()
@ BasicBlock
Various leaf nodes.
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
CondCode getCondFromCMov(const MachineInstr &MI)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
FunctionPass * createX86CmovConversionLegacyPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
MCRegisterClass TargetRegisterClass
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.