xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86FlagsCopyLowering.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric /// \file
90b57cec5SDimitry Andric ///
100b57cec5SDimitry Andric /// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
110b57cec5SDimitry Andric /// flag bits.
120b57cec5SDimitry Andric ///
130b57cec5SDimitry Andric /// We have to do this by carefully analyzing and rewriting the usage of the
140b57cec5SDimitry Andric /// copied EFLAGS register because there is no general way to rematerialize the
150b57cec5SDimitry Andric /// entire EFLAGS register safely and efficiently. Using `popf` both forces
160b57cec5SDimitry Andric /// dynamic stack adjustment and can create correctness issues due to IF, TF,
170b57cec5SDimitry Andric /// and other non-status flags being overwritten. Using sequences involving
180b57cec5SDimitry Andric /// SAHF don't work on all x86 processors and are often quite slow compared to
190b57cec5SDimitry Andric /// directly testing a single status preserved in its own GPR.
200b57cec5SDimitry Andric ///
210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric #include "X86.h"
240b57cec5SDimitry Andric #include "X86InstrBuilder.h"
250b57cec5SDimitry Andric #include "X86InstrInfo.h"
260b57cec5SDimitry Andric #include "X86Subtarget.h"
27*0fca6ea1SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
280b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
290b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
300b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
310b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
320b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
330b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/MachineSSAUpdater.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
490b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
500b57cec5SDimitry Andric #include "llvm/MC/MCSchedule.h"
510b57cec5SDimitry Andric #include "llvm/Pass.h"
520b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
530b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
540b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
550b57cec5SDimitry Andric #include <algorithm>
560b57cec5SDimitry Andric #include <cassert>
570b57cec5SDimitry Andric #include <iterator>
580b57cec5SDimitry Andric #include <utility>
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric using namespace llvm;
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric #define PASS_KEY "x86-flags-copy-lowering"
630b57cec5SDimitry Andric #define DEBUG_TYPE PASS_KEY
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated");
660b57cec5SDimitry Andric STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted");
670b57cec5SDimitry Andric STATISTIC(NumTestsInserted, "Number of test instructions inserted");
680b57cec5SDimitry Andric STATISTIC(NumAddsInserted, "Number of adds instructions inserted");
69*0fca6ea1SDimitry Andric STATISTIC(NumNFsConvertedTo, "Number of NF instructions converted to");
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric namespace {
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric // Convenient array type for storing registers associated with each condition.
740b57cec5SDimitry Andric using CondRegArray = std::array<unsigned, X86::LAST_VALID_COND + 1>;
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric class X86FlagsCopyLoweringPass : public MachineFunctionPass {
770b57cec5SDimitry Andric public:
X86FlagsCopyLoweringPass()780b57cec5SDimitry Andric   X86FlagsCopyLoweringPass() : MachineFunctionPass(ID) {}
790b57cec5SDimitry Andric 
getPassName() const800b57cec5SDimitry Andric   StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }
810b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
820b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric   /// Pass identification, replacement for typeid.
850b57cec5SDimitry Andric   static char ID;
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric private:
88480093f4SDimitry Andric   MachineRegisterInfo *MRI = nullptr;
89480093f4SDimitry Andric   const X86Subtarget *Subtarget = nullptr;
90480093f4SDimitry Andric   const X86InstrInfo *TII = nullptr;
91480093f4SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
92480093f4SDimitry Andric   const TargetRegisterClass *PromoteRC = nullptr;
93480093f4SDimitry Andric   MachineDominatorTree *MDT = nullptr;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,
960b57cec5SDimitry Andric                                   MachineBasicBlock::iterator CopyDefI);
970b57cec5SDimitry Andric 
98e8d8bef9SDimitry Andric   Register promoteCondToReg(MachineBasicBlock &MBB,
990b57cec5SDimitry Andric                             MachineBasicBlock::iterator TestPos,
100fe6060f1SDimitry Andric                             const DebugLoc &TestLoc, X86::CondCode Cond);
101fe6060f1SDimitry Andric   std::pair<unsigned, bool> getCondOrInverseInReg(
102fe6060f1SDimitry Andric       MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
103fe6060f1SDimitry Andric       const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs);
1040b57cec5SDimitry Andric   void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
105fe6060f1SDimitry Andric                   const DebugLoc &Loc, unsigned Reg);
1060b57cec5SDimitry Andric 
107*0fca6ea1SDimitry Andric   void rewriteSetCC(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
108*0fca6ea1SDimitry Andric                     const DebugLoc &Loc, MachineInstr &MI,
1090b57cec5SDimitry Andric                     CondRegArray &CondRegs);
110*0fca6ea1SDimitry Andric   void rewriteArithmetic(MachineBasicBlock &MBB,
111*0fca6ea1SDimitry Andric                          MachineBasicBlock::iterator Pos, const DebugLoc &Loc,
112*0fca6ea1SDimitry Andric                          MachineInstr &MI, CondRegArray &CondRegs);
113*0fca6ea1SDimitry Andric   void rewriteMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
114*0fca6ea1SDimitry Andric                  const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs);
1150b57cec5SDimitry Andric };
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric } // end anonymous namespace
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass, DEBUG_TYPE,
1200b57cec5SDimitry Andric                       "X86 EFLAGS copy lowering", false, false)
1210b57cec5SDimitry Andric INITIALIZE_PASS_END(X86FlagsCopyLoweringPass, DEBUG_TYPE,
1220b57cec5SDimitry Andric                     "X86 EFLAGS copy lowering", false, false)
1230b57cec5SDimitry Andric 
createX86FlagsCopyLoweringPass()1240b57cec5SDimitry Andric FunctionPass *llvm::createX86FlagsCopyLoweringPass() {
1250b57cec5SDimitry Andric   return new X86FlagsCopyLoweringPass();
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric char X86FlagsCopyLoweringPass::ID = 0;
1290b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1300b57cec5SDimitry Andric void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage &AU) const {
131*0fca6ea1SDimitry Andric   AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();
1320b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric 
isArithmeticOp(unsigned Opc)135*0fca6ea1SDimitry Andric static bool isArithmeticOp(unsigned Opc) {
136*0fca6ea1SDimitry Andric   return X86::isADC(Opc) || X86::isSBB(Opc) || X86::isRCL(Opc) ||
137*0fca6ea1SDimitry Andric          X86::isRCR(Opc) || (Opc == X86::SETB_C32r || Opc == X86::SETB_C64r);
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
splitBlock(MachineBasicBlock & MBB,MachineInstr & SplitI,const X86InstrInfo & TII)1400b57cec5SDimitry Andric static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,
1410b57cec5SDimitry Andric                                      MachineInstr &SplitI,
1420b57cec5SDimitry Andric                                      const X86InstrInfo &TII) {
1430b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   assert(SplitI.getParent() == &MBB &&
1460b57cec5SDimitry Andric          "Split instruction must be in the split block!");
1470b57cec5SDimitry Andric   assert(SplitI.isBranch() &&
1480b57cec5SDimitry Andric          "Only designed to split a tail of branch instructions!");
1490b57cec5SDimitry Andric   assert(X86::getCondFromBranch(SplitI) != X86::COND_INVALID &&
1500b57cec5SDimitry Andric          "Must split on an actual jCC instruction!");
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   // Dig out the previous instruction to the split point.
1530b57cec5SDimitry Andric   MachineInstr &PrevI = *std::prev(SplitI.getIterator());
1540b57cec5SDimitry Andric   assert(PrevI.isBranch() && "Must split after a branch!");
1550b57cec5SDimitry Andric   assert(X86::getCondFromBranch(PrevI) != X86::COND_INVALID &&
1560b57cec5SDimitry Andric          "Must split after an actual jCC instruction!");
1570b57cec5SDimitry Andric   assert(!std::prev(PrevI.getIterator())->isTerminator() &&
1580b57cec5SDimitry Andric          "Must only have this one terminator prior to the split!");
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   // Grab the one successor edge that will stay in `MBB`.
1610b57cec5SDimitry Andric   MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(0).getMBB();
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   // Analyze the original block to see if we are actually splitting an edge
1640b57cec5SDimitry Andric   // into two edges. This can happen when we have multiple conditional jumps to
1650b57cec5SDimitry Andric   // the same successor.
1660b57cec5SDimitry Andric   bool IsEdgeSplit =
1670b57cec5SDimitry Andric       std::any_of(SplitI.getIterator(), MBB.instr_end(),
1680b57cec5SDimitry Andric                   [&](MachineInstr &MI) {
1690b57cec5SDimitry Andric                     assert(MI.isTerminator() &&
1700b57cec5SDimitry Andric                            "Should only have spliced terminators!");
1710b57cec5SDimitry Andric                     return llvm::any_of(
1720b57cec5SDimitry Andric                         MI.operands(), [&](MachineOperand &MOp) {
1730b57cec5SDimitry Andric                           return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;
1740b57cec5SDimitry Andric                         });
1750b57cec5SDimitry Andric                   }) ||
1760b57cec5SDimitry Andric       MBB.getFallThrough() == &UnsplitSucc;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // Insert the new block immediately after the current one. Any existing
1810b57cec5SDimitry Andric   // fallthrough will be sunk into this new block anyways.
1820b57cec5SDimitry Andric   MF.insert(std::next(MachineFunction::iterator(&MBB)), &NewMBB);
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   // Splice the tail of instructions into the new block.
1850b57cec5SDimitry Andric   NewMBB.splice(NewMBB.end(), &MBB, SplitI.getIterator(), MBB.end());
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // Copy the necessary succesors (and their probability info) into the new
1880b57cec5SDimitry Andric   // block.
1890b57cec5SDimitry Andric   for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
1900b57cec5SDimitry Andric     if (IsEdgeSplit || *SI != &UnsplitSucc)
1910b57cec5SDimitry Andric       NewMBB.copySuccessor(&MBB, SI);
1920b57cec5SDimitry Andric   // Normalize the probabilities if we didn't end up splitting the edge.
1930b57cec5SDimitry Andric   if (!IsEdgeSplit)
1940b57cec5SDimitry Andric     NewMBB.normalizeSuccProbs();
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   // Now replace all of the moved successors in the original block with the new
1970b57cec5SDimitry Andric   // block. This will merge their probabilities.
1980b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : NewMBB.successors())
1990b57cec5SDimitry Andric     if (Succ != &UnsplitSucc)
2000b57cec5SDimitry Andric       MBB.replaceSuccessor(Succ, &NewMBB);
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   // We should always end up replacing at least one successor.
2030b57cec5SDimitry Andric   assert(MBB.isSuccessor(&NewMBB) &&
2040b57cec5SDimitry Andric          "Failed to make the new block a successor!");
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   // Now update all the PHIs.
2070b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : NewMBB.successors()) {
2080b57cec5SDimitry Andric     for (MachineInstr &MI : *Succ) {
2090b57cec5SDimitry Andric       if (!MI.isPHI())
2100b57cec5SDimitry Andric         break;
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric       for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;
2130b57cec5SDimitry Andric            OpIdx += 2) {
2140b57cec5SDimitry Andric         MachineOperand &OpV = MI.getOperand(OpIdx);
2150b57cec5SDimitry Andric         MachineOperand &OpMBB = MI.getOperand(OpIdx + 1);
2160b57cec5SDimitry Andric         assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!");
2170b57cec5SDimitry Andric         if (OpMBB.getMBB() != &MBB)
2180b57cec5SDimitry Andric           continue;
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric         // Replace the operand for unsplit successors
2210b57cec5SDimitry Andric         if (!IsEdgeSplit || Succ != &UnsplitSucc) {
2220b57cec5SDimitry Andric           OpMBB.setMBB(&NewMBB);
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric           // We have to continue scanning as there may be multiple entries in
2250b57cec5SDimitry Andric           // the PHI.
2260b57cec5SDimitry Andric           continue;
2270b57cec5SDimitry Andric         }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric         // When we have split the edge append a new successor.
2300b57cec5SDimitry Andric         MI.addOperand(MF, OpV);
2310b57cec5SDimitry Andric         MI.addOperand(MF, MachineOperand::CreateMBB(&NewMBB));
2320b57cec5SDimitry Andric         break;
2330b57cec5SDimitry Andric       }
2340b57cec5SDimitry Andric     }
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   return NewMBB;
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric 
240*0fca6ea1SDimitry Andric enum EFLAGSClobber { NoClobber, EvitableClobber, InevitableClobber };
241*0fca6ea1SDimitry Andric 
getClobberType(const MachineInstr & MI)242*0fca6ea1SDimitry Andric static EFLAGSClobber getClobberType(const MachineInstr &MI) {
243*0fca6ea1SDimitry Andric   const MachineOperand *FlagDef =
244*0fca6ea1SDimitry Andric       MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);
245*0fca6ea1SDimitry Andric   if (!FlagDef)
246*0fca6ea1SDimitry Andric     return NoClobber;
247*0fca6ea1SDimitry Andric   if (FlagDef->isDead() && X86::getNFVariant(MI.getOpcode()))
248*0fca6ea1SDimitry Andric     return EvitableClobber;
249*0fca6ea1SDimitry Andric 
250*0fca6ea1SDimitry Andric   return InevitableClobber;
2512a168f03SDimitry Andric }
2522a168f03SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)2530b57cec5SDimitry Andric bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction &MF) {
2540b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
2550b57cec5SDimitry Andric                     << " **********\n");
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   Subtarget = &MF.getSubtarget<X86Subtarget>();
2580b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
2590b57cec5SDimitry Andric   TII = Subtarget->getInstrInfo();
2600b57cec5SDimitry Andric   TRI = Subtarget->getRegisterInfo();
2610b57cec5SDimitry Andric   PromoteRC = &X86::GR8RegClass;
2620b57cec5SDimitry Andric 
263*0fca6ea1SDimitry Andric   if (MF.empty())
2640b57cec5SDimitry Andric     // Nothing to do for a degenerate empty function...
2650b57cec5SDimitry Andric     return false;
2660b57cec5SDimitry Andric 
267*0fca6ea1SDimitry Andric   if (none_of(MRI->def_instructions(X86::EFLAGS), [](const MachineInstr &MI) {
268*0fca6ea1SDimitry Andric         return MI.getOpcode() == TargetOpcode::COPY;
269*0fca6ea1SDimitry Andric       }))
270*0fca6ea1SDimitry Andric     return false;
271*0fca6ea1SDimitry Andric 
272*0fca6ea1SDimitry Andric   // We change the code, so we don't preserve the dominator tree anyway. If we
273*0fca6ea1SDimitry Andric   // got a valid MDT from the pass manager, use that, otherwise construct one
274*0fca6ea1SDimitry Andric   // now. This is an optimization that avoids unnecessary MDT construction for
275*0fca6ea1SDimitry Andric   // functions that have no flag copies.
276*0fca6ea1SDimitry Andric 
277*0fca6ea1SDimitry Andric   auto MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
278*0fca6ea1SDimitry Andric   std::unique_ptr<MachineDominatorTree> OwnedMDT;
279*0fca6ea1SDimitry Andric   if (MDTWrapper) {
280*0fca6ea1SDimitry Andric     MDT = &MDTWrapper->getDomTree();
281*0fca6ea1SDimitry Andric   } else {
282*0fca6ea1SDimitry Andric     OwnedMDT = std::make_unique<MachineDominatorTree>();
283*0fca6ea1SDimitry Andric     OwnedMDT->getBase().recalculate(MF);
284*0fca6ea1SDimitry Andric     MDT = OwnedMDT.get();
285*0fca6ea1SDimitry Andric   }
286*0fca6ea1SDimitry Andric 
2870b57cec5SDimitry Andric   // Collect the copies in RPO so that when there are chains where a copy is in
2880b57cec5SDimitry Andric   // turn copied again we visit the first one first. This ensures we can find
2890b57cec5SDimitry Andric   // viable locations for testing the original EFLAGS that dominate all the
2900b57cec5SDimitry Andric   // uses across complex CFGs.
291*0fca6ea1SDimitry Andric   SmallSetVector<MachineInstr *, 4> Copies;
2920b57cec5SDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2930b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : RPOT)
2940b57cec5SDimitry Andric     for (MachineInstr &MI : *MBB)
2950b57cec5SDimitry Andric       if (MI.getOpcode() == TargetOpcode::COPY &&
2960b57cec5SDimitry Andric           MI.getOperand(0).getReg() == X86::EFLAGS)
297*0fca6ea1SDimitry Andric         Copies.insert(&MI);
2980b57cec5SDimitry Andric 
299*0fca6ea1SDimitry Andric   // Try to elminate the copys by transform the instructions between copy and
300*0fca6ea1SDimitry Andric   // copydef to the NF (no flags update) variants, e.g.
301*0fca6ea1SDimitry Andric   //
302*0fca6ea1SDimitry Andric   // %1:gr64 = COPY $eflags
303*0fca6ea1SDimitry Andric   // OP1 implicit-def dead $eflags
304*0fca6ea1SDimitry Andric   // $eflags = COPY %1
305*0fca6ea1SDimitry Andric   // OP2 cc, implicit $eflags
306*0fca6ea1SDimitry Andric   //
307*0fca6ea1SDimitry Andric   // ->
308*0fca6ea1SDimitry Andric   //
309*0fca6ea1SDimitry Andric   // OP1_NF
310*0fca6ea1SDimitry Andric   // OP2 implicit $eflags
311*0fca6ea1SDimitry Andric   if (Subtarget->hasNF()) {
312*0fca6ea1SDimitry Andric     SmallSetVector<MachineInstr *, 4> RemovedCopies;
313*0fca6ea1SDimitry Andric     // CopyIIt may be invalidated by removing copies.
314*0fca6ea1SDimitry Andric     auto CopyIIt = Copies.begin(), CopyIEnd = Copies.end();
315*0fca6ea1SDimitry Andric     while (CopyIIt != CopyIEnd) {
316*0fca6ea1SDimitry Andric       auto NCopyIIt = std::next(CopyIIt);
317*0fca6ea1SDimitry Andric       SmallSetVector<MachineInstr *, 4> EvitableClobbers;
318*0fca6ea1SDimitry Andric       MachineInstr *CopyI = *CopyIIt;
319*0fca6ea1SDimitry Andric       MachineOperand &VOp = CopyI->getOperand(1);
320*0fca6ea1SDimitry Andric       MachineInstr *CopyDefI = MRI->getVRegDef(VOp.getReg());
321*0fca6ea1SDimitry Andric       MachineBasicBlock *CopyIMBB = CopyI->getParent();
322*0fca6ea1SDimitry Andric       MachineBasicBlock *CopyDefIMBB = CopyDefI->getParent();
323*0fca6ea1SDimitry Andric       // Walk all basic blocks reachable in depth-first iteration on the inverse
324*0fca6ea1SDimitry Andric       // CFG from CopyIMBB to CopyDefIMBB. These blocks are all the blocks that
325*0fca6ea1SDimitry Andric       // may be executed between the execution of CopyDefIMBB and CopyIMBB. On
326*0fca6ea1SDimitry Andric       // all execution paths, instructions from CopyDefI to CopyI (exclusive)
327*0fca6ea1SDimitry Andric       // has to be NF-convertible if it clobbers flags.
328*0fca6ea1SDimitry Andric       for (auto BI = idf_begin(CopyIMBB), BE = idf_end(CopyDefIMBB); BI != BE;
329*0fca6ea1SDimitry Andric            ++BI) {
330*0fca6ea1SDimitry Andric         MachineBasicBlock *MBB = *BI;
331*0fca6ea1SDimitry Andric         for (auto I = (MBB != CopyDefIMBB)
332*0fca6ea1SDimitry Andric                           ? MBB->begin()
333*0fca6ea1SDimitry Andric                           : std::next(MachineBasicBlock::iterator(CopyDefI)),
334*0fca6ea1SDimitry Andric                   E = (MBB != CopyIMBB) ? MBB->end()
335*0fca6ea1SDimitry Andric                                         : MachineBasicBlock::iterator(CopyI);
336*0fca6ea1SDimitry Andric              I != E; ++I) {
337*0fca6ea1SDimitry Andric           MachineInstr &MI = *I;
338*0fca6ea1SDimitry Andric           EFLAGSClobber ClobberType = getClobberType(MI);
339*0fca6ea1SDimitry Andric           if (ClobberType == NoClobber)
340*0fca6ea1SDimitry Andric             continue;
341*0fca6ea1SDimitry Andric 
342*0fca6ea1SDimitry Andric           if (ClobberType == InevitableClobber)
343*0fca6ea1SDimitry Andric             goto ProcessNextCopyI;
344*0fca6ea1SDimitry Andric 
345*0fca6ea1SDimitry Andric           assert(ClobberType == EvitableClobber && "unexpected workflow");
346*0fca6ea1SDimitry Andric           EvitableClobbers.insert(&MI);
347*0fca6ea1SDimitry Andric         }
348*0fca6ea1SDimitry Andric       }
349*0fca6ea1SDimitry Andric       // Covert evitable clobbers into NF variants and remove the copyies.
350*0fca6ea1SDimitry Andric       RemovedCopies.insert(CopyI);
351*0fca6ea1SDimitry Andric       CopyI->eraseFromParent();
352*0fca6ea1SDimitry Andric       if (MRI->use_nodbg_empty(CopyDefI->getOperand(0).getReg())) {
353*0fca6ea1SDimitry Andric         RemovedCopies.insert(CopyDefI);
354*0fca6ea1SDimitry Andric         CopyDefI->eraseFromParent();
355*0fca6ea1SDimitry Andric       }
356*0fca6ea1SDimitry Andric       ++NumCopiesEliminated;
357*0fca6ea1SDimitry Andric       for (auto *Clobber : EvitableClobbers) {
358*0fca6ea1SDimitry Andric         unsigned NewOpc = X86::getNFVariant(Clobber->getOpcode());
359*0fca6ea1SDimitry Andric         assert(NewOpc && "evitable clobber must have a NF variant");
360*0fca6ea1SDimitry Andric         Clobber->setDesc(TII->get(NewOpc));
361*0fca6ea1SDimitry Andric         Clobber->removeOperand(
362*0fca6ea1SDimitry Andric             Clobber->findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr)
363*0fca6ea1SDimitry Andric                 ->getOperandNo());
364*0fca6ea1SDimitry Andric         ++NumNFsConvertedTo;
365*0fca6ea1SDimitry Andric       }
366*0fca6ea1SDimitry Andric       // Update liveins for basic blocks in the path
367*0fca6ea1SDimitry Andric       for (auto BI = idf_begin(CopyIMBB), BE = idf_end(CopyDefIMBB); BI != BE;
368*0fca6ea1SDimitry Andric            ++BI)
369*0fca6ea1SDimitry Andric         if (*BI != CopyDefIMBB)
370*0fca6ea1SDimitry Andric           BI->addLiveIn(X86::EFLAGS);
371*0fca6ea1SDimitry Andric     ProcessNextCopyI:
372*0fca6ea1SDimitry Andric       CopyIIt = NCopyIIt;
373*0fca6ea1SDimitry Andric     }
374*0fca6ea1SDimitry Andric     Copies.set_subtract(RemovedCopies);
375*0fca6ea1SDimitry Andric   }
376*0fca6ea1SDimitry Andric 
377*0fca6ea1SDimitry Andric   // For the rest of copies that cannot be eliminated by NF transform, we use
378*0fca6ea1SDimitry Andric   // setcc to preserve the flags in GPR32 before OP1, and recheck its value
379*0fca6ea1SDimitry Andric   // before using the flags, e.g.
380*0fca6ea1SDimitry Andric   //
381*0fca6ea1SDimitry Andric   // %1:gr64 = COPY $eflags
382*0fca6ea1SDimitry Andric   // OP1 implicit-def dead $eflags
383*0fca6ea1SDimitry Andric   // $eflags = COPY %1
384*0fca6ea1SDimitry Andric   // OP2 cc, implicit $eflags
385*0fca6ea1SDimitry Andric   //
386*0fca6ea1SDimitry Andric   // ->
387*0fca6ea1SDimitry Andric   //
388*0fca6ea1SDimitry Andric   // %1:gr8 = SETCCr cc, implicit $eflags
389*0fca6ea1SDimitry Andric   // OP1 implicit-def dead $eflags
390*0fca6ea1SDimitry Andric   // TEST8rr %1, %1, implicit-def $eflags
391*0fca6ea1SDimitry Andric   // OP2 ne, implicit $eflags
3920b57cec5SDimitry Andric   for (MachineInstr *CopyI : Copies) {
3930b57cec5SDimitry Andric     MachineBasicBlock &MBB = *CopyI->getParent();
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric     MachineOperand &VOp = CopyI->getOperand(1);
3960b57cec5SDimitry Andric     assert(VOp.isReg() &&
3970b57cec5SDimitry Andric            "The input to the copy for EFLAGS should always be a register!");
3980b57cec5SDimitry Andric     MachineInstr &CopyDefI = *MRI->getVRegDef(VOp.getReg());
3990b57cec5SDimitry Andric     if (CopyDefI.getOpcode() != TargetOpcode::COPY) {
4000b57cec5SDimitry Andric       // FIXME: The big likely candidate here are PHI nodes. We could in theory
4010b57cec5SDimitry Andric       // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
4020b57cec5SDimitry Andric       // enough that it is probably better to change every other part of LLVM
4030b57cec5SDimitry Andric       // to avoid creating them. The issue is that once we have PHIs we won't
4040b57cec5SDimitry Andric       // know which original EFLAGS value we need to capture with our setCCs
4050b57cec5SDimitry Andric       // below. The end result will be computing a complete set of setCCs that
4060b57cec5SDimitry Andric       // we *might* want, computing them in every place where we copy *out* of
4070b57cec5SDimitry Andric       // EFLAGS and then doing SSA formation on all of them to insert necessary
4080b57cec5SDimitry Andric       // PHI nodes and consume those here. Then hoping that somehow we DCE the
4090b57cec5SDimitry Andric       // unnecessary ones. This DCE seems very unlikely to be successful and so
4100b57cec5SDimitry Andric       // we will almost certainly end up with a glut of dead setCC
4110b57cec5SDimitry Andric       // instructions. Until we have a motivating test case and fail to avoid
4120b57cec5SDimitry Andric       // it by changing other parts of LLVM's lowering, we refuse to handle
4130b57cec5SDimitry Andric       // this complex case here.
4140b57cec5SDimitry Andric       LLVM_DEBUG(
4150b57cec5SDimitry Andric           dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
4160b57cec5SDimitry Andric           CopyDefI.dump());
4170b57cec5SDimitry Andric       report_fatal_error(
4180b57cec5SDimitry Andric           "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
4190b57cec5SDimitry Andric     }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric     auto Cleanup = make_scope_exit([&] {
4220b57cec5SDimitry Andric       // All uses of the EFLAGS copy are now rewritten, kill the copy into
4230b57cec5SDimitry Andric       // eflags and if dead the copy from.
4240b57cec5SDimitry Andric       CopyI->eraseFromParent();
4250b57cec5SDimitry Andric       if (MRI->use_empty(CopyDefI.getOperand(0).getReg()))
4260b57cec5SDimitry Andric         CopyDefI.eraseFromParent();
4270b57cec5SDimitry Andric       ++NumCopiesEliminated;
4280b57cec5SDimitry Andric     });
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric     MachineOperand &DOp = CopyI->getOperand(0);
4310b57cec5SDimitry Andric     assert(DOp.isDef() && "Expected register def!");
4320b57cec5SDimitry Andric     assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!");
4330b57cec5SDimitry Andric     if (DOp.isDead())
4340b57cec5SDimitry Andric       continue;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric     MachineBasicBlock *TestMBB = CopyDefI.getParent();
4370b57cec5SDimitry Andric     auto TestPos = CopyDefI.getIterator();
4380b57cec5SDimitry Andric     DebugLoc TestLoc = CopyDefI.getDebugLoc();
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump());
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric     // Walk up across live-in EFLAGS to find where they were actually def'ed.
4430b57cec5SDimitry Andric     //
4440b57cec5SDimitry Andric     // This copy's def may just be part of a region of blocks covered by
4450b57cec5SDimitry Andric     // a single def of EFLAGS and we want to find the top of that region where
4460b57cec5SDimitry Andric     // possible.
4470b57cec5SDimitry Andric     //
4480b57cec5SDimitry Andric     // This is essentially a search for a *candidate* reaching definition
4490b57cec5SDimitry Andric     // location. We don't need to ever find the actual reaching definition here,
4500b57cec5SDimitry Andric     // but we want to walk up the dominator tree to find the highest point which
4510b57cec5SDimitry Andric     // would be viable for such a definition.
4520b57cec5SDimitry Andric     auto HasEFLAGSClobber = [&](MachineBasicBlock::iterator Begin,
4530b57cec5SDimitry Andric                                 MachineBasicBlock::iterator End) {
4540b57cec5SDimitry Andric       // Scan backwards as we expect these to be relatively short and often find
4550b57cec5SDimitry Andric       // a clobber near the end.
4560b57cec5SDimitry Andric       return llvm::any_of(
4570b57cec5SDimitry Andric           llvm::reverse(llvm::make_range(Begin, End)), [&](MachineInstr &MI) {
4580b57cec5SDimitry Andric             // Flag any instruction (other than the copy we are
4590b57cec5SDimitry Andric             // currently rewriting) that defs EFLAGS.
460*0fca6ea1SDimitry Andric             return &MI != CopyI &&
461*0fca6ea1SDimitry Andric                    MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);
4620b57cec5SDimitry Andric           });
4630b57cec5SDimitry Andric     };
4640b57cec5SDimitry Andric     auto HasEFLAGSClobberPath = [&](MachineBasicBlock *BeginMBB,
4650b57cec5SDimitry Andric                                     MachineBasicBlock *EndMBB) {
4660b57cec5SDimitry Andric       assert(MDT->dominates(BeginMBB, EndMBB) &&
4670b57cec5SDimitry Andric              "Only support paths down the dominator tree!");
4680b57cec5SDimitry Andric       SmallPtrSet<MachineBasicBlock *, 4> Visited;
4690b57cec5SDimitry Andric       SmallVector<MachineBasicBlock *, 4> Worklist;
4700b57cec5SDimitry Andric       // We terminate at the beginning. No need to scan it.
4710b57cec5SDimitry Andric       Visited.insert(BeginMBB);
4720b57cec5SDimitry Andric       Worklist.push_back(EndMBB);
4730b57cec5SDimitry Andric       do {
4740b57cec5SDimitry Andric         auto *MBB = Worklist.pop_back_val();
4750b57cec5SDimitry Andric         for (auto *PredMBB : MBB->predecessors()) {
4760b57cec5SDimitry Andric           if (!Visited.insert(PredMBB).second)
4770b57cec5SDimitry Andric             continue;
4780b57cec5SDimitry Andric           if (HasEFLAGSClobber(PredMBB->begin(), PredMBB->end()))
4790b57cec5SDimitry Andric             return true;
4800b57cec5SDimitry Andric           // Enqueue this block to walk its predecessors.
4810b57cec5SDimitry Andric           Worklist.push_back(PredMBB);
4820b57cec5SDimitry Andric         }
4830b57cec5SDimitry Andric       } while (!Worklist.empty());
4840b57cec5SDimitry Andric       // No clobber found along a path from the begin to end.
4850b57cec5SDimitry Andric       return false;
4860b57cec5SDimitry Andric     };
4870b57cec5SDimitry Andric     while (TestMBB->isLiveIn(X86::EFLAGS) && !TestMBB->pred_empty() &&
4880b57cec5SDimitry Andric            !HasEFLAGSClobber(TestMBB->begin(), TestPos)) {
4890b57cec5SDimitry Andric       // Find the nearest common dominator of the predecessors, as
4900b57cec5SDimitry Andric       // that will be the best candidate to hoist into.
4910b57cec5SDimitry Andric       MachineBasicBlock *HoistMBB =
4920b57cec5SDimitry Andric           std::accumulate(std::next(TestMBB->pred_begin()), TestMBB->pred_end(),
4930b57cec5SDimitry Andric                           *TestMBB->pred_begin(),
4940b57cec5SDimitry Andric                           [&](MachineBasicBlock *LHS, MachineBasicBlock *RHS) {
4950b57cec5SDimitry Andric                             return MDT->findNearestCommonDominator(LHS, RHS);
4960b57cec5SDimitry Andric                           });
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric       // Now we need to scan all predecessors that may be reached along paths to
4990b57cec5SDimitry Andric       // the hoist block. A clobber anywhere in any of these blocks the hoist.
5000b57cec5SDimitry Andric       // Note that this even handles loops because we require *no* clobbers.
5010b57cec5SDimitry Andric       if (HasEFLAGSClobberPath(HoistMBB, TestMBB))
5020b57cec5SDimitry Andric         break;
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric       // We also need the terminators to not sneakily clobber flags.
5050b57cec5SDimitry Andric       if (HasEFLAGSClobber(HoistMBB->getFirstTerminator()->getIterator(),
5060b57cec5SDimitry Andric                            HoistMBB->instr_end()))
5070b57cec5SDimitry Andric         break;
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric       // We found a viable location, hoist our test position to it.
5100b57cec5SDimitry Andric       TestMBB = HoistMBB;
5110b57cec5SDimitry Andric       TestPos = TestMBB->getFirstTerminator()->getIterator();
5120b57cec5SDimitry Andric       // Clear the debug location as it would just be confusing after hoisting.
5130b57cec5SDimitry Andric       TestLoc = DebugLoc();
5140b57cec5SDimitry Andric     }
5150b57cec5SDimitry Andric     LLVM_DEBUG({
5160b57cec5SDimitry Andric       auto DefIt = llvm::find_if(
5170b57cec5SDimitry Andric           llvm::reverse(llvm::make_range(TestMBB->instr_begin(), TestPos)),
5180b57cec5SDimitry Andric           [&](MachineInstr &MI) {
519*0fca6ea1SDimitry Andric             return MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr);
5200b57cec5SDimitry Andric           });
5210b57cec5SDimitry Andric       if (DefIt.base() != TestMBB->instr_begin()) {
5220b57cec5SDimitry Andric         dbgs() << "  Using EFLAGS defined by: ";
5230b57cec5SDimitry Andric         DefIt->dump();
5240b57cec5SDimitry Andric       } else {
5250b57cec5SDimitry Andric         dbgs() << "  Using live-in flags for BB:\n";
5260b57cec5SDimitry Andric         TestMBB->dump();
5270b57cec5SDimitry Andric       }
5280b57cec5SDimitry Andric     });
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric     // While rewriting uses, we buffer jumps and rewrite them in a second pass
5310b57cec5SDimitry Andric     // because doing so will perturb the CFG that we are walking to find the
5320b57cec5SDimitry Andric     // uses in the first place.
5330b57cec5SDimitry Andric     SmallVector<MachineInstr *, 4> JmpIs;
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric     // Gather the condition flags that have already been preserved in
5360b57cec5SDimitry Andric     // registers. We do this from scratch each time as we expect there to be
5370b57cec5SDimitry Andric     // very few of them and we expect to not revisit the same copy definition
5380b57cec5SDimitry Andric     // many times. If either of those change sufficiently we could build a map
5390b57cec5SDimitry Andric     // of these up front instead.
5400b57cec5SDimitry Andric     CondRegArray CondRegs = collectCondsInRegs(*TestMBB, TestPos);
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     // Collect the basic blocks we need to scan. Typically this will just be
5430b57cec5SDimitry Andric     // a single basic block but we may have to scan multiple blocks if the
5440b57cec5SDimitry Andric     // EFLAGS copy lives into successors.
5450b57cec5SDimitry Andric     SmallVector<MachineBasicBlock *, 2> Blocks;
5460b57cec5SDimitry Andric     SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;
5470b57cec5SDimitry Andric     Blocks.push_back(&MBB);
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     do {
5500b57cec5SDimitry Andric       MachineBasicBlock &UseMBB = *Blocks.pop_back_val();
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric       // Track when if/when we find a kill of the flags in this block.
5530b57cec5SDimitry Andric       bool FlagsKilled = false;
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric       // In most cases, we walk from the beginning to the end of the block. But
5560b57cec5SDimitry Andric       // when the block is the same block as the copy is from, we will visit it
5570b57cec5SDimitry Andric       // twice. The first time we start from the copy and go to the end. The
5580b57cec5SDimitry Andric       // second time we start from the beginning and go to the copy. This lets
5590b57cec5SDimitry Andric       // us handle copies inside of cycles.
5600b57cec5SDimitry Andric       // FIXME: This loop is *super* confusing. This is at least in part
5610b57cec5SDimitry Andric       // a symptom of all of this routine needing to be refactored into
5620b57cec5SDimitry Andric       // documentable components. Once done, there may be a better way to write
5630b57cec5SDimitry Andric       // this loop.
5640b57cec5SDimitry Andric       for (auto MII = (&UseMBB == &MBB && !VisitedBlocks.count(&UseMBB))
5650b57cec5SDimitry Andric                           ? std::next(CopyI->getIterator())
5660b57cec5SDimitry Andric                           : UseMBB.instr_begin(),
5670b57cec5SDimitry Andric                 MIE = UseMBB.instr_end();
5680b57cec5SDimitry Andric            MII != MIE;) {
5690b57cec5SDimitry Andric         MachineInstr &MI = *MII++;
5700b57cec5SDimitry Andric         // If we are in the original copy block and encounter either the copy
5710b57cec5SDimitry Andric         // def or the copy itself, break so that we don't re-process any part of
5720b57cec5SDimitry Andric         // the block or process the instructions in the range that was copied
5730b57cec5SDimitry Andric         // over.
5740b57cec5SDimitry Andric         if (&MI == CopyI || &MI == &CopyDefI) {
5750b57cec5SDimitry Andric           assert(&UseMBB == &MBB && VisitedBlocks.count(&MBB) &&
5760b57cec5SDimitry Andric                  "Should only encounter these on the second pass over the "
5770b57cec5SDimitry Andric                  "original block.");
5780b57cec5SDimitry Andric           break;
5790b57cec5SDimitry Andric         }
5800b57cec5SDimitry Andric 
581*0fca6ea1SDimitry Andric         MachineOperand *FlagUse =
582*0fca6ea1SDimitry Andric             MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr);
583*0fca6ea1SDimitry Andric         FlagsKilled = MI.modifiesRegister(X86::EFLAGS, TRI);
584*0fca6ea1SDimitry Andric 
585*0fca6ea1SDimitry Andric         if (!FlagUse && FlagsKilled)
5860b57cec5SDimitry Andric           break;
587*0fca6ea1SDimitry Andric         else if (!FlagUse)
5880b57cec5SDimitry Andric           continue;
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Rewriting use: "; MI.dump());
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric         // Check the kill flag before we rewrite as that may change it.
5930b57cec5SDimitry Andric         if (FlagUse->isKill())
5940b57cec5SDimitry Andric           FlagsKilled = true;
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric         // Once we encounter a branch, the rest of the instructions must also be
5970b57cec5SDimitry Andric         // branches. We can't rewrite in place here, so we handle them below.
5980b57cec5SDimitry Andric         //
5990b57cec5SDimitry Andric         // Note that we don't have to handle tail calls here, even conditional
6000b57cec5SDimitry Andric         // tail calls, as those are not introduced into the X86 MI until post-RA
6010b57cec5SDimitry Andric         // branch folding or black placement. As a consequence, we get to deal
6020b57cec5SDimitry Andric         // with the simpler formulation of conditional branches followed by tail
6030b57cec5SDimitry Andric         // calls.
6040b57cec5SDimitry Andric         if (X86::getCondFromBranch(MI) != X86::COND_INVALID) {
6050b57cec5SDimitry Andric           auto JmpIt = MI.getIterator();
6060b57cec5SDimitry Andric           do {
6070b57cec5SDimitry Andric             JmpIs.push_back(&*JmpIt);
6080b57cec5SDimitry Andric             ++JmpIt;
6090b57cec5SDimitry Andric           } while (JmpIt != UseMBB.instr_end() &&
610*0fca6ea1SDimitry Andric                    X86::getCondFromBranch(*JmpIt) != X86::COND_INVALID);
6110b57cec5SDimitry Andric           break;
6120b57cec5SDimitry Andric         }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric         // Otherwise we can just rewrite in-place.
615*0fca6ea1SDimitry Andric         unsigned Opc = MI.getOpcode();
616*0fca6ea1SDimitry Andric         if (Opc == TargetOpcode::COPY) {
617*0fca6ea1SDimitry Andric           // Just replace this copy with the original copy def.
618*0fca6ea1SDimitry Andric           MRI->replaceRegWith(MI.getOperand(0).getReg(),
619*0fca6ea1SDimitry Andric                               CopyDefI.getOperand(0).getReg());
620*0fca6ea1SDimitry Andric           MI.eraseFromParent();
621*0fca6ea1SDimitry Andric         } else if (X86::isSETCC(Opc)) {
622*0fca6ea1SDimitry Andric           rewriteSetCC(*TestMBB, TestPos, TestLoc, MI, CondRegs);
623*0fca6ea1SDimitry Andric         } else if (isArithmeticOp(Opc)) {
624*0fca6ea1SDimitry Andric           rewriteArithmetic(*TestMBB, TestPos, TestLoc, MI, CondRegs);
6250b57cec5SDimitry Andric         } else {
626*0fca6ea1SDimitry Andric           rewriteMI(*TestMBB, TestPos, TestLoc, MI, CondRegs);
6270b57cec5SDimitry Andric         }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric         // If this was the last use of the flags, we're done.
6300b57cec5SDimitry Andric         if (FlagsKilled)
6310b57cec5SDimitry Andric           break;
6320b57cec5SDimitry Andric       }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric       // If the flags were killed, we're done with this block.
6350b57cec5SDimitry Andric       if (FlagsKilled)
6360b57cec5SDimitry Andric         continue;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric       // Otherwise we need to scan successors for ones where the flags live-in
6390b57cec5SDimitry Andric       // and queue those up for processing.
6400b57cec5SDimitry Andric       for (MachineBasicBlock *SuccMBB : UseMBB.successors())
6410b57cec5SDimitry Andric         if (SuccMBB->isLiveIn(X86::EFLAGS) &&
6420b57cec5SDimitry Andric             VisitedBlocks.insert(SuccMBB).second) {
6430b57cec5SDimitry Andric           // We currently don't do any PHI insertion and so we require that the
6440b57cec5SDimitry Andric           // test basic block dominates all of the use basic blocks. Further, we
6450b57cec5SDimitry Andric           // can't have a cycle from the test block back to itself as that would
6460b57cec5SDimitry Andric           // create a cycle requiring a PHI to break it.
6470b57cec5SDimitry Andric           //
6480b57cec5SDimitry Andric           // We could in theory do PHI insertion here if it becomes useful by
6490b57cec5SDimitry Andric           // just taking undef values in along every edge that we don't trace
6500b57cec5SDimitry Andric           // this EFLAGS copy along. This isn't as bad as fully general PHI
6510b57cec5SDimitry Andric           // insertion, but still seems like a great deal of complexity.
6520b57cec5SDimitry Andric           //
6530b57cec5SDimitry Andric           // Because it is theoretically possible that some earlier MI pass or
6540b57cec5SDimitry Andric           // other lowering transformation could induce this to happen, we do
6550b57cec5SDimitry Andric           // a hard check even in non-debug builds here.
6560b57cec5SDimitry Andric           if (SuccMBB == TestMBB || !MDT->dominates(TestMBB, SuccMBB)) {
6570b57cec5SDimitry Andric             LLVM_DEBUG({
6580b57cec5SDimitry Andric               dbgs()
6590b57cec5SDimitry Andric                   << "ERROR: Encountered use that is not dominated by our test "
6600b57cec5SDimitry Andric                      "basic block! Rewriting this would require inserting PHI "
6610b57cec5SDimitry Andric                      "nodes to track the flag state across the CFG.\n\nTest "
6620b57cec5SDimitry Andric                      "block:\n";
6630b57cec5SDimitry Andric               TestMBB->dump();
6640b57cec5SDimitry Andric               dbgs() << "Use block:\n";
6650b57cec5SDimitry Andric               SuccMBB->dump();
6660b57cec5SDimitry Andric             });
6670b57cec5SDimitry Andric             report_fatal_error(
6680b57cec5SDimitry Andric                 "Cannot lower EFLAGS copy when original copy def "
6690b57cec5SDimitry Andric                 "does not dominate all uses.");
6700b57cec5SDimitry Andric           }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric           Blocks.push_back(SuccMBB);
673480093f4SDimitry Andric 
674480093f4SDimitry Andric           // After this, EFLAGS will be recreated before each use.
675480093f4SDimitry Andric           SuccMBB->removeLiveIn(X86::EFLAGS);
6760b57cec5SDimitry Andric         }
6770b57cec5SDimitry Andric     } while (!Blocks.empty());
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric     // Now rewrite the jumps that use the flags. These we handle specially
6800b57cec5SDimitry Andric     // because if there are multiple jumps in a single basic block we'll have
6810b57cec5SDimitry Andric     // to do surgery on the CFG.
6820b57cec5SDimitry Andric     MachineBasicBlock *LastJmpMBB = nullptr;
6830b57cec5SDimitry Andric     for (MachineInstr *JmpI : JmpIs) {
6840b57cec5SDimitry Andric       // Past the first jump within a basic block we need to split the blocks
6850b57cec5SDimitry Andric       // apart.
6860b57cec5SDimitry Andric       if (JmpI->getParent() == LastJmpMBB)
6870b57cec5SDimitry Andric         splitBlock(*JmpI->getParent(), *JmpI, *TII);
6880b57cec5SDimitry Andric       else
6890b57cec5SDimitry Andric         LastJmpMBB = JmpI->getParent();
6900b57cec5SDimitry Andric 
691*0fca6ea1SDimitry Andric       rewriteMI(*TestMBB, TestPos, TestLoc, *JmpI, CondRegs);
6920b57cec5SDimitry Andric     }
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric     // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
6950b57cec5SDimitry Andric     // the copy's def operand is itself a kill.
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric #ifndef NDEBUG
6990b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF)
7000b57cec5SDimitry Andric     for (MachineInstr &MI : MBB)
7010b57cec5SDimitry Andric       if (MI.getOpcode() == TargetOpcode::COPY &&
7020b57cec5SDimitry Andric           (MI.getOperand(0).getReg() == X86::EFLAGS ||
7030b57cec5SDimitry Andric            MI.getOperand(1).getReg() == X86::EFLAGS)) {
7040b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
7050b57cec5SDimitry Andric                    MI.dump());
7060b57cec5SDimitry Andric         llvm_unreachable("Unlowered EFLAGS copy!");
7070b57cec5SDimitry Andric       }
7080b57cec5SDimitry Andric #endif
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   return true;
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric /// Collect any conditions that have already been set in registers so that we
7140b57cec5SDimitry Andric /// can re-use them rather than adding duplicates.
collectCondsInRegs(MachineBasicBlock & MBB,MachineBasicBlock::iterator TestPos)7150b57cec5SDimitry Andric CondRegArray X86FlagsCopyLoweringPass::collectCondsInRegs(
7160b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator TestPos) {
7170b57cec5SDimitry Andric   CondRegArray CondRegs = {};
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   // Scan backwards across the range of instructions with live EFLAGS.
7200b57cec5SDimitry Andric   for (MachineInstr &MI :
7210b57cec5SDimitry Andric        llvm::reverse(llvm::make_range(MBB.begin(), TestPos))) {
7220b57cec5SDimitry Andric     X86::CondCode Cond = X86::getCondFromSETCC(MI);
7238bcb0991SDimitry Andric     if (Cond != X86::COND_INVALID && !MI.mayStore() &&
724e8d8bef9SDimitry Andric         MI.getOperand(0).isReg() && MI.getOperand(0).getReg().isVirtual()) {
7250b57cec5SDimitry Andric       assert(MI.getOperand(0).isDef() &&
7260b57cec5SDimitry Andric              "A non-storing SETcc should always define a register!");
7270b57cec5SDimitry Andric       CondRegs[Cond] = MI.getOperand(0).getReg();
7280b57cec5SDimitry Andric     }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     // Stop scanning when we see the first definition of the EFLAGS as prior to
7310b57cec5SDimitry Andric     // this we would potentially capture the wrong flag state.
732*0fca6ea1SDimitry Andric     if (MI.findRegisterDefOperand(X86::EFLAGS, /*TRI=*/nullptr))
7330b57cec5SDimitry Andric       break;
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric   return CondRegs;
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
promoteCondToReg(MachineBasicBlock & TestMBB,MachineBasicBlock::iterator TestPos,const DebugLoc & TestLoc,X86::CondCode Cond)738e8d8bef9SDimitry Andric Register X86FlagsCopyLoweringPass::promoteCondToReg(
7390b57cec5SDimitry Andric     MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
740fe6060f1SDimitry Andric     const DebugLoc &TestLoc, X86::CondCode Cond) {
7418bcb0991SDimitry Andric   Register Reg = MRI->createVirtualRegister(PromoteRC);
742*0fca6ea1SDimitry Andric   auto SetI = BuildMI(TestMBB, TestPos, TestLoc, TII->get(X86::SETCCr), Reg)
743*0fca6ea1SDimitry Andric                   .addImm(Cond);
7440b57cec5SDimitry Andric   (void)SetI;
7450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    save cond: "; SetI->dump());
7460b57cec5SDimitry Andric   ++NumSetCCsInserted;
7470b57cec5SDimitry Andric   return Reg;
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric 
getCondOrInverseInReg(MachineBasicBlock & TestMBB,MachineBasicBlock::iterator TestPos,const DebugLoc & TestLoc,X86::CondCode Cond,CondRegArray & CondRegs)7500b57cec5SDimitry Andric std::pair<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
7510b57cec5SDimitry Andric     MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
752fe6060f1SDimitry Andric     const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {
7530b57cec5SDimitry Andric   unsigned &CondReg = CondRegs[Cond];
7540b57cec5SDimitry Andric   unsigned &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(Cond)];
7550b57cec5SDimitry Andric   if (!CondReg && !InvCondReg)
7560b57cec5SDimitry Andric     CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   if (CondReg)
7590b57cec5SDimitry Andric     return {CondReg, false};
7600b57cec5SDimitry Andric   else
7610b57cec5SDimitry Andric     return {InvCondReg, true};
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
insertTest(MachineBasicBlock & MBB,MachineBasicBlock::iterator Pos,const DebugLoc & Loc,unsigned Reg)7640b57cec5SDimitry Andric void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock &MBB,
7650b57cec5SDimitry Andric                                           MachineBasicBlock::iterator Pos,
766fe6060f1SDimitry Andric                                           const DebugLoc &Loc, unsigned Reg) {
7670b57cec5SDimitry Andric   auto TestI =
7680b57cec5SDimitry Andric       BuildMI(MBB, Pos, Loc, TII->get(X86::TEST8rr)).addReg(Reg).addReg(Reg);
7690b57cec5SDimitry Andric   (void)TestI;
7700b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    test cond: "; TestI->dump());
7710b57cec5SDimitry Andric   ++NumTestsInserted;
7720b57cec5SDimitry Andric }
7730b57cec5SDimitry Andric 
rewriteSetCC(MachineBasicBlock & MBB,MachineBasicBlock::iterator Pos,const DebugLoc & Loc,MachineInstr & MI,CondRegArray & CondRegs)774*0fca6ea1SDimitry Andric void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock &MBB,
775*0fca6ea1SDimitry Andric                                             MachineBasicBlock::iterator Pos,
776*0fca6ea1SDimitry Andric                                             const DebugLoc &Loc,
777*0fca6ea1SDimitry Andric                                             MachineInstr &MI,
7780b57cec5SDimitry Andric                                             CondRegArray &CondRegs) {
779*0fca6ea1SDimitry Andric   X86::CondCode Cond = X86::getCondFromSETCC(MI);
780*0fca6ea1SDimitry Andric   // Note that we can't usefully rewrite this to the inverse without complex
781*0fca6ea1SDimitry Andric   // analysis of the users of the setCC. Largely we rely on duplicates which
782*0fca6ea1SDimitry Andric   // could have been avoided already being avoided here.
783*0fca6ea1SDimitry Andric   unsigned &CondReg = CondRegs[Cond];
784*0fca6ea1SDimitry Andric   if (!CondReg)
785*0fca6ea1SDimitry Andric     CondReg = promoteCondToReg(MBB, Pos, Loc, Cond);
7860b57cec5SDimitry Andric 
787*0fca6ea1SDimitry Andric   // Rewriting a register def is trivial: we just replace the register and
788*0fca6ea1SDimitry Andric   // remove the setcc.
789*0fca6ea1SDimitry Andric   if (!MI.mayStore()) {
790*0fca6ea1SDimitry Andric     assert(MI.getOperand(0).isReg() &&
791*0fca6ea1SDimitry Andric            "Cannot have a non-register defined operand to SETcc!");
792*0fca6ea1SDimitry Andric     Register OldReg = MI.getOperand(0).getReg();
793*0fca6ea1SDimitry Andric     // Drop Kill flags on the old register before replacing. CondReg may have
794*0fca6ea1SDimitry Andric     // a longer live range.
795*0fca6ea1SDimitry Andric     MRI->clearKillFlags(OldReg);
796*0fca6ea1SDimitry Andric     MRI->replaceRegWith(OldReg, CondReg);
797*0fca6ea1SDimitry Andric     MI.eraseFromParent();
798*0fca6ea1SDimitry Andric     return;
799*0fca6ea1SDimitry Andric   }
800*0fca6ea1SDimitry Andric 
801*0fca6ea1SDimitry Andric   // Otherwise, we need to emit a store.
802*0fca6ea1SDimitry Andric   auto MIB = BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
803*0fca6ea1SDimitry Andric                      TII->get(X86::MOV8mr));
804*0fca6ea1SDimitry Andric   // Copy the address operands.
805*0fca6ea1SDimitry Andric   for (int i = 0; i < X86::AddrNumOperands; ++i)
806*0fca6ea1SDimitry Andric     MIB.add(MI.getOperand(i));
807*0fca6ea1SDimitry Andric 
808*0fca6ea1SDimitry Andric   MIB.addReg(CondReg);
809*0fca6ea1SDimitry Andric   MIB.setMemRefs(MI.memoperands());
810*0fca6ea1SDimitry Andric   MI.eraseFromParent();
811*0fca6ea1SDimitry Andric }
812*0fca6ea1SDimitry Andric 
rewriteArithmetic(MachineBasicBlock & MBB,MachineBasicBlock::iterator Pos,const DebugLoc & Loc,MachineInstr & MI,CondRegArray & CondRegs)813*0fca6ea1SDimitry Andric void X86FlagsCopyLoweringPass::rewriteArithmetic(
814*0fca6ea1SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
815*0fca6ea1SDimitry Andric     const DebugLoc &Loc, MachineInstr &MI, CondRegArray &CondRegs) {
816*0fca6ea1SDimitry Andric   // Arithmetic is either reading CF or OF.
817*0fca6ea1SDimitry Andric   X86::CondCode Cond = X86::COND_B; // CF == 1
8180b57cec5SDimitry Andric   // The addend to use to reset CF or OF when added to the flag value.
8190b57cec5SDimitry Andric   // Set up an addend that when one is added will need a carry due to not
8200b57cec5SDimitry Andric   // having a higher bit available.
821*0fca6ea1SDimitry Andric   int Addend = 255;
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   // Now get a register that contains the value of the flag input to the
8240b57cec5SDimitry Andric   // arithmetic. We require exactly this flag to simplify the arithmetic
8250b57cec5SDimitry Andric   // required to materialize it back into the flag.
8260b57cec5SDimitry Andric   unsigned &CondReg = CondRegs[Cond];
8270b57cec5SDimitry Andric   if (!CondReg)
828*0fca6ea1SDimitry Andric     CondReg = promoteCondToReg(MBB, Pos, Loc, Cond);
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   // Insert an instruction that will set the flag back to the desired value.
8318bcb0991SDimitry Andric   Register TmpReg = MRI->createVirtualRegister(PromoteRC);
8320b57cec5SDimitry Andric   auto AddI =
833*0fca6ea1SDimitry Andric       BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
834*0fca6ea1SDimitry Andric               TII->get(Subtarget->hasNDD() ? X86::ADD8ri_ND : X86::ADD8ri))
8350b57cec5SDimitry Andric           .addDef(TmpReg, RegState::Dead)
8360b57cec5SDimitry Andric           .addReg(CondReg)
8370b57cec5SDimitry Andric           .addImm(Addend);
8380b57cec5SDimitry Andric   (void)AddI;
8390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    add cond: "; AddI->dump());
8400b57cec5SDimitry Andric   ++NumAddsInserted;
841*0fca6ea1SDimitry Andric   MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);
8420b57cec5SDimitry Andric }
8430b57cec5SDimitry Andric 
getImplicitCondFromMI(unsigned Opc)844*0fca6ea1SDimitry Andric static X86::CondCode getImplicitCondFromMI(unsigned Opc) {
845*0fca6ea1SDimitry Andric #define FROM_TO(A, B)                                                          \
846*0fca6ea1SDimitry Andric   case X86::CMOV##A##_Fp32:                                                    \
847*0fca6ea1SDimitry Andric   case X86::CMOV##A##_Fp64:                                                    \
848*0fca6ea1SDimitry Andric   case X86::CMOV##A##_Fp80:                                                    \
849*0fca6ea1SDimitry Andric     return X86::COND_##B;
850*0fca6ea1SDimitry Andric 
851*0fca6ea1SDimitry Andric   switch (Opc) {
852*0fca6ea1SDimitry Andric   default:
853*0fca6ea1SDimitry Andric     return X86::COND_INVALID;
854*0fca6ea1SDimitry Andric     FROM_TO(B, B)
855*0fca6ea1SDimitry Andric     FROM_TO(E, E)
856*0fca6ea1SDimitry Andric     FROM_TO(P, P)
857*0fca6ea1SDimitry Andric     FROM_TO(BE, BE)
858*0fca6ea1SDimitry Andric     FROM_TO(NB, AE)
859*0fca6ea1SDimitry Andric     FROM_TO(NE, NE)
860*0fca6ea1SDimitry Andric     FROM_TO(NP, NP)
861*0fca6ea1SDimitry Andric     FROM_TO(NBE, A)
862*0fca6ea1SDimitry Andric   }
863*0fca6ea1SDimitry Andric #undef FROM_TO
864*0fca6ea1SDimitry Andric }
865*0fca6ea1SDimitry Andric 
getOpcodeWithCC(unsigned Opc,X86::CondCode CC)866*0fca6ea1SDimitry Andric static unsigned getOpcodeWithCC(unsigned Opc, X86::CondCode CC) {
867*0fca6ea1SDimitry Andric   assert((CC == X86::COND_E || CC == X86::COND_NE) && "Unexpected CC");
868*0fca6ea1SDimitry Andric #define CASE(A)                                                                \
869*0fca6ea1SDimitry Andric   case X86::CMOVB_##A:                                                         \
870*0fca6ea1SDimitry Andric   case X86::CMOVE_##A:                                                         \
871*0fca6ea1SDimitry Andric   case X86::CMOVP_##A:                                                         \
872*0fca6ea1SDimitry Andric   case X86::CMOVBE_##A:                                                        \
873*0fca6ea1SDimitry Andric   case X86::CMOVNB_##A:                                                        \
874*0fca6ea1SDimitry Andric   case X86::CMOVNE_##A:                                                        \
875*0fca6ea1SDimitry Andric   case X86::CMOVNP_##A:                                                        \
876*0fca6ea1SDimitry Andric   case X86::CMOVNBE_##A:                                                       \
877*0fca6ea1SDimitry Andric     return (CC == X86::COND_E) ? X86::CMOVE_##A : X86::CMOVNE_##A;
878*0fca6ea1SDimitry Andric   switch (Opc) {
879*0fca6ea1SDimitry Andric   default:
880*0fca6ea1SDimitry Andric     llvm_unreachable("Unexpected opcode");
881*0fca6ea1SDimitry Andric     CASE(Fp32)
882*0fca6ea1SDimitry Andric     CASE(Fp64)
883*0fca6ea1SDimitry Andric     CASE(Fp80)
884*0fca6ea1SDimitry Andric   }
885*0fca6ea1SDimitry Andric #undef CASE
886*0fca6ea1SDimitry Andric }
887*0fca6ea1SDimitry Andric 
rewriteMI(MachineBasicBlock & MBB,MachineBasicBlock::iterator Pos,const DebugLoc & Loc,MachineInstr & MI,CondRegArray & CondRegs)888*0fca6ea1SDimitry Andric void X86FlagsCopyLoweringPass::rewriteMI(MachineBasicBlock &MBB,
889*0fca6ea1SDimitry Andric                                          MachineBasicBlock::iterator Pos,
890*0fca6ea1SDimitry Andric                                          const DebugLoc &Loc, MachineInstr &MI,
8910b57cec5SDimitry Andric                                          CondRegArray &CondRegs) {
8920b57cec5SDimitry Andric   // First get the register containing this specific condition.
893*0fca6ea1SDimitry Andric   bool IsImplicitCC = false;
894*0fca6ea1SDimitry Andric   X86::CondCode CC = X86::getCondFromMI(MI);
895*0fca6ea1SDimitry Andric   if (CC == X86::COND_INVALID) {
896*0fca6ea1SDimitry Andric     CC = getImplicitCondFromMI(MI.getOpcode());
897*0fca6ea1SDimitry Andric     IsImplicitCC = true;
898*0fca6ea1SDimitry Andric   }
899*0fca6ea1SDimitry Andric   assert(CC != X86::COND_INVALID && "Unknown EFLAG user!");
9000b57cec5SDimitry Andric   unsigned CondReg;
9010b57cec5SDimitry Andric   bool Inverted;
9020b57cec5SDimitry Andric   std::tie(CondReg, Inverted) =
903*0fca6ea1SDimitry Andric       getCondOrInverseInReg(MBB, Pos, Loc, CC, CondRegs);
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   // Insert a direct test of the saved register.
906*0fca6ea1SDimitry Andric   insertTest(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(), CondReg);
9070b57cec5SDimitry Andric 
908*0fca6ea1SDimitry Andric   // Rewrite the instruction to use the !ZF flag from the test, and then kill
909*0fca6ea1SDimitry Andric   // its use of the flags afterward.
910*0fca6ea1SDimitry Andric   X86::CondCode NewCC = Inverted ? X86::COND_E : X86::COND_NE;
911*0fca6ea1SDimitry Andric   if (IsImplicitCC)
912*0fca6ea1SDimitry Andric     MI.setDesc(TII->get(getOpcodeWithCC(MI.getOpcode(), NewCC)));
913*0fca6ea1SDimitry Andric   else
914*0fca6ea1SDimitry Andric     MI.getOperand(MI.getDesc().getNumOperands() - 1).setImm(NewCC);
9150b57cec5SDimitry Andric 
916*0fca6ea1SDimitry Andric   MI.findRegisterUseOperand(X86::EFLAGS, /*TRI=*/nullptr)->setIsKill(true);
917*0fca6ea1SDimitry Andric   LLVM_DEBUG(dbgs() << "    fixed instruction: "; MI.dump());
9180b57cec5SDimitry Andric }
919