77 #define DEBUG_TYPE "x86-cmov-conversion" 79 STATISTIC(NumOfSkippedCmovGroups,
"Number of unsupported CMOV-groups");
80 STATISTIC(NumOfCmovGroupCandidate,
"Number of CMOV-group candidates");
81 STATISTIC(NumOfLoopCandidate,
"Number of CMOV-conversion profitable loops");
82 STATISTIC(NumOfOptimizedCmovGroups,
"Number of optimized CMOV-groups");
93 cl::desc(
"Enable the X86 cmov-to-branch optimization."),
98 cl::desc(
"Minimum gain per loop (in cycles) threshold."),
102 "x86-cmov-converter-force-mem-operand",
103 cl::desc(
"Convert cmovs to branches whenever they have memory operands."),
115 StringRef getPassName()
const override {
return "X86 cmov Conversion"; }
139 CmovGroups &CmovInstGroups,
140 bool IncludeLoads =
false);
149 CmovGroups &CmovInstGroups);
161 void X86CmovConverterPass::getAnalysisUsage(
AnalysisUsage &AU)
const {
175 bool Changed =
false;
179 TII = STI.getInstrInfo();
180 TRI = STI.getRegisterInfo();
181 TSchedModel.init(&STI);
189 CmovGroups AllCmovGroups;
193 if (collectCmovCandidates(Blocks, AllCmovGroups,
true)) {
194 for (
auto &Group : AllCmovGroups) {
203 convertCmovInstsToBranches(Group);
235 for (
int i = 0; i < (int)
Loops.size(); ++i)
237 Loops.push_back(Child);
241 if (!CurrLoop->getSubLoops().empty())
245 CmovGroups CmovInstGroups;
247 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
250 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
255 for (
auto &Group : CmovInstGroups)
256 convertCmovInstsToBranches(Group);
262 bool X86CmovConverterPass::collectCmovCandidates(
286 for (
auto *MBB : Blocks) {
292 bool FoundNonCMOVInst =
false;
294 bool SkipGroup =
false;
296 for (
auto &
I : *MBB) {
298 if (
I.isDebugInstr())
309 FoundNonCMOVInst =
false;
315 if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
322 else if (CC != MemOpCC)
329 MRI->use_nodbg_instructions(
I.defs().begin()->getReg()),
331 return UseI.
getOpcode() == X86::SUBREG_TO_REG;
343 FoundNonCMOVInst =
true;
346 if (
I.definesRegister(X86::EFLAGS)) {
350 CmovInstGroups.push_back(Group);
352 ++NumOfSkippedCmovGroups;
361 CmovInstGroups.push_back(Group);
363 ++NumOfSkippedCmovGroups;
366 NumOfCmovGroupCandidate += CmovInstGroups.size();
367 return !CmovInstGroups.empty();
379 return (TrueOpDepth + FalseOpDepth + 1) / 2;
382 bool X86CmovConverterPass::checkForProfitableCmovCandidates(
391 static const unsigned LoopIterations = 2;
393 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
394 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
402 DepthMap[
nullptr] = {0, 0};
405 for (
auto &Group : CmovInstGroups)
406 CmovInstructions.
insert(Group.begin(), Group.end());
431 for (
unsigned I = 0;
I < LoopIterations; ++
I) {
433 for (
auto *MBB : Blocks) {
435 RegDefMaps[PhyRegType].
clear();
438 if (
MI.isDebugInstr())
440 unsigned MIDepth = 0;
441 unsigned MIDepthOpt = 0;
442 bool IsCMOV = CmovInstructions.
count(&
MI);
443 for (
auto &MO :
MI.uses()) {
445 if (!MO.isReg() || !MO.isUse())
447 unsigned Reg = MO.getReg();
450 OperandToDefMap[&MO] =
DefMI;
452 MIDepth =
std::max(MIDepth, Info.Depth);
454 MIDepthOpt =
std::max(MIDepthOpt, Info.OptDepth);
460 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(1))].OptDepth,
461 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(2))].OptDepth);
464 for (
auto &MO :
MI.operands()) {
465 if (!MO.isReg() || !MO.isDef())
467 unsigned Reg = MO.getReg();
471 unsigned Latency = TSchedModel.computeInstrLatency(&
MI);
472 DepthMap[&
MI] = {MIDepth +=
Latency, MIDepthOpt += Latency};
473 MaxDepth.Depth =
std::max(MaxDepth.Depth, MIDepth);
474 MaxDepth.OptDepth =
std::max(MaxDepth.OptDepth, MIDepthOpt);
479 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
480 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
512 bool WorthOptLoop =
false;
513 if (Diff[1] == Diff[0])
514 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
515 else if (Diff[1] > Diff[0])
517 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].
Depth - LoopDepth[0].
Depth) &&
518 (Diff[1] * 8 >= LoopDepth[1].Depth);
523 ++NumOfLoopCandidate;
536 unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
537 CmovGroups TempGroups;
539 for (
auto &Group : TempGroups) {
540 bool WorthOpGroup =
true;
541 for (
auto *
MI : Group) {
545 auto UIs =
MRI->use_instructions(
MI->defs().begin()->getReg());
546 if (UIs.begin() != UIs.end() && ++UIs.begin() == UIs.end()) {
547 unsigned Op = UIs.begin()->getOpcode();
548 if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
549 WorthOpGroup =
false;
555 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(3))].Depth;
557 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(1))].Depth,
558 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(2))].Depth);
559 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
560 WorthOpGroup =
false;
566 CmovInstGroups.push_back(Group);
569 return !CmovInstGroups.empty();
582 for (
auto I = std::next(ItrMI),
E = BB->
end();
I !=
E; ++
I) {
583 if (
I->readsRegister(X86::EFLAGS))
585 if (
I->definesRegister(X86::EFLAGS))
591 if ((*I)->isLiveIn(X86::EFLAGS))
604 "Last instruction in a CMOV group must be a CMOV instruction");
608 if (
I->isDebugInstr())
614 for (
auto *
MI : DBGInstructions)
618 void X86CmovConverterPass::convertCmovInstsToBranches(
620 assert(!Group.
empty() &&
"No CMOV instructions to convert");
621 ++NumOfOptimizedCmovGroups;
726 auto FRIt = FalseBBRegRewriteTable.
find(FalseReg);
727 if (FRIt == FalseBBRegRewriteTable.
end())
729 FalseReg = FRIt->second;
731 FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
739 "Can only handle memory-operand cmov instructions with a condition " 740 "opposite to the selected branch direction.");
765 unsigned TmpReg =
MRI->createVirtualRegister(RC);
768 bool Unfolded =
TII->unfoldMemoryOperand(*MBB->
getParent(),
MI, TmpReg,
772 assert(Unfolded &&
"Should never fail to unfold a loading cmov!");
778 "Last new instruction isn't the expected CMOV!");
781 if (&*MIItBegin == &MI)
786 for (
auto *NewMI : NewMIs) {
788 FalseMBB->
insert(FalseInsertionPoint, NewMI);
790 for (
auto &MOp : NewMI->uses()) {
793 auto It = FalseBBRegRewriteTable.
find(MOp.getReg());
794 if (It == FalseBBRegRewriteTable.
end())
797 MOp.setReg(It->second);
803 MOp.setIsKill(
false);
810 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
822 unsigned DestReg = MIIt->getOperand(0).getReg();
823 unsigned Op1Reg = MIIt->getOperand(1).getReg();
824 unsigned Op2Reg = MIIt->getOperand(2).getReg();
832 auto Op1Itr = RegRewriteTable.
find(Op1Reg);
833 if (Op1Itr != RegRewriteTable.
end())
834 Op1Reg = Op1Itr->second.first;
836 auto Op2Itr = RegRewriteTable.
find(Op2Reg);
837 if (Op2Itr != RegRewriteTable.
end())
838 Op2Reg = Op2Itr->second.second;
843 MIB =
BuildMI(*SinkMBB, SinkInsertionPoint, DL,
TII->get(X86::PHI), DestReg)
853 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
857 MBB->
erase(MIItBegin, MIItEnd);
867 return new X86CmovConverterPass();
unsigned GetCondBranchFromCond(CondCode CC)
void push_back(const T &Elt)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Compute iterated dominance frontiers using a linear time algorithm.
static void packCmovGroup(MachineInstr *First, MachineInstr *Last)
Given /p First CMOV instruction and /p Last CMOV instruction representing a group of CMOV instruction...
CondCode getCondFromCMovOpc(unsigned Opc)
Return condition code of a CMov opcode.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void initializeX86CmovConverterPassPass(PassRegistry &)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
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
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth)
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
static bool checkEFLAGSLive(MachineInstr *MI)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
static cl::opt< bool > EnableCmovConverter("x86-cmov-converter", cl::desc("Enable the X86 cmov-to-branch optimization."), cl::init(true), cl::Hidden)
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
MachineInstrBundleIterator< MachineInstr > iterator
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
LLVM Basic Block Representation.
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.
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 GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static cl::opt< unsigned > GainCycleThreshold("x86-cmov-converter-threshold", cl::desc("Minimum gain per loop (in cycles) threshold."), cl::init(4), cl::Hidden)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
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 class - This class is used to implement most global optimizations.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
succ_iterator succ_begin()
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass * createX86CmovConverterPass()
This pass converts X86 cmov instructions into branch when profitable.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
MachineInstrBuilder MachineInstrBuilder & DefMI
LLVM_NODISCARD T pop_back_val()
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const MachineBasicBlock * getParent() const
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.
bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr kills the specified register.
INITIALIZE_PASS_BEGIN(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion", false, false) INITIALIZE_PASS_END(X86CmovConverterPass
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 '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
StringRef - Represent a constant reference to a string, i.e.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const