56 #define DEBUG_TYPE "x86-cmov-converter"
58 STATISTIC(NumOfSkippedCmovGroups,
"Number of unsupported CMOV-groups");
59 STATISTIC(NumOfCmovGroupCandidate,
"Number of CMOV-group candidates");
60 STATISTIC(NumOfLoopCandidate,
"Number of CMOV-conversion profitable loops");
61 STATISTIC(NumOfOptimizedCmovGroups,
"Number of optimized CMOV-groups");
66 EnableCmovConverter(
"x86-cmov-converter",
67 cl::desc(
"Enable the X86 cmov-to-branch optimization."),
74 ~X86CmovConverterPass() {}
76 StringRef getPassName()
const override {
return "X86 cmov Conversion"; }
98 bool collectCmovCandidates(
MachineLoop *CurrLoop, CmovGroups &CmovInstGroups);
106 bool checkForProfitableCmovCandidates(
MachineLoop *CurrLoop,
107 CmovGroups &CmovInstGroups);
117 void X86CmovConverterPass::getAnalysisUsage(
AnalysisUsage &AU)
const {
125 if (!EnableCmovConverter)
131 bool Changed =
false;
135 TII = STI.getInstrInfo();
136 TSchedModel.init(STI.getSchedModel(), &STI,
TII);
164 if (!CurrLoop || CurrLoop->
getHeader() != &MBB ||
169 CmovGroups CmovInstGroups;
171 if (!collectCmovCandidates(CurrLoop, CmovInstGroups))
174 if (!checkForProfitableCmovCandidates(CurrLoop, CmovInstGroups))
178 for (
auto &Group : CmovInstGroups)
179 convertCmovInstsToBranches(Group);
184 bool X86CmovConverterPass::collectCmovCandidates(
MachineLoop *CurrLoop,
185 CmovGroups &CmovInstGroups) {
207 for (
auto *MBB : CurrLoop->
getBlocks()) {
213 bool FoundNonCMOVInst =
false;
215 bool SkipGroup =
false;
217 for (
auto &
I : *MBB) {
225 FoundNonCMOVInst =
false;
231 if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
241 FoundNonCMOVInst =
true;
244 if (
I.definesRegister(X86::EFLAGS)) {
248 CmovInstGroups.push_back(Group);
250 ++NumOfSkippedCmovGroups;
259 CmovInstGroups.push_back(Group);
261 ++NumOfSkippedCmovGroups;
264 NumOfCmovGroupCandidate += CmovInstGroups.size();
265 return !CmovInstGroups.empty();
271 static unsigned getDepthOfOptCmov(
unsigned TrueOpDepth,
unsigned FalseOpDepth) {
277 return (TrueOpDepth + FalseOpDepth + 1) / 2;
280 bool X86CmovConverterPass::checkForProfitableCmovCandidates(
281 MachineLoop *CurrLoop, CmovGroups &CmovInstGroups) {
289 static const unsigned LoopIterations = 2;
291 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
292 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
300 DepthMap[
nullptr] = {0, 0};
303 for (
auto &Group : CmovInstGroups)
304 CmovInstructions.
insert(Group.begin(), Group.end());
329 for (
unsigned I = 0;
I < LoopIterations; ++
I) {
331 for (
auto *MBB : CurrLoop->
getBlocks()) {
333 RegDefMaps[PhyRegType].
clear();
335 unsigned MIDepth = 0;
336 unsigned MIDepthOpt = 0;
337 bool IsCMOV = CmovInstructions.
count(&
MI);
338 for (
auto &MO :
MI.uses()) {
340 if (!MO.isReg() || !MO.isUse())
342 unsigned Reg = MO.getReg();
345 OperandToDefMap[&MO] = DefMI;
346 DepthInfo Info = DepthMap.
lookup(DefMI);
347 MIDepth =
std::max(MIDepth, Info.Depth);
349 MIDepthOpt =
std::max(MIDepthOpt, Info.OptDepth);
354 MIDepthOpt = getDepthOfOptCmov(
355 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(1))].OptDepth,
356 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(2))].OptDepth);
359 for (
auto &MO :
MI.operands()) {
360 if (!MO.isReg() || !MO.isDef())
362 unsigned Reg = MO.getReg();
366 unsigned Latency = TSchedModel.computeInstrLatency(&
MI);
367 DepthMap[&
MI] = {MIDepth +=
Latency, MIDepthOpt += Latency};
368 MaxDepth.Depth =
std::max(MaxDepth.Depth, MIDepth);
369 MaxDepth.OptDepth =
std::max(MaxDepth.OptDepth, MIDepthOpt);
374 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
375 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
399 bool WorthOptLoop =
false;
400 if (Diff[1] == Diff[0])
401 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
402 else if (Diff[1] > Diff[0])
404 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].
Depth - LoopDepth[0].
Depth);
409 ++NumOfLoopCandidate;
422 unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
423 CmovGroups TempGroups;
425 for (
auto &Group : TempGroups) {
426 bool WorthOpGroup =
true;
427 for (
auto *
MI : Group) {
431 auto UIs =
MRI->use_instructions(
MI->defs().begin()->getReg());
432 if (UIs.begin() != UIs.end() && ++UIs.begin() == UIs.end()) {
433 unsigned Op = UIs.begin()->getOpcode();
434 if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
435 WorthOpGroup =
false;
441 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(3))].Depth;
442 unsigned ValCost = getDepthOfOptCmov(
443 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(1))].Depth,
444 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(2))].Depth);
445 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
446 WorthOpGroup =
false;
452 CmovInstGroups.push_back(Group);
455 return !CmovInstGroups.empty();
468 for (
auto I = std::next(ItrMI),
E = BB->
end();
I !=
E; ++
I) {
469 if (
I->readsRegister(X86::EFLAGS))
471 if (
I->definesRegister(X86::EFLAGS))
477 if ((*I)->isLiveIn(X86::EFLAGS))
484 void X86CmovConverterPass::convertCmovInstsToBranches(
486 assert(!Group.
empty() &&
"No CMOV instructions to convert");
487 ++NumOfOptimizedCmovGroups;
535 if (checkEFLAGSLive(LastCMOV)) {
569 unsigned DestReg = MIIt->getOperand(0).getReg();
570 unsigned Op1Reg = MIIt->getOperand(1).getReg();
571 unsigned Op2Reg = MIIt->getOperand(2).getReg();
579 auto Op1Itr = RegRewriteTable.
find(Op1Reg);
580 if (Op1Itr != RegRewriteTable.
end())
581 Op1Reg = Op1Itr->second.first;
583 auto Op2Itr = RegRewriteTable.
find(Op2Reg);
584 if (Op2Itr != RegRewriteTable.
end())
585 Op2Reg = Op2Itr->second.second;
590 MIB =
BuildMI(*SinkMBB, SinkInsertionPoint, DL,
TII->get(X86::PHI), DestReg)
596 DEBUG(
dbgs() <<
"\tFrom: "; MIIt->dump());
600 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
604 MBB->
erase(MIItBegin, MIItEnd);
610 return new X86CmovConverterPass();
unsigned GetCondBranchFromCond(CondCode CC)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
STATISTIC(NumFunctions,"Total number of functions")
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...
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
AnalysisUsage & addRequired()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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
FunctionPass * createX86CmovConverterPass()
This pass converts X86 cmov instructions into branch when profitable.
Reg
All possible values of the reg field in the ModR/M byte.
LLVM_NODISCARD bool empty() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
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.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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.
FunctionPass class - This class is used to implement most global optimizations.
self_iterator getIterator()
succ_iterator succ_begin()
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.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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 DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
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.
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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr kills the specified register.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
StringRef - Represent a constant reference to a string, i.e.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.