109467b48Spatrick //====- X86CmovConversion.cpp - Convert Cmov to Branch --------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick /// \file
1009467b48Spatrick /// This file implements a pass that converts X86 cmov instructions into
1109467b48Spatrick /// branches when profitable. This pass is conservative. It transforms if and
1209467b48Spatrick /// only if it can guarantee a gain with high confidence.
1309467b48Spatrick ///
1409467b48Spatrick /// Thus, the optimization applies under the following conditions:
1509467b48Spatrick /// 1. Consider as candidates only CMOVs in innermost loops (assume that
1609467b48Spatrick /// most hotspots are represented by these loops).
1709467b48Spatrick /// 2. Given a group of CMOV instructions that are using the same EFLAGS def
1809467b48Spatrick /// instruction:
1909467b48Spatrick /// a. Consider them as candidates only if all have the same code condition
2009467b48Spatrick /// or the opposite one to prevent generating more than one conditional
2109467b48Spatrick /// jump per EFLAGS def instruction.
2209467b48Spatrick /// b. Consider them as candidates only if all are profitable to be
2309467b48Spatrick /// converted (assume that one bad conversion may cause a degradation).
2409467b48Spatrick /// 3. Apply conversion only for loops that are found profitable and only for
2509467b48Spatrick /// CMOV candidates that were found profitable.
2609467b48Spatrick /// a. A loop is considered profitable only if conversion will reduce its
2709467b48Spatrick /// depth cost by some threshold.
2809467b48Spatrick /// b. CMOV is considered profitable if the cost of its condition is higher
2909467b48Spatrick /// than the average cost of its true-value and false-value by 25% of
3009467b48Spatrick /// branch-misprediction-penalty. This assures no degradation even with
3109467b48Spatrick /// 25% branch misprediction.
3209467b48Spatrick ///
3309467b48Spatrick /// Note: This pass is assumed to run on SSA machine code.
3409467b48Spatrick //
3509467b48Spatrick //===----------------------------------------------------------------------===//
3609467b48Spatrick //
3709467b48Spatrick // External interfaces:
3809467b48Spatrick // FunctionPass *llvm::createX86CmovConverterPass();
3909467b48Spatrick // bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
4009467b48Spatrick //
4109467b48Spatrick //===----------------------------------------------------------------------===//
4209467b48Spatrick
4309467b48Spatrick #include "X86.h"
4409467b48Spatrick #include "X86InstrInfo.h"
4509467b48Spatrick #include "llvm/ADT/ArrayRef.h"
4609467b48Spatrick #include "llvm/ADT/DenseMap.h"
4709467b48Spatrick #include "llvm/ADT/STLExtras.h"
4809467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
4909467b48Spatrick #include "llvm/ADT/SmallVector.h"
5009467b48Spatrick #include "llvm/ADT/Statistic.h"
5109467b48Spatrick #include "llvm/CodeGen/MachineBasicBlock.h"
5209467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
5309467b48Spatrick #include "llvm/CodeGen/MachineFunctionPass.h"
5409467b48Spatrick #include "llvm/CodeGen/MachineInstr.h"
5509467b48Spatrick #include "llvm/CodeGen/MachineInstrBuilder.h"
5609467b48Spatrick #include "llvm/CodeGen/MachineLoopInfo.h"
5709467b48Spatrick #include "llvm/CodeGen/MachineOperand.h"
5809467b48Spatrick #include "llvm/CodeGen/MachineRegisterInfo.h"
5909467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h"
6009467b48Spatrick #include "llvm/CodeGen/TargetRegisterInfo.h"
6109467b48Spatrick #include "llvm/CodeGen/TargetSchedule.h"
6209467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
6309467b48Spatrick #include "llvm/IR/DebugLoc.h"
6409467b48Spatrick #include "llvm/InitializePasses.h"
6509467b48Spatrick #include "llvm/MC/MCSchedule.h"
6609467b48Spatrick #include "llvm/Pass.h"
6709467b48Spatrick #include "llvm/Support/CommandLine.h"
6809467b48Spatrick #include "llvm/Support/Debug.h"
6909467b48Spatrick #include "llvm/Support/raw_ostream.h"
70*d415bd75Srobert #include "llvm/Target/CGPassBuilderOption.h"
7109467b48Spatrick #include <algorithm>
7209467b48Spatrick #include <cassert>
7309467b48Spatrick #include <iterator>
7409467b48Spatrick #include <utility>
7509467b48Spatrick
7609467b48Spatrick using namespace llvm;
7709467b48Spatrick
7809467b48Spatrick #define DEBUG_TYPE "x86-cmov-conversion"
7909467b48Spatrick
8009467b48Spatrick STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
8109467b48Spatrick STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
8209467b48Spatrick STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
8309467b48Spatrick STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
8409467b48Spatrick
8509467b48Spatrick // This internal switch can be used to turn off the cmov/branch optimization.
8609467b48Spatrick static cl::opt<bool>
8709467b48Spatrick EnableCmovConverter("x86-cmov-converter",
8809467b48Spatrick cl::desc("Enable the X86 cmov-to-branch optimization."),
8909467b48Spatrick cl::init(true), cl::Hidden);
9009467b48Spatrick
9109467b48Spatrick static cl::opt<unsigned>
9209467b48Spatrick GainCycleThreshold("x86-cmov-converter-threshold",
9309467b48Spatrick cl::desc("Minimum gain per loop (in cycles) threshold."),
9409467b48Spatrick cl::init(4), cl::Hidden);
9509467b48Spatrick
9609467b48Spatrick static cl::opt<bool> ForceMemOperand(
9709467b48Spatrick "x86-cmov-converter-force-mem-operand",
9809467b48Spatrick cl::desc("Convert cmovs to branches whenever they have memory operands."),
9909467b48Spatrick cl::init(true), cl::Hidden);
10009467b48Spatrick
101*d415bd75Srobert static cl::opt<bool> ForceAll(
102*d415bd75Srobert "x86-cmov-converter-force-all",
103*d415bd75Srobert cl::desc("Convert all cmovs to branches."),
104*d415bd75Srobert cl::init(false), cl::Hidden);
105*d415bd75Srobert
10609467b48Spatrick namespace {
10709467b48Spatrick
10809467b48Spatrick /// Converts X86 cmov instructions into branches when profitable.
10909467b48Spatrick class X86CmovConverterPass : public MachineFunctionPass {
11009467b48Spatrick public:
X86CmovConverterPass()11109467b48Spatrick X86CmovConverterPass() : MachineFunctionPass(ID) { }
11209467b48Spatrick
getPassName() const11309467b48Spatrick StringRef getPassName() const override { return "X86 cmov Conversion"; }
11409467b48Spatrick bool runOnMachineFunction(MachineFunction &MF) override;
11509467b48Spatrick void getAnalysisUsage(AnalysisUsage &AU) const override;
11609467b48Spatrick
11709467b48Spatrick /// Pass identification, replacement for typeid.
11809467b48Spatrick static char ID;
11909467b48Spatrick
12009467b48Spatrick private:
12109467b48Spatrick MachineRegisterInfo *MRI = nullptr;
12209467b48Spatrick const TargetInstrInfo *TII = nullptr;
12309467b48Spatrick const TargetRegisterInfo *TRI = nullptr;
12473471bf0Spatrick MachineLoopInfo *MLI = nullptr;
12509467b48Spatrick TargetSchedModel TSchedModel;
12609467b48Spatrick
12709467b48Spatrick /// List of consecutive CMOV instructions.
12809467b48Spatrick using CmovGroup = SmallVector<MachineInstr *, 2>;
12909467b48Spatrick using CmovGroups = SmallVector<CmovGroup, 2>;
13009467b48Spatrick
13109467b48Spatrick /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
13209467b48Spatrick /// CmovInstGroups accordingly.
13309467b48Spatrick ///
13409467b48Spatrick /// \param Blocks List of blocks to process.
13509467b48Spatrick /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
13609467b48Spatrick /// \returns true iff it found any CMOV-group-candidate.
13709467b48Spatrick bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
13809467b48Spatrick CmovGroups &CmovInstGroups,
13909467b48Spatrick bool IncludeLoads = false);
14009467b48Spatrick
14109467b48Spatrick /// Check if it is profitable to transform each CMOV-group-candidates into
14209467b48Spatrick /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
14309467b48Spatrick ///
14409467b48Spatrick /// \param Blocks List of blocks to process.
14509467b48Spatrick /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
14609467b48Spatrick /// \returns true iff any CMOV-group-candidate remain.
14709467b48Spatrick bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
14809467b48Spatrick CmovGroups &CmovInstGroups);
14909467b48Spatrick
15009467b48Spatrick /// Convert the given list of consecutive CMOV instructions into a branch.
15109467b48Spatrick ///
15209467b48Spatrick /// \param Group Consecutive CMOV instructions to be converted into branch.
15309467b48Spatrick void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
15409467b48Spatrick };
15509467b48Spatrick
15609467b48Spatrick } // end anonymous namespace
15709467b48Spatrick
15809467b48Spatrick char X86CmovConverterPass::ID = 0;
15909467b48Spatrick
getAnalysisUsage(AnalysisUsage & AU) const16009467b48Spatrick void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
16109467b48Spatrick MachineFunctionPass::getAnalysisUsage(AU);
16209467b48Spatrick AU.addRequired<MachineLoopInfo>();
16309467b48Spatrick }
16409467b48Spatrick
runOnMachineFunction(MachineFunction & MF)16509467b48Spatrick bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
16609467b48Spatrick if (skipFunction(MF.getFunction()))
16709467b48Spatrick return false;
16809467b48Spatrick if (!EnableCmovConverter)
16909467b48Spatrick return false;
17009467b48Spatrick
171*d415bd75Srobert // If the SelectOptimize pass is enabled, cmovs have already been optimized.
172*d415bd75Srobert if (!getCGPassBuilderOption().DisableSelectOptimize)
173*d415bd75Srobert return false;
174*d415bd75Srobert
17509467b48Spatrick LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
17609467b48Spatrick << "**********\n");
17709467b48Spatrick
17809467b48Spatrick bool Changed = false;
17973471bf0Spatrick MLI = &getAnalysis<MachineLoopInfo>();
18009467b48Spatrick const TargetSubtargetInfo &STI = MF.getSubtarget();
18109467b48Spatrick MRI = &MF.getRegInfo();
18209467b48Spatrick TII = STI.getInstrInfo();
18309467b48Spatrick TRI = STI.getRegisterInfo();
18409467b48Spatrick TSchedModel.init(&STI);
18509467b48Spatrick
18609467b48Spatrick // Before we handle the more subtle cases of register-register CMOVs inside
187*d415bd75Srobert // of potentially hot loops, we want to quickly remove all CMOVs (ForceAll) or
188*d415bd75Srobert // the ones with a memory operand (ForceMemOperand option). The latter CMOV
189*d415bd75Srobert // will risk a stall waiting for the load to complete that speculative
190*d415bd75Srobert // execution behind a branch is better suited to handle on modern x86 chips.
191*d415bd75Srobert if (ForceMemOperand || ForceAll) {
19209467b48Spatrick CmovGroups AllCmovGroups;
19309467b48Spatrick SmallVector<MachineBasicBlock *, 4> Blocks;
19409467b48Spatrick for (auto &MBB : MF)
19509467b48Spatrick Blocks.push_back(&MBB);
19609467b48Spatrick if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
19709467b48Spatrick for (auto &Group : AllCmovGroups) {
19809467b48Spatrick // Skip any group that doesn't do at least one memory operand cmov.
199*d415bd75Srobert if (ForceMemOperand && !ForceAll &&
200*d415bd75Srobert llvm::none_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
20109467b48Spatrick continue;
20209467b48Spatrick
20309467b48Spatrick // For CMOV groups which we can rewrite and which contain a memory load,
20409467b48Spatrick // always rewrite them. On x86, a CMOV will dramatically amplify any
20509467b48Spatrick // memory latency by blocking speculative execution.
20609467b48Spatrick Changed = true;
20709467b48Spatrick convertCmovInstsToBranches(Group);
20809467b48Spatrick }
20909467b48Spatrick }
210*d415bd75Srobert // Early return as ForceAll converts all CmovGroups.
211*d415bd75Srobert if (ForceAll)
212*d415bd75Srobert return Changed;
21309467b48Spatrick }
21409467b48Spatrick
21509467b48Spatrick //===--------------------------------------------------------------------===//
21609467b48Spatrick // Register-operand Conversion Algorithm
21709467b48Spatrick // ---------
21809467b48Spatrick // For each innermost loop
21909467b48Spatrick // collectCmovCandidates() {
22009467b48Spatrick // Find all CMOV-group-candidates.
22109467b48Spatrick // }
22209467b48Spatrick //
22309467b48Spatrick // checkForProfitableCmovCandidates() {
22409467b48Spatrick // * Calculate both loop-depth and optimized-loop-depth.
22509467b48Spatrick // * Use these depth to check for loop transformation profitability.
22609467b48Spatrick // * Check for CMOV-group-candidate transformation profitability.
22709467b48Spatrick // }
22809467b48Spatrick //
22909467b48Spatrick // For each profitable CMOV-group-candidate
23009467b48Spatrick // convertCmovInstsToBranches() {
23109467b48Spatrick // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
23209467b48Spatrick // * Replace each CMOV instruction with a PHI instruction in SinkBB.
23309467b48Spatrick // }
23409467b48Spatrick //
23509467b48Spatrick // Note: For more details, see each function description.
23609467b48Spatrick //===--------------------------------------------------------------------===//
23709467b48Spatrick
23809467b48Spatrick // Build up the loops in pre-order.
23973471bf0Spatrick SmallVector<MachineLoop *, 4> Loops(MLI->begin(), MLI->end());
24009467b48Spatrick // Note that we need to check size on each iteration as we accumulate child
24109467b48Spatrick // loops.
24209467b48Spatrick for (int i = 0; i < (int)Loops.size(); ++i)
24309467b48Spatrick for (MachineLoop *Child : Loops[i]->getSubLoops())
24409467b48Spatrick Loops.push_back(Child);
24509467b48Spatrick
24609467b48Spatrick for (MachineLoop *CurrLoop : Loops) {
24709467b48Spatrick // Optimize only innermost loops.
24809467b48Spatrick if (!CurrLoop->getSubLoops().empty())
24909467b48Spatrick continue;
25009467b48Spatrick
25109467b48Spatrick // List of consecutive CMOV instructions to be processed.
25209467b48Spatrick CmovGroups CmovInstGroups;
25309467b48Spatrick
25409467b48Spatrick if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
25509467b48Spatrick continue;
25609467b48Spatrick
25709467b48Spatrick if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
25809467b48Spatrick CmovInstGroups))
25909467b48Spatrick continue;
26009467b48Spatrick
26109467b48Spatrick Changed = true;
26209467b48Spatrick for (auto &Group : CmovInstGroups)
26309467b48Spatrick convertCmovInstsToBranches(Group);
26409467b48Spatrick }
26509467b48Spatrick
26609467b48Spatrick return Changed;
26709467b48Spatrick }
26809467b48Spatrick
collectCmovCandidates(ArrayRef<MachineBasicBlock * > Blocks,CmovGroups & CmovInstGroups,bool IncludeLoads)26909467b48Spatrick bool X86CmovConverterPass::collectCmovCandidates(
27009467b48Spatrick ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
27109467b48Spatrick bool IncludeLoads) {
27209467b48Spatrick //===--------------------------------------------------------------------===//
27309467b48Spatrick // Collect all CMOV-group-candidates and add them into CmovInstGroups.
27409467b48Spatrick //
27509467b48Spatrick // CMOV-group:
27609467b48Spatrick // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
27709467b48Spatrick //
27809467b48Spatrick // CMOV-group-candidate:
27909467b48Spatrick // CMOV-group where all the CMOV instructions are
28009467b48Spatrick // 1. consecutive.
28109467b48Spatrick // 2. have same condition code or opposite one.
28209467b48Spatrick // 3. have only operand registers (X86::CMOVrr).
28309467b48Spatrick //===--------------------------------------------------------------------===//
28409467b48Spatrick // List of possible improvement (TODO's):
28509467b48Spatrick // --------------------------------------
28609467b48Spatrick // TODO: Add support for X86::CMOVrm instructions.
28709467b48Spatrick // TODO: Add support for X86::SETcc instructions.
28809467b48Spatrick // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
28909467b48Spatrick //===--------------------------------------------------------------------===//
29009467b48Spatrick
29109467b48Spatrick // Current processed CMOV-Group.
29209467b48Spatrick CmovGroup Group;
29309467b48Spatrick for (auto *MBB : Blocks) {
29409467b48Spatrick Group.clear();
29509467b48Spatrick // Condition code of first CMOV instruction current processed range and its
29609467b48Spatrick // opposite condition code.
29709467b48Spatrick X86::CondCode FirstCC = X86::COND_INVALID, FirstOppCC = X86::COND_INVALID,
29809467b48Spatrick MemOpCC = X86::COND_INVALID;
29909467b48Spatrick // Indicator of a non CMOVrr instruction in the current processed range.
30009467b48Spatrick bool FoundNonCMOVInst = false;
30109467b48Spatrick // Indicator for current processed CMOV-group if it should be skipped.
30209467b48Spatrick bool SkipGroup = false;
30309467b48Spatrick
30409467b48Spatrick for (auto &I : *MBB) {
30509467b48Spatrick // Skip debug instructions.
30609467b48Spatrick if (I.isDebugInstr())
30709467b48Spatrick continue;
30809467b48Spatrick X86::CondCode CC = X86::getCondFromCMov(I);
30909467b48Spatrick // Check if we found a X86::CMOVrr instruction.
31009467b48Spatrick if (CC != X86::COND_INVALID && (IncludeLoads || !I.mayLoad())) {
31109467b48Spatrick if (Group.empty()) {
31209467b48Spatrick // We found first CMOV in the range, reset flags.
31309467b48Spatrick FirstCC = CC;
31409467b48Spatrick FirstOppCC = X86::GetOppositeBranchCondition(CC);
31509467b48Spatrick // Clear out the prior group's memory operand CC.
31609467b48Spatrick MemOpCC = X86::COND_INVALID;
31709467b48Spatrick FoundNonCMOVInst = false;
31809467b48Spatrick SkipGroup = false;
31909467b48Spatrick }
32009467b48Spatrick Group.push_back(&I);
32109467b48Spatrick // Check if it is a non-consecutive CMOV instruction or it has different
32209467b48Spatrick // condition code than FirstCC or FirstOppCC.
32309467b48Spatrick if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
32409467b48Spatrick // Mark the SKipGroup indicator to skip current processed CMOV-Group.
32509467b48Spatrick SkipGroup = true;
32609467b48Spatrick if (I.mayLoad()) {
32709467b48Spatrick if (MemOpCC == X86::COND_INVALID)
32809467b48Spatrick // The first memory operand CMOV.
32909467b48Spatrick MemOpCC = CC;
33009467b48Spatrick else if (CC != MemOpCC)
33109467b48Spatrick // Can't handle mixed conditions with memory operands.
33209467b48Spatrick SkipGroup = true;
33309467b48Spatrick }
33409467b48Spatrick // Check if we were relying on zero-extending behavior of the CMOV.
33509467b48Spatrick if (!SkipGroup &&
33609467b48Spatrick llvm::any_of(
33709467b48Spatrick MRI->use_nodbg_instructions(I.defs().begin()->getReg()),
33809467b48Spatrick [&](MachineInstr &UseI) {
33909467b48Spatrick return UseI.getOpcode() == X86::SUBREG_TO_REG;
34009467b48Spatrick }))
34109467b48Spatrick // FIXME: We should model the cost of using an explicit MOV to handle
34209467b48Spatrick // the zero-extension rather than just refusing to handle this.
34309467b48Spatrick SkipGroup = true;
34409467b48Spatrick continue;
34509467b48Spatrick }
34609467b48Spatrick // If Group is empty, keep looking for first CMOV in the range.
34709467b48Spatrick if (Group.empty())
34809467b48Spatrick continue;
34909467b48Spatrick
35009467b48Spatrick // We found a non X86::CMOVrr instruction.
35109467b48Spatrick FoundNonCMOVInst = true;
35209467b48Spatrick // Check if this instruction define EFLAGS, to determine end of processed
35309467b48Spatrick // range, as there would be no more instructions using current EFLAGS def.
35409467b48Spatrick if (I.definesRegister(X86::EFLAGS)) {
35509467b48Spatrick // Check if current processed CMOV-group should not be skipped and add
35609467b48Spatrick // it as a CMOV-group-candidate.
35709467b48Spatrick if (!SkipGroup)
35809467b48Spatrick CmovInstGroups.push_back(Group);
35909467b48Spatrick else
36009467b48Spatrick ++NumOfSkippedCmovGroups;
36109467b48Spatrick Group.clear();
36209467b48Spatrick }
36309467b48Spatrick }
36409467b48Spatrick // End of basic block is considered end of range, check if current processed
36509467b48Spatrick // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
36609467b48Spatrick if (Group.empty())
36709467b48Spatrick continue;
36809467b48Spatrick if (!SkipGroup)
36909467b48Spatrick CmovInstGroups.push_back(Group);
37009467b48Spatrick else
37109467b48Spatrick ++NumOfSkippedCmovGroups;
37209467b48Spatrick }
37309467b48Spatrick
37409467b48Spatrick NumOfCmovGroupCandidate += CmovInstGroups.size();
37509467b48Spatrick return !CmovInstGroups.empty();
37609467b48Spatrick }
37709467b48Spatrick
37809467b48Spatrick /// \returns Depth of CMOV instruction as if it was converted into branch.
37909467b48Spatrick /// \param TrueOpDepth depth cost of CMOV true value operand.
38009467b48Spatrick /// \param FalseOpDepth depth cost of CMOV false value operand.
getDepthOfOptCmov(unsigned TrueOpDepth,unsigned FalseOpDepth)38109467b48Spatrick static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
38209467b48Spatrick // The depth of the result after branch conversion is
38309467b48Spatrick // TrueOpDepth * TrueOpProbability + FalseOpDepth * FalseOpProbability.
38409467b48Spatrick // As we have no info about branch weight, we assume 75% for one and 25% for
38509467b48Spatrick // the other, and pick the result with the largest resulting depth.
38609467b48Spatrick return std::max(
38709467b48Spatrick divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
38809467b48Spatrick divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
38909467b48Spatrick }
39009467b48Spatrick
checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock * > Blocks,CmovGroups & CmovInstGroups)39109467b48Spatrick bool X86CmovConverterPass::checkForProfitableCmovCandidates(
39209467b48Spatrick ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
39309467b48Spatrick struct DepthInfo {
39409467b48Spatrick /// Depth of original loop.
39509467b48Spatrick unsigned Depth;
39609467b48Spatrick /// Depth of optimized loop.
39709467b48Spatrick unsigned OptDepth;
39809467b48Spatrick };
39909467b48Spatrick /// Number of loop iterations to calculate depth for ?!
40009467b48Spatrick static const unsigned LoopIterations = 2;
40109467b48Spatrick DenseMap<MachineInstr *, DepthInfo> DepthMap;
40209467b48Spatrick DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
40309467b48Spatrick enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
40409467b48Spatrick /// For each register type maps the register to its last def instruction.
40509467b48Spatrick DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
40609467b48Spatrick /// Maps register operand to its def instruction, which can be nullptr if it
40709467b48Spatrick /// is unknown (e.g., operand is defined outside the loop).
40809467b48Spatrick DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
40909467b48Spatrick
41009467b48Spatrick // Set depth of unknown instruction (i.e., nullptr) to zero.
41109467b48Spatrick DepthMap[nullptr] = {0, 0};
41209467b48Spatrick
41309467b48Spatrick SmallPtrSet<MachineInstr *, 4> CmovInstructions;
41409467b48Spatrick for (auto &Group : CmovInstGroups)
41509467b48Spatrick CmovInstructions.insert(Group.begin(), Group.end());
41609467b48Spatrick
41709467b48Spatrick //===--------------------------------------------------------------------===//
41809467b48Spatrick // Step 1: Calculate instruction depth and loop depth.
41909467b48Spatrick // Optimized-Loop:
42009467b48Spatrick // loop with CMOV-group-candidates converted into branches.
42109467b48Spatrick //
42209467b48Spatrick // Instruction-Depth:
42309467b48Spatrick // instruction latency + max operand depth.
42409467b48Spatrick // * For CMOV instruction in optimized loop the depth is calculated as:
42509467b48Spatrick // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
42609467b48Spatrick // TODO: Find a better way to estimate the latency of the branch instruction
42709467b48Spatrick // rather than using the CMOV latency.
42809467b48Spatrick //
42909467b48Spatrick // Loop-Depth:
43009467b48Spatrick // max instruction depth of all instructions in the loop.
43109467b48Spatrick // Note: instruction with max depth represents the critical-path in the loop.
43209467b48Spatrick //
43309467b48Spatrick // Loop-Depth[i]:
43409467b48Spatrick // Loop-Depth calculated for first `i` iterations.
43509467b48Spatrick // Note: it is enough to calculate depth for up to two iterations.
43609467b48Spatrick //
43709467b48Spatrick // Depth-Diff[i]:
43809467b48Spatrick // Number of cycles saved in first 'i` iterations by optimizing the loop.
43909467b48Spatrick //===--------------------------------------------------------------------===//
440*d415bd75Srobert for (DepthInfo &MaxDepth : LoopDepth) {
44109467b48Spatrick for (auto *MBB : Blocks) {
44209467b48Spatrick // Clear physical registers Def map.
44309467b48Spatrick RegDefMaps[PhyRegType].clear();
44409467b48Spatrick for (MachineInstr &MI : *MBB) {
44509467b48Spatrick // Skip debug instructions.
44609467b48Spatrick if (MI.isDebugInstr())
44709467b48Spatrick continue;
44809467b48Spatrick unsigned MIDepth = 0;
44909467b48Spatrick unsigned MIDepthOpt = 0;
45009467b48Spatrick bool IsCMOV = CmovInstructions.count(&MI);
45109467b48Spatrick for (auto &MO : MI.uses()) {
45209467b48Spatrick // Checks for "isUse()" as "uses()" returns also implicit definitions.
45309467b48Spatrick if (!MO.isReg() || !MO.isUse())
45409467b48Spatrick continue;
45509467b48Spatrick Register Reg = MO.getReg();
45673471bf0Spatrick auto &RDM = RegDefMaps[Reg.isVirtual()];
45709467b48Spatrick if (MachineInstr *DefMI = RDM.lookup(Reg)) {
45809467b48Spatrick OperandToDefMap[&MO] = DefMI;
45909467b48Spatrick DepthInfo Info = DepthMap.lookup(DefMI);
46009467b48Spatrick MIDepth = std::max(MIDepth, Info.Depth);
46109467b48Spatrick if (!IsCMOV)
46209467b48Spatrick MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
46309467b48Spatrick }
46409467b48Spatrick }
46509467b48Spatrick
46609467b48Spatrick if (IsCMOV)
46709467b48Spatrick MIDepthOpt = getDepthOfOptCmov(
46809467b48Spatrick DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
46909467b48Spatrick DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
47009467b48Spatrick
47109467b48Spatrick // Iterates over all operands to handle implicit definitions as well.
47209467b48Spatrick for (auto &MO : MI.operands()) {
47309467b48Spatrick if (!MO.isReg() || !MO.isDef())
47409467b48Spatrick continue;
47509467b48Spatrick Register Reg = MO.getReg();
47673471bf0Spatrick RegDefMaps[Reg.isVirtual()][Reg] = &MI;
47709467b48Spatrick }
47809467b48Spatrick
47909467b48Spatrick unsigned Latency = TSchedModel.computeInstrLatency(&MI);
48009467b48Spatrick DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
48109467b48Spatrick MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
48209467b48Spatrick MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
48309467b48Spatrick }
48409467b48Spatrick }
48509467b48Spatrick }
48609467b48Spatrick
48709467b48Spatrick unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
48809467b48Spatrick LoopDepth[1].Depth - LoopDepth[1].OptDepth};
48909467b48Spatrick
49009467b48Spatrick //===--------------------------------------------------------------------===//
49109467b48Spatrick // Step 2: Check if Loop worth to be optimized.
49209467b48Spatrick // Worth-Optimize-Loop:
49309467b48Spatrick // case 1: Diff[1] == Diff[0]
49409467b48Spatrick // Critical-path is iteration independent - there is no dependency
49509467b48Spatrick // of critical-path instructions on critical-path instructions of
49609467b48Spatrick // previous iteration.
49709467b48Spatrick // Thus, it is enough to check gain percent of 1st iteration -
49809467b48Spatrick // To be conservative, the optimized loop need to have a depth of
49909467b48Spatrick // 12.5% cycles less than original loop, per iteration.
50009467b48Spatrick //
50109467b48Spatrick // case 2: Diff[1] > Diff[0]
50209467b48Spatrick // Critical-path is iteration dependent - there is dependency of
50309467b48Spatrick // critical-path instructions on critical-path instructions of
50409467b48Spatrick // previous iteration.
50509467b48Spatrick // Thus, check the gain percent of the 2nd iteration (similar to the
50609467b48Spatrick // previous case), but it is also required to check the gradient of
50709467b48Spatrick // the gain - the change in Depth-Diff compared to the change in
50809467b48Spatrick // Loop-Depth between 1st and 2nd iterations.
50909467b48Spatrick // To be conservative, the gradient need to be at least 50%.
51009467b48Spatrick //
51109467b48Spatrick // In addition, In order not to optimize loops with very small gain, the
51209467b48Spatrick // gain (in cycles) after 2nd iteration should not be less than a given
51309467b48Spatrick // threshold. Thus, the check (Diff[1] >= GainCycleThreshold) must apply.
51409467b48Spatrick //
51509467b48Spatrick // If loop is not worth optimizing, remove all CMOV-group-candidates.
51609467b48Spatrick //===--------------------------------------------------------------------===//
51709467b48Spatrick if (Diff[1] < GainCycleThreshold)
51809467b48Spatrick return false;
51909467b48Spatrick
52009467b48Spatrick bool WorthOptLoop = false;
52109467b48Spatrick if (Diff[1] == Diff[0])
52209467b48Spatrick WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
52309467b48Spatrick else if (Diff[1] > Diff[0])
52409467b48Spatrick WorthOptLoop =
52509467b48Spatrick (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
52609467b48Spatrick (Diff[1] * 8 >= LoopDepth[1].Depth);
52709467b48Spatrick
52809467b48Spatrick if (!WorthOptLoop)
52909467b48Spatrick return false;
53009467b48Spatrick
53109467b48Spatrick ++NumOfLoopCandidate;
53209467b48Spatrick
53309467b48Spatrick //===--------------------------------------------------------------------===//
53409467b48Spatrick // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
53509467b48Spatrick // Worth-Optimize-Group:
536*d415bd75Srobert // Iff it is worth to optimize all CMOV instructions in the group.
53709467b48Spatrick //
53809467b48Spatrick // Worth-Optimize-CMOV:
53909467b48Spatrick // Predicted branch is faster than CMOV by the difference between depth of
54009467b48Spatrick // condition operand and depth of taken (predicted) value operand.
54109467b48Spatrick // To be conservative, the gain of such CMOV transformation should cover at
54209467b48Spatrick // at least 25% of branch-misprediction-penalty.
54309467b48Spatrick //===--------------------------------------------------------------------===//
54409467b48Spatrick unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
54509467b48Spatrick CmovGroups TempGroups;
54609467b48Spatrick std::swap(TempGroups, CmovInstGroups);
54709467b48Spatrick for (auto &Group : TempGroups) {
54809467b48Spatrick bool WorthOpGroup = true;
54909467b48Spatrick for (auto *MI : Group) {
55009467b48Spatrick // Avoid CMOV instruction which value is used as a pointer to load from.
55109467b48Spatrick // This is another conservative check to avoid converting CMOV instruction
55209467b48Spatrick // used with tree-search like algorithm, where the branch is unpredicted.
55309467b48Spatrick auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
55473471bf0Spatrick if (!UIs.empty() && ++UIs.begin() == UIs.end()) {
55509467b48Spatrick unsigned Op = UIs.begin()->getOpcode();
55609467b48Spatrick if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
55709467b48Spatrick WorthOpGroup = false;
55809467b48Spatrick break;
55909467b48Spatrick }
56009467b48Spatrick }
56109467b48Spatrick
56209467b48Spatrick unsigned CondCost =
56309467b48Spatrick DepthMap[OperandToDefMap.lookup(&MI->getOperand(4))].Depth;
56409467b48Spatrick unsigned ValCost = getDepthOfOptCmov(
56509467b48Spatrick DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
56609467b48Spatrick DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
56709467b48Spatrick if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
56809467b48Spatrick WorthOpGroup = false;
56909467b48Spatrick break;
57009467b48Spatrick }
57109467b48Spatrick }
57209467b48Spatrick
57309467b48Spatrick if (WorthOpGroup)
57409467b48Spatrick CmovInstGroups.push_back(Group);
57509467b48Spatrick }
57609467b48Spatrick
57709467b48Spatrick return !CmovInstGroups.empty();
57809467b48Spatrick }
57909467b48Spatrick
checkEFLAGSLive(MachineInstr * MI)58009467b48Spatrick static bool checkEFLAGSLive(MachineInstr *MI) {
58109467b48Spatrick if (MI->killsRegister(X86::EFLAGS))
58209467b48Spatrick return false;
58309467b48Spatrick
58409467b48Spatrick // The EFLAGS operand of MI might be missing a kill marker.
58509467b48Spatrick // Figure out whether EFLAGS operand should LIVE after MI instruction.
58609467b48Spatrick MachineBasicBlock *BB = MI->getParent();
58709467b48Spatrick MachineBasicBlock::iterator ItrMI = MI;
58809467b48Spatrick
58909467b48Spatrick // Scan forward through BB for a use/def of EFLAGS.
59009467b48Spatrick for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
59109467b48Spatrick if (I->readsRegister(X86::EFLAGS))
59209467b48Spatrick return true;
59309467b48Spatrick if (I->definesRegister(X86::EFLAGS))
59409467b48Spatrick return false;
59509467b48Spatrick }
59609467b48Spatrick
59709467b48Spatrick // We hit the end of the block, check whether EFLAGS is live into a successor.
598*d415bd75Srobert for (MachineBasicBlock *Succ : BB->successors())
599*d415bd75Srobert if (Succ->isLiveIn(X86::EFLAGS))
60009467b48Spatrick return true;
60109467b48Spatrick
60209467b48Spatrick return false;
60309467b48Spatrick }
60409467b48Spatrick
60509467b48Spatrick /// Given /p First CMOV instruction and /p Last CMOV instruction representing a
60609467b48Spatrick /// group of CMOV instructions, which may contain debug instructions in between,
60709467b48Spatrick /// move all debug instructions to after the last CMOV instruction, making the
60809467b48Spatrick /// CMOV group consecutive.
packCmovGroup(MachineInstr * First,MachineInstr * Last)60909467b48Spatrick static void packCmovGroup(MachineInstr *First, MachineInstr *Last) {
61009467b48Spatrick assert(X86::getCondFromCMov(*Last) != X86::COND_INVALID &&
61109467b48Spatrick "Last instruction in a CMOV group must be a CMOV instruction");
61209467b48Spatrick
61309467b48Spatrick SmallVector<MachineInstr *, 2> DBGInstructions;
61409467b48Spatrick for (auto I = First->getIterator(), E = Last->getIterator(); I != E; I++) {
61509467b48Spatrick if (I->isDebugInstr())
61609467b48Spatrick DBGInstructions.push_back(&*I);
61709467b48Spatrick }
61809467b48Spatrick
61909467b48Spatrick // Splice the debug instruction after the cmov group.
62009467b48Spatrick MachineBasicBlock *MBB = First->getParent();
62109467b48Spatrick for (auto *MI : DBGInstructions)
62209467b48Spatrick MBB->insertAfter(Last, MI->removeFromParent());
62309467b48Spatrick }
62409467b48Spatrick
convertCmovInstsToBranches(SmallVectorImpl<MachineInstr * > & Group) const62509467b48Spatrick void X86CmovConverterPass::convertCmovInstsToBranches(
62609467b48Spatrick SmallVectorImpl<MachineInstr *> &Group) const {
62709467b48Spatrick assert(!Group.empty() && "No CMOV instructions to convert");
62809467b48Spatrick ++NumOfOptimizedCmovGroups;
62909467b48Spatrick
63009467b48Spatrick // If the CMOV group is not packed, e.g., there are debug instructions between
63109467b48Spatrick // first CMOV and last CMOV, then pack the group and make the CMOV instruction
63209467b48Spatrick // consecutive by moving the debug instructions to after the last CMOV.
63309467b48Spatrick packCmovGroup(Group.front(), Group.back());
63409467b48Spatrick
63509467b48Spatrick // To convert a CMOVcc instruction, we actually have to insert the diamond
63609467b48Spatrick // control-flow pattern. The incoming instruction knows the destination vreg
63709467b48Spatrick // to set, the condition code register to branch on, the true/false values to
63809467b48Spatrick // select between, and a branch opcode to use.
63909467b48Spatrick
64009467b48Spatrick // Before
64109467b48Spatrick // -----
64209467b48Spatrick // MBB:
64309467b48Spatrick // cond = cmp ...
64409467b48Spatrick // v1 = CMOVge t1, f1, cond
64509467b48Spatrick // v2 = CMOVlt t2, f2, cond
64609467b48Spatrick // v3 = CMOVge v1, f3, cond
64709467b48Spatrick //
64809467b48Spatrick // After
64909467b48Spatrick // -----
65009467b48Spatrick // MBB:
65109467b48Spatrick // cond = cmp ...
65209467b48Spatrick // jge %SinkMBB
65309467b48Spatrick //
65409467b48Spatrick // FalseMBB:
65509467b48Spatrick // jmp %SinkMBB
65609467b48Spatrick //
65709467b48Spatrick // SinkMBB:
65809467b48Spatrick // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
65909467b48Spatrick // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
66009467b48Spatrick // ; true-value with false-value
66109467b48Spatrick // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
66209467b48Spatrick // ; previous Phi instruction result
66309467b48Spatrick
66409467b48Spatrick MachineInstr &MI = *Group.front();
66509467b48Spatrick MachineInstr *LastCMOV = Group.back();
66609467b48Spatrick DebugLoc DL = MI.getDebugLoc();
66709467b48Spatrick
66809467b48Spatrick X86::CondCode CC = X86::CondCode(X86::getCondFromCMov(MI));
66909467b48Spatrick X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
67009467b48Spatrick // Potentially swap the condition codes so that any memory operand to a CMOV
67109467b48Spatrick // is in the *false* position instead of the *true* position. We can invert
67209467b48Spatrick // any non-memory operand CMOV instructions to cope with this and we ensure
67309467b48Spatrick // memory operand CMOVs are only included with a single condition code.
67409467b48Spatrick if (llvm::any_of(Group, [&](MachineInstr *I) {
67509467b48Spatrick return I->mayLoad() && X86::getCondFromCMov(*I) == CC;
67609467b48Spatrick }))
67709467b48Spatrick std::swap(CC, OppCC);
67809467b48Spatrick
67909467b48Spatrick MachineBasicBlock *MBB = MI.getParent();
68009467b48Spatrick MachineFunction::iterator It = ++MBB->getIterator();
68109467b48Spatrick MachineFunction *F = MBB->getParent();
68209467b48Spatrick const BasicBlock *BB = MBB->getBasicBlock();
68309467b48Spatrick
68409467b48Spatrick MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
68509467b48Spatrick MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
68609467b48Spatrick F->insert(It, FalseMBB);
68709467b48Spatrick F->insert(It, SinkMBB);
68809467b48Spatrick
68909467b48Spatrick // If the EFLAGS register isn't dead in the terminator, then claim that it's
69009467b48Spatrick // live into the sink and copy blocks.
69109467b48Spatrick if (checkEFLAGSLive(LastCMOV)) {
69209467b48Spatrick FalseMBB->addLiveIn(X86::EFLAGS);
69309467b48Spatrick SinkMBB->addLiveIn(X86::EFLAGS);
69409467b48Spatrick }
69509467b48Spatrick
69609467b48Spatrick // Transfer the remainder of BB and its successor edges to SinkMBB.
69709467b48Spatrick SinkMBB->splice(SinkMBB->begin(), MBB,
69809467b48Spatrick std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
69909467b48Spatrick SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
70009467b48Spatrick
70109467b48Spatrick // Add the false and sink blocks as its successors.
70209467b48Spatrick MBB->addSuccessor(FalseMBB);
70309467b48Spatrick MBB->addSuccessor(SinkMBB);
70409467b48Spatrick
70509467b48Spatrick // Create the conditional branch instruction.
70609467b48Spatrick BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
70709467b48Spatrick
70809467b48Spatrick // Add the sink block to the false block successors.
70909467b48Spatrick FalseMBB->addSuccessor(SinkMBB);
71009467b48Spatrick
71109467b48Spatrick MachineInstrBuilder MIB;
71209467b48Spatrick MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
71309467b48Spatrick MachineBasicBlock::iterator MIItEnd =
71409467b48Spatrick std::next(MachineBasicBlock::iterator(LastCMOV));
71509467b48Spatrick MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
71609467b48Spatrick MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
71709467b48Spatrick
71809467b48Spatrick // First we need to insert an explicit load on the false path for any memory
71909467b48Spatrick // operand. We also need to potentially do register rewriting here, but it is
72009467b48Spatrick // simpler as the memory operands are always on the false path so we can
72109467b48Spatrick // simply take that input, whatever it is.
72209467b48Spatrick DenseMap<unsigned, unsigned> FalseBBRegRewriteTable;
72309467b48Spatrick for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
72409467b48Spatrick auto &MI = *MIIt++;
72509467b48Spatrick // Skip any CMOVs in this group which don't load from memory.
72609467b48Spatrick if (!MI.mayLoad()) {
72709467b48Spatrick // Remember the false-side register input.
72809467b48Spatrick Register FalseReg =
72909467b48Spatrick MI.getOperand(X86::getCondFromCMov(MI) == CC ? 1 : 2).getReg();
73009467b48Spatrick // Walk back through any intermediate cmovs referenced.
73109467b48Spatrick while (true) {
73209467b48Spatrick auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
73309467b48Spatrick if (FRIt == FalseBBRegRewriteTable.end())
73409467b48Spatrick break;
73509467b48Spatrick FalseReg = FRIt->second;
73609467b48Spatrick }
73709467b48Spatrick FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
73809467b48Spatrick continue;
73909467b48Spatrick }
74009467b48Spatrick
74109467b48Spatrick // The condition must be the *opposite* of the one we've decided to branch
74209467b48Spatrick // on as the branch will go *around* the load and the load should happen
74309467b48Spatrick // when the CMOV condition is false.
74409467b48Spatrick assert(X86::getCondFromCMov(MI) == OppCC &&
74509467b48Spatrick "Can only handle memory-operand cmov instructions with a condition "
74609467b48Spatrick "opposite to the selected branch direction.");
74709467b48Spatrick
74809467b48Spatrick // The goal is to rewrite the cmov from:
74909467b48Spatrick //
75009467b48Spatrick // MBB:
75109467b48Spatrick // %A = CMOVcc %B (tied), (mem)
75209467b48Spatrick //
75309467b48Spatrick // to
75409467b48Spatrick //
75509467b48Spatrick // MBB:
75609467b48Spatrick // %A = CMOVcc %B (tied), %C
75709467b48Spatrick // FalseMBB:
75809467b48Spatrick // %C = MOV (mem)
75909467b48Spatrick //
76009467b48Spatrick // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
76109467b48Spatrick //
76209467b48Spatrick // MBB:
76309467b48Spatrick // JMP!cc SinkMBB
76409467b48Spatrick // FalseMBB:
76509467b48Spatrick // %C = MOV (mem)
76609467b48Spatrick // SinkMBB:
76709467b48Spatrick // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
76809467b48Spatrick
76909467b48Spatrick // Get a fresh register to use as the destination of the MOV.
77009467b48Spatrick const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
77109467b48Spatrick Register TmpReg = MRI->createVirtualRegister(RC);
77209467b48Spatrick
77309467b48Spatrick SmallVector<MachineInstr *, 4> NewMIs;
77409467b48Spatrick bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
77509467b48Spatrick /*UnfoldLoad*/ true,
77609467b48Spatrick /*UnfoldStore*/ false, NewMIs);
77709467b48Spatrick (void)Unfolded;
77809467b48Spatrick assert(Unfolded && "Should never fail to unfold a loading cmov!");
77909467b48Spatrick
78009467b48Spatrick // Move the new CMOV to just before the old one and reset any impacted
78109467b48Spatrick // iterator.
78209467b48Spatrick auto *NewCMOV = NewMIs.pop_back_val();
78309467b48Spatrick assert(X86::getCondFromCMov(*NewCMOV) == OppCC &&
78409467b48Spatrick "Last new instruction isn't the expected CMOV!");
78509467b48Spatrick LLVM_DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
78609467b48Spatrick MBB->insert(MachineBasicBlock::iterator(MI), NewCMOV);
78709467b48Spatrick if (&*MIItBegin == &MI)
78809467b48Spatrick MIItBegin = MachineBasicBlock::iterator(NewCMOV);
78909467b48Spatrick
79009467b48Spatrick // Sink whatever instructions were needed to produce the unfolded operand
79109467b48Spatrick // into the false block.
79209467b48Spatrick for (auto *NewMI : NewMIs) {
79309467b48Spatrick LLVM_DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
79409467b48Spatrick FalseMBB->insert(FalseInsertionPoint, NewMI);
79509467b48Spatrick // Re-map any operands that are from other cmovs to the inputs for this block.
79609467b48Spatrick for (auto &MOp : NewMI->uses()) {
79709467b48Spatrick if (!MOp.isReg())
79809467b48Spatrick continue;
79909467b48Spatrick auto It = FalseBBRegRewriteTable.find(MOp.getReg());
80009467b48Spatrick if (It == FalseBBRegRewriteTable.end())
80109467b48Spatrick continue;
80209467b48Spatrick
80309467b48Spatrick MOp.setReg(It->second);
80409467b48Spatrick // This might have been a kill when it referenced the cmov result, but
80509467b48Spatrick // it won't necessarily be once rewritten.
80609467b48Spatrick // FIXME: We could potentially improve this by tracking whether the
80709467b48Spatrick // operand to the cmov was also a kill, and then skipping the PHI node
80809467b48Spatrick // construction below.
80909467b48Spatrick MOp.setIsKill(false);
81009467b48Spatrick }
81109467b48Spatrick }
812*d415bd75Srobert MBB->erase(&MI);
81309467b48Spatrick
81409467b48Spatrick // Add this PHI to the rewrite table.
81509467b48Spatrick FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
81609467b48Spatrick }
81709467b48Spatrick
81809467b48Spatrick // As we are creating the PHIs, we have to be careful if there is more than
81909467b48Spatrick // one. Later CMOVs may reference the results of earlier CMOVs, but later
82009467b48Spatrick // PHIs have to reference the individual true/false inputs from earlier PHIs.
82109467b48Spatrick // That also means that PHI construction must work forward from earlier to
82209467b48Spatrick // later, and that the code must maintain a mapping from earlier PHI's
82309467b48Spatrick // destination registers, and the registers that went into the PHI.
82409467b48Spatrick DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
82509467b48Spatrick
82609467b48Spatrick for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
82709467b48Spatrick Register DestReg = MIIt->getOperand(0).getReg();
82809467b48Spatrick Register Op1Reg = MIIt->getOperand(1).getReg();
82909467b48Spatrick Register Op2Reg = MIIt->getOperand(2).getReg();
83009467b48Spatrick
83109467b48Spatrick // If this CMOV we are processing is the opposite condition from the jump we
83209467b48Spatrick // generated, then we have to swap the operands for the PHI that is going to
83309467b48Spatrick // be generated.
83409467b48Spatrick if (X86::getCondFromCMov(*MIIt) == OppCC)
83509467b48Spatrick std::swap(Op1Reg, Op2Reg);
83609467b48Spatrick
83709467b48Spatrick auto Op1Itr = RegRewriteTable.find(Op1Reg);
83809467b48Spatrick if (Op1Itr != RegRewriteTable.end())
83909467b48Spatrick Op1Reg = Op1Itr->second.first;
84009467b48Spatrick
84109467b48Spatrick auto Op2Itr = RegRewriteTable.find(Op2Reg);
84209467b48Spatrick if (Op2Itr != RegRewriteTable.end())
84309467b48Spatrick Op2Reg = Op2Itr->second.second;
84409467b48Spatrick
84509467b48Spatrick // SinkMBB:
84609467b48Spatrick // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
84709467b48Spatrick // ...
84809467b48Spatrick MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
84909467b48Spatrick .addReg(Op1Reg)
85009467b48Spatrick .addMBB(FalseMBB)
85109467b48Spatrick .addReg(Op2Reg)
85209467b48Spatrick .addMBB(MBB);
85309467b48Spatrick (void)MIB;
85409467b48Spatrick LLVM_DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
85509467b48Spatrick LLVM_DEBUG(dbgs() << "\tTo: "; MIB->dump());
85609467b48Spatrick
85709467b48Spatrick // Add this PHI to the rewrite table.
85809467b48Spatrick RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
85909467b48Spatrick }
86009467b48Spatrick
86109467b48Spatrick // Now remove the CMOV(s).
86209467b48Spatrick MBB->erase(MIItBegin, MIItEnd);
86373471bf0Spatrick
86473471bf0Spatrick // Add new basic blocks to MachineLoopInfo.
86573471bf0Spatrick if (MachineLoop *L = MLI->getLoopFor(MBB)) {
86673471bf0Spatrick L->addBasicBlockToLoop(FalseMBB, MLI->getBase());
86773471bf0Spatrick L->addBasicBlockToLoop(SinkMBB, MLI->getBase());
86873471bf0Spatrick }
86909467b48Spatrick }
87009467b48Spatrick
87109467b48Spatrick INITIALIZE_PASS_BEGIN(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
87209467b48Spatrick false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)87309467b48Spatrick INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
87409467b48Spatrick INITIALIZE_PASS_END(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
87509467b48Spatrick false, false)
87609467b48Spatrick
87709467b48Spatrick FunctionPass *llvm::createX86CmovConverterPass() {
87809467b48Spatrick return new X86CmovConverterPass();
87909467b48Spatrick }
880