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");
89class X86CmovConversionImpl {
96 MachineRegisterInfo *MRI =
nullptr;
97 const TargetInstrInfo *TII =
nullptr;
98 const X86Subtarget *STI =
nullptr;
99 MachineLoopInfo *MLI =
nullptr;
100 TargetSchedModel TSchedModel;
103 using CmovGroup = SmallVector<MachineInstr *, 2>;
104 using CmovGroups = SmallVector<CmovGroup, 2>;
113 CmovGroups &CmovInstGroups,
114 bool IncludeLoads =
false);
123 CmovGroups &CmovInstGroups);
128 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group)
const;
133 X86CmovConversionLegacy() : MachineFunctionPass(ID) {}
135 StringRef getPassName()
const override {
return "X86 cmov Conversion"; }
137 void getAnalysisUsage(AnalysisUsage &AU)
const override;
145char X86CmovConversionLegacy::ID = 0;
147void X86CmovConversionLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
155 const X86Options &CLOpts = STI->
getCLOpts();
156 if (!CLOpts.cmov_converter)
169 TSchedModel.
init(STI);
177 if (CLOpts.cmov_converter_force_mem_operand ||
178 CLOpts.cmov_converter_force_all) {
179 CmovGroups AllCmovGroups;
181 if (collectCmovCandidates(Blocks, AllCmovGroups,
true)) {
182 for (
auto &Group : AllCmovGroups) {
184 if (CLOpts.cmov_converter_force_mem_operand &&
185 !CLOpts.cmov_converter_force_all &&
186 llvm::none_of(Group, [&](MachineInstr *
I) { return I->mayLoad(); }))
193 convertCmovInstsToBranches(Group);
197 if (CLOpts.cmov_converter_force_all)
228 for (
int i = 0; i < (int)
Loops.size(); ++i)
231 for (MachineLoop *CurrLoop :
Loops) {
233 if (!CurrLoop->getSubLoops().empty())
237 CmovGroups CmovInstGroups;
239 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
242 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
247 for (
auto &Group : CmovInstGroups)
248 convertCmovInstsToBranches(Group);
254bool X86CmovConversionImpl::collectCmovCandidates(
278 for (
auto *
MBB : Blocks) {
285 bool FoundNonCMOVInst =
false;
287 bool SkipGroup =
false;
289 for (
auto &
I : *
MBB) {
291 if (
I.isDebugInstr())
298 !
I.getFlag(MachineInstr::MIFlag::Unpredictable) &&
299 (IncludeLoads || !
I.mayLoad()) && !
I.hasOrderedMemoryRef()) {
306 FoundNonCMOVInst =
false;
312 if (FoundNonCMOVInst || (
CC != FirstCC &&
CC != FirstOppCC))
319 else if (
CC != MemOpCC)
327 [&](MachineInstr &UseI) {
328 return UseI.getOpcode() == X86::SUBREG_TO_REG;
340 FoundNonCMOVInst =
true;
343 if (
I.definesRegister(X86::EFLAGS,
nullptr)) {
347 CmovInstGroups.push_back(Group);
349 ++NumOfSkippedCmovGroups;
358 CmovInstGroups.push_back(Group);
360 ++NumOfSkippedCmovGroups;
363 NumOfCmovGroupCandidate += CmovInstGroups.
size();
364 return !CmovInstGroups.empty();
376 divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
377 divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
380bool X86CmovConversionImpl::checkForProfitableCmovCandidates(
389 static const unsigned LoopIterations = 2;
390 DenseMap<MachineInstr *, DepthInfo> DepthMap;
391 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
392 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
394 DenseMap<Register, MachineInstr *> RegDefMaps[RegTypeNum];
397 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
400 DepthMap[
nullptr] = {0, 0};
402 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
403 for (
auto &Group : CmovInstGroups)
429 for (DepthInfo &MaxDepth : LoopDepth) {
430 for (
auto *
MBB : Blocks) {
432 RegDefMaps[PhyRegType].
clear();
433 for (MachineInstr &
MI : *
MBB) {
435 if (
MI.isDebugInstr())
437 unsigned MIDepth = 0;
438 unsigned MIDepthOpt = 0;
439 bool IsCMOV = CmovInstructions.
count(&
MI);
440 for (
auto &MO :
MI.uses()) {
442 if (!MO.isReg() || !MO.isUse())
446 if (MachineInstr *
DefMI = RDM.lookup(
Reg)) {
447 OperandToDefMap[&MO] =
DefMI;
449 MIDepth = std::max(MIDepth,
Info.Depth);
451 MIDepthOpt = std::max(MIDepthOpt,
Info.OptDepth);
457 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(1))].OptDepth,
458 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(2))].OptDepth);
461 for (
auto &MO :
MI.operands()) {
462 if (!MO.isReg() || !MO.isDef())
468 unsigned Latency = TSchedModel.computeInstrLatency(&
MI);
470 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
471 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
476 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
477 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
507 if (Diff[1] < STI->
getCLOpts().cmov_converter_threshold)
510 bool WorthOptLoop =
false;
511 if (Diff[1] == Diff[0])
512 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
513 else if (Diff[1] > Diff[0])
515 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].
Depth - LoopDepth[0].
Depth) &&
516 (Diff[1] * 8 >= LoopDepth[1].Depth);
521 ++NumOfLoopCandidate;
534 unsigned MispredictPenalty = STI->getMispredictionPenalty();
535 CmovGroups TempGroups;
537 for (
auto &Group : TempGroups) {
538 bool WorthOpGroup =
true;
539 for (
auto *
MI : Group) {
545 unsigned Op = UIs.begin()->getOpcode();
546 if (
Op == X86::MOV64rm ||
Op == X86::MOV32rm) {
547 WorthOpGroup =
false;
553 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(4))].Depth;
555 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(1))].Depth,
556 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(2))].Depth);
557 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
558 WorthOpGroup =
false;
564 CmovInstGroups.push_back(Group);
567 return !CmovInstGroups.empty();
571 if (
MI->killsRegister(X86::EFLAGS,
nullptr))
580 for (
auto I = std::next(ItrMI),
E = BB->
end();
I !=
E; ++
I) {
581 if (
I->readsRegister(X86::EFLAGS,
nullptr))
583 if (
I->definesRegister(X86::EFLAGS,
nullptr))
589 if (Succ->isLiveIn(X86::EFLAGS))
601 "Last instruction in a CMOV group must be a CMOV instruction");
604 for (
auto I =
First->getIterator(),
E =
Last->getIterator();
I !=
E;
I++) {
605 if (
I->isDebugInstr())
611 for (
auto *
MI : DBGInstructions)
612 MBB->insertAfter(
Last,
MI->removeFromParent());
615void X86CmovConversionImpl::convertCmovInstsToBranches(
616 SmallVectorImpl<MachineInstr *> &Group)
const {
617 assert(!Group.
empty() &&
"No CMOV instructions to convert");
618 ++NumOfOptimizedCmovGroups;
654 MachineInstr &
MI = *Group.
front();
655 MachineInstr *LastCMOV = Group.
back();
674 MachineBasicBlock *FalseMBB =
F->CreateMachineBasicBlock(BB);
675 MachineBasicBlock *SinkMBB =
F->CreateMachineBasicBlock(BB);
676 F->insert(It, FalseMBB);
677 F->insert(It, SinkMBB);
701 MachineInstrBuilder MIB;
712 DenseMap<Register, Register> FalseBBRegRewriteTable;
722 auto FRIt = FalseBBRegRewriteTable.
find(FalseReg);
723 if (FRIt == FalseBBRegRewriteTable.
end())
725 FalseReg = FRIt->second;
727 FalseBBRegRewriteTable[
MI.getOperand(0).getReg()] = FalseReg;
735 "Can only handle memory-operand cmov instructions with a condition "
736 "opposite to the selected branch direction.");
764 unsigned OldDebugInstrNum =
MI.peekDebugInstrNum();
765 SmallVector<MachineInstr *, 4> NewMIs;
770 assert(Unfolded &&
"Should never fail to unfold a loading cmov!");
776 "Last new instruction isn't the expected CMOV!");
779 if (&*MIItBegin == &
MI)
782 if (OldDebugInstrNum)
783 NewCMOV->setDebugInstrNum(OldDebugInstrNum);
787 for (
auto *NewMI : NewMIs) {
789 FalseMBB->
insert(FalseInsertionPoint, NewMI);
791 for (
auto &MOp : NewMI->uses()) {
794 auto It = FalseBBRegRewriteTable.
find(MOp.getReg());
795 if (It == FalseBBRegRewriteTable.
end())
798 MOp.setReg(It->second);
804 MOp.setIsKill(
false);
810 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
819 DenseMap<Register, std::pair<Register, Register>> RegRewriteTable;
822 Register DestReg = MIIt->getOperand(0).getReg();
823 Register Op1Reg = MIIt->getOperand(1).getReg();
824 Register 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)
854 if (
unsigned InstrNum = MIIt->peekDebugInstrNum())
858 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
863 if (MIItBegin != MIItEnd)
864 F->getProperties().resetNoPHIs();
871 L->addBasicBlockToLoop(FalseMBB, *MLI);
872 L->addBasicBlockToLoop(SinkMBB, *MLI);
877 "X86 cmov Conversion",
false,
false)
883 return new X86CmovConversionLegacy();
886bool X86CmovConversionLegacy::runOnMachineFunction(
MachineFunction &MF) {
889 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
890 X86CmovConversionImpl Impl(MLI);
891 return Impl.runOnMachineFunction(MF);
898 X86CmovConversionImpl Impl(MLI);
899 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
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)
MachineRegisterInfo & MRI
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 bool checkEFLAGSLive(MachineInstr *MI)
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth)
static void packCmovGroup(MachineInstr *First, MachineInstr *Last)
Given /p First CMOV instruction and /p Last CMOV instruction representing a group of CMOV instruction...
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.
iterator find(const_arg_type_t< KeyT > Val)
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.
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 TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
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.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
const X86Options & getCLOpts() const
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)
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...
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
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
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
bool DisableSelectOptimize