Path: blob/main/contrib/llvm-project/llvm/lib/Target/X86/X86FloatingPoint.cpp
35269 views
//===-- X86FloatingPoint.cpp - Floating point Reg -> Stack converter ------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the pass which converts floating point instructions from9// pseudo registers into register stack instructions. This pass uses live10// variable information to indicate where the FPn registers are used and their11// lifetimes.12//13// The x87 hardware tracks liveness of the stack registers, so it is necessary14// to implement exact liveness tracking between basic blocks. The CFG edges are15// partitioned into bundles where the same FP registers must be live in16// identical stack positions. Instructions are inserted at the end of each basic17// block to rearrange the live registers to match the outgoing bundle.18//19// This approach avoids splitting critical edges at the potential cost of more20// live register shuffling instructions when critical edges are present.21//22//===----------------------------------------------------------------------===//2324#include "X86.h"25#include "X86InstrInfo.h"26#include "llvm/ADT/DepthFirstIterator.h"27#include "llvm/ADT/STLExtras.h"28#include "llvm/ADT/SmallSet.h"29#include "llvm/ADT/SmallVector.h"30#include "llvm/ADT/Statistic.h"31#include "llvm/CodeGen/EdgeBundles.h"32#include "llvm/CodeGen/LiveRegUnits.h"33#include "llvm/CodeGen/MachineFunctionPass.h"34#include "llvm/CodeGen/MachineInstrBuilder.h"35#include "llvm/CodeGen/MachineRegisterInfo.h"36#include "llvm/CodeGen/Passes.h"37#include "llvm/CodeGen/TargetInstrInfo.h"38#include "llvm/CodeGen/TargetSubtargetInfo.h"39#include "llvm/Config/llvm-config.h"40#include "llvm/IR/InlineAsm.h"41#include "llvm/InitializePasses.h"42#include "llvm/Support/Debug.h"43#include "llvm/Support/ErrorHandling.h"44#include "llvm/Support/raw_ostream.h"45#include "llvm/Target/TargetMachine.h"46#include <algorithm>47#include <bitset>48using namespace llvm;4950#define DEBUG_TYPE "x86-codegen"5152STATISTIC(NumFXCH, "Number of fxch instructions inserted");53STATISTIC(NumFP , "Number of floating point instructions");5455namespace {56const unsigned ScratchFPReg = 7;5758struct FPS : public MachineFunctionPass {59static char ID;60FPS() : MachineFunctionPass(ID) {61// This is really only to keep valgrind quiet.62// The logic in isLive() is too much for it.63memset(Stack, 0, sizeof(Stack));64memset(RegMap, 0, sizeof(RegMap));65}6667void getAnalysisUsage(AnalysisUsage &AU) const override {68AU.setPreservesCFG();69AU.addRequired<EdgeBundles>();70AU.addPreservedID(MachineLoopInfoID);71AU.addPreservedID(MachineDominatorsID);72MachineFunctionPass::getAnalysisUsage(AU);73}7475bool runOnMachineFunction(MachineFunction &MF) override;7677MachineFunctionProperties getRequiredProperties() const override {78return MachineFunctionProperties().set(79MachineFunctionProperties::Property::NoVRegs);80}8182StringRef getPassName() const override { return "X86 FP Stackifier"; }8384private:85const TargetInstrInfo *TII = nullptr; // Machine instruction info.8687// Two CFG edges are related if they leave the same block, or enter the same88// block. The transitive closure of an edge under this relation is a89// LiveBundle. It represents a set of CFG edges where the live FP stack90// registers must be allocated identically in the x87 stack.91//92// A LiveBundle is usually all the edges leaving a block, or all the edges93// entering a block, but it can contain more edges if critical edges are94// present.95//96// The set of live FP registers in a LiveBundle is calculated by bundleCFG,97// but the exact mapping of FP registers to stack slots is fixed later.98struct LiveBundle {99// Bit mask of live FP registers. Bit 0 = FP0, bit 1 = FP1, &c.100unsigned Mask = 0;101102// Number of pre-assigned live registers in FixStack. This is 0 when the103// stack order has not yet been fixed.104unsigned FixCount = 0;105106// Assigned stack order for live-in registers.107// FixStack[i] == getStackEntry(i) for all i < FixCount.108unsigned char FixStack[8];109110LiveBundle() = default;111112// Have the live registers been assigned a stack order yet?113bool isFixed() const { return !Mask || FixCount; }114};115116// Numbered LiveBundle structs. LiveBundles[0] is used for all CFG edges117// with no live FP registers.118SmallVector<LiveBundle, 8> LiveBundles;119120// The edge bundle analysis provides indices into the LiveBundles vector.121EdgeBundles *Bundles = nullptr;122123// Return a bitmask of FP registers in block's live-in list.124static unsigned calcLiveInMask(MachineBasicBlock *MBB, bool RemoveFPs) {125unsigned Mask = 0;126for (MachineBasicBlock::livein_iterator I = MBB->livein_begin();127I != MBB->livein_end(); ) {128MCPhysReg Reg = I->PhysReg;129static_assert(X86::FP6 - X86::FP0 == 6, "sequential regnums");130if (Reg >= X86::FP0 && Reg <= X86::FP6) {131Mask |= 1 << (Reg - X86::FP0);132if (RemoveFPs) {133I = MBB->removeLiveIn(I);134continue;135}136}137++I;138}139return Mask;140}141142// Partition all the CFG edges into LiveBundles.143void bundleCFGRecomputeKillFlags(MachineFunction &MF);144145MachineBasicBlock *MBB = nullptr; // Current basic block146147// The hardware keeps track of how many FP registers are live, so we have148// to model that exactly. Usually, each live register corresponds to an149// FP<n> register, but when dealing with calls, returns, and inline150// assembly, it is sometimes necessary to have live scratch registers.151unsigned Stack[8]; // FP<n> Registers in each stack slot...152unsigned StackTop = 0; // The current top of the FP stack.153154enum {155NumFPRegs = 8 // Including scratch pseudo-registers.156};157158// For each live FP<n> register, point to its Stack[] entry.159// The first entries correspond to FP0-FP6, the rest are scratch registers160// used when we need slightly different live registers than what the161// register allocator thinks.162unsigned RegMap[NumFPRegs];163164// Set up our stack model to match the incoming registers to MBB.165void setupBlockStack();166167// Shuffle live registers to match the expectations of successor blocks.168void finishBlockStack();169170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)171void dumpStack() const {172dbgs() << "Stack contents:";173for (unsigned i = 0; i != StackTop; ++i) {174dbgs() << " FP" << Stack[i];175assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");176}177}178#endif179180/// getSlot - Return the stack slot number a particular register number is181/// in.182unsigned getSlot(unsigned RegNo) const {183assert(RegNo < NumFPRegs && "Regno out of range!");184return RegMap[RegNo];185}186187/// isLive - Is RegNo currently live in the stack?188bool isLive(unsigned RegNo) const {189unsigned Slot = getSlot(RegNo);190return Slot < StackTop && Stack[Slot] == RegNo;191}192193/// getStackEntry - Return the X86::FP<n> register in register ST(i).194unsigned getStackEntry(unsigned STi) const {195if (STi >= StackTop)196report_fatal_error("Access past stack top!");197return Stack[StackTop-1-STi];198}199200/// getSTReg - Return the X86::ST(i) register which contains the specified201/// FP<RegNo> register.202unsigned getSTReg(unsigned RegNo) const {203return StackTop - 1 - getSlot(RegNo) + X86::ST0;204}205206// pushReg - Push the specified FP<n> register onto the stack.207void pushReg(unsigned Reg) {208assert(Reg < NumFPRegs && "Register number out of range!");209if (StackTop >= 8)210report_fatal_error("Stack overflow!");211Stack[StackTop] = Reg;212RegMap[Reg] = StackTop++;213}214215// popReg - Pop a register from the stack.216void popReg() {217if (StackTop == 0)218report_fatal_error("Cannot pop empty stack!");219RegMap[Stack[--StackTop]] = ~0; // Update state220}221222bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }223void moveToTop(unsigned RegNo, MachineBasicBlock::iterator I) {224DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();225if (isAtTop(RegNo)) return;226227unsigned STReg = getSTReg(RegNo);228unsigned RegOnTop = getStackEntry(0);229230// Swap the slots the regs are in.231std::swap(RegMap[RegNo], RegMap[RegOnTop]);232233// Swap stack slot contents.234if (RegMap[RegOnTop] >= StackTop)235report_fatal_error("Access past stack top!");236std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);237238// Emit an fxch to update the runtime processors version of the state.239BuildMI(*MBB, I, dl, TII->get(X86::XCH_F)).addReg(STReg);240++NumFXCH;241}242243void duplicateToTop(unsigned RegNo, unsigned AsReg,244MachineBasicBlock::iterator I) {245DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();246unsigned STReg = getSTReg(RegNo);247pushReg(AsReg); // New register on top of stack248249BuildMI(*MBB, I, dl, TII->get(X86::LD_Frr)).addReg(STReg);250}251252/// popStackAfter - Pop the current value off of the top of the FP stack253/// after the specified instruction.254void popStackAfter(MachineBasicBlock::iterator &I);255256/// freeStackSlotAfter - Free the specified register from the register257/// stack, so that it is no longer in a register. If the register is258/// currently at the top of the stack, we just pop the current instruction,259/// otherwise we store the current top-of-stack into the specified slot,260/// then pop the top of stack.261void freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned Reg);262263/// freeStackSlotBefore - Just the pop, no folding. Return the inserted264/// instruction.265MachineBasicBlock::iterator266freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo);267268/// Adjust the live registers to be the set in Mask.269void adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I);270271/// Shuffle the top FixCount stack entries such that FP reg FixStack[0] is272/// st(0), FP reg FixStack[1] is st(1) etc.273void shuffleStackTop(const unsigned char *FixStack, unsigned FixCount,274MachineBasicBlock::iterator I);275276bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);277278void handleCall(MachineBasicBlock::iterator &I);279void handleReturn(MachineBasicBlock::iterator &I);280void handleZeroArgFP(MachineBasicBlock::iterator &I);281void handleOneArgFP(MachineBasicBlock::iterator &I);282void handleOneArgFPRW(MachineBasicBlock::iterator &I);283void handleTwoArgFP(MachineBasicBlock::iterator &I);284void handleCompareFP(MachineBasicBlock::iterator &I);285void handleCondMovFP(MachineBasicBlock::iterator &I);286void handleSpecialFP(MachineBasicBlock::iterator &I);287288// Check if a COPY instruction is using FP registers.289static bool isFPCopy(MachineInstr &MI) {290Register DstReg = MI.getOperand(0).getReg();291Register SrcReg = MI.getOperand(1).getReg();292293return X86::RFP80RegClass.contains(DstReg) ||294X86::RFP80RegClass.contains(SrcReg);295}296297void setKillFlags(MachineBasicBlock &MBB) const;298};299}300301char FPS::ID = 0;302303INITIALIZE_PASS_BEGIN(FPS, DEBUG_TYPE, "X86 FP Stackifier",304false, false)305INITIALIZE_PASS_DEPENDENCY(EdgeBundles)306INITIALIZE_PASS_END(FPS, DEBUG_TYPE, "X86 FP Stackifier",307false, false)308309FunctionPass *llvm::createX86FloatingPointStackifierPass() { return new FPS(); }310311/// getFPReg - Return the X86::FPx register number for the specified operand.312/// For example, this returns 3 for X86::FP3.313static unsigned getFPReg(const MachineOperand &MO) {314assert(MO.isReg() && "Expected an FP register!");315Register Reg = MO.getReg();316assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");317return Reg - X86::FP0;318}319320/// runOnMachineFunction - Loop over all of the basic blocks, transforming FP321/// register references into FP stack references.322///323bool FPS::runOnMachineFunction(MachineFunction &MF) {324// We only need to run this pass if there are any FP registers used in this325// function. If it is all integer, there is nothing for us to do!326bool FPIsUsed = false;327328static_assert(X86::FP6 == X86::FP0+6, "Register enums aren't sorted right!");329const MachineRegisterInfo &MRI = MF.getRegInfo();330for (unsigned i = 0; i <= 6; ++i)331if (!MRI.reg_nodbg_empty(X86::FP0 + i)) {332FPIsUsed = true;333break;334}335336// Early exit.337if (!FPIsUsed) return false;338339Bundles = &getAnalysis<EdgeBundles>();340TII = MF.getSubtarget().getInstrInfo();341342// Prepare cross-MBB liveness.343bundleCFGRecomputeKillFlags(MF);344345StackTop = 0;346347// Process the function in depth first order so that we process at least one348// of the predecessors for every reachable block in the function.349df_iterator_default_set<MachineBasicBlock*> Processed;350MachineBasicBlock *Entry = &MF.front();351352LiveBundle &Bundle =353LiveBundles[Bundles->getBundle(Entry->getNumber(), false)];354355// In regcall convention, some FP registers may not be passed through356// the stack, so they will need to be assigned to the stack first357if ((Entry->getParent()->getFunction().getCallingConv() ==358CallingConv::X86_RegCall) && (Bundle.Mask && !Bundle.FixCount)) {359// In the register calling convention, up to one FP argument could be360// saved in the first FP register.361// If bundle.mask is non-zero and Bundle.FixCount is zero, it means362// that the FP registers contain arguments.363// The actual value is passed in FP0.364// Here we fix the stack and mark FP0 as pre-assigned register.365assert((Bundle.Mask & 0xFE) == 0 &&366"Only FP0 could be passed as an argument");367Bundle.FixCount = 1;368Bundle.FixStack[0] = 0;369}370371bool Changed = false;372for (MachineBasicBlock *BB : depth_first_ext(Entry, Processed))373Changed |= processBasicBlock(MF, *BB);374375// Process any unreachable blocks in arbitrary order now.376if (MF.size() != Processed.size())377for (MachineBasicBlock &BB : MF)378if (Processed.insert(&BB).second)379Changed |= processBasicBlock(MF, BB);380381LiveBundles.clear();382383return Changed;384}385386/// bundleCFG - Scan all the basic blocks to determine consistent live-in and387/// live-out sets for the FP registers. Consistent means that the set of388/// registers live-out from a block is identical to the live-in set of all389/// successors. This is not enforced by the normal live-in lists since390/// registers may be implicitly defined, or not used by all successors.391void FPS::bundleCFGRecomputeKillFlags(MachineFunction &MF) {392assert(LiveBundles.empty() && "Stale data in LiveBundles");393LiveBundles.resize(Bundles->getNumBundles());394395// Gather the actual live-in masks for all MBBs.396for (MachineBasicBlock &MBB : MF) {397setKillFlags(MBB);398399const unsigned Mask = calcLiveInMask(&MBB, false);400if (!Mask)401continue;402// Update MBB ingoing bundle mask.403LiveBundles[Bundles->getBundle(MBB.getNumber(), false)].Mask |= Mask;404}405}406407/// processBasicBlock - Loop over all of the instructions in the basic block,408/// transforming FP instructions into their stack form.409///410bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {411bool Changed = false;412MBB = &BB;413414setupBlockStack();415416for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {417MachineInstr &MI = *I;418uint64_t Flags = MI.getDesc().TSFlags;419420unsigned FPInstClass = Flags & X86II::FPTypeMask;421if (MI.isInlineAsm())422FPInstClass = X86II::SpecialFP;423424if (MI.isCopy() && isFPCopy(MI))425FPInstClass = X86II::SpecialFP;426427if (MI.isImplicitDef() &&428X86::RFP80RegClass.contains(MI.getOperand(0).getReg()))429FPInstClass = X86II::SpecialFP;430431if (MI.isCall())432FPInstClass = X86II::SpecialFP;433434if (FPInstClass == X86II::NotFP)435continue; // Efficiently ignore non-fp insts!436437MachineInstr *PrevMI = nullptr;438if (I != BB.begin())439PrevMI = &*std::prev(I);440441++NumFP; // Keep track of # of pseudo instrs442LLVM_DEBUG(dbgs() << "\nFPInst:\t" << MI);443444// Get dead variables list now because the MI pointer may be deleted as part445// of processing!446SmallVector<unsigned, 8> DeadRegs;447for (const MachineOperand &MO : MI.operands())448if (MO.isReg() && MO.isDead())449DeadRegs.push_back(MO.getReg());450451switch (FPInstClass) {452case X86II::ZeroArgFP: handleZeroArgFP(I); break;453case X86II::OneArgFP: handleOneArgFP(I); break; // fstp ST(0)454case X86II::OneArgFPRW: handleOneArgFPRW(I); break; // ST(0) = fsqrt(ST(0))455case X86II::TwoArgFP: handleTwoArgFP(I); break;456case X86II::CompareFP: handleCompareFP(I); break;457case X86II::CondMovFP: handleCondMovFP(I); break;458case X86II::SpecialFP: handleSpecialFP(I); break;459default: llvm_unreachable("Unknown FP Type!");460}461462// Check to see if any of the values defined by this instruction are dead463// after definition. If so, pop them.464for (unsigned Reg : DeadRegs) {465// Check if Reg is live on the stack. An inline-asm register operand that466// is in the clobber list and marked dead might not be live on the stack.467static_assert(X86::FP7 - X86::FP0 == 7, "sequential FP regnumbers");468if (Reg >= X86::FP0 && Reg <= X86::FP6 && isLive(Reg-X86::FP0)) {469LLVM_DEBUG(dbgs() << "Register FP#" << Reg - X86::FP0 << " is dead!\n");470freeStackSlotAfter(I, Reg-X86::FP0);471}472}473474// Print out all of the instructions expanded to if -debug475LLVM_DEBUG({476MachineBasicBlock::iterator PrevI = PrevMI;477if (I == PrevI) {478dbgs() << "Just deleted pseudo instruction\n";479} else {480MachineBasicBlock::iterator Start = I;481// Rewind to first instruction newly inserted.482while (Start != BB.begin() && std::prev(Start) != PrevI)483--Start;484dbgs() << "Inserted instructions:\n\t";485Start->print(dbgs());486while (++Start != std::next(I)) {487}488}489dumpStack();490});491(void)PrevMI;492493Changed = true;494}495496finishBlockStack();497498return Changed;499}500501/// setupBlockStack - Use the live bundles to set up our model of the stack502/// to match predecessors' live out stack.503void FPS::setupBlockStack() {504LLVM_DEBUG(dbgs() << "\nSetting up live-ins for " << printMBBReference(*MBB)505<< " derived from " << MBB->getName() << ".\n");506StackTop = 0;507// Get the live-in bundle for MBB.508const LiveBundle &Bundle =509LiveBundles[Bundles->getBundle(MBB->getNumber(), false)];510511if (!Bundle.Mask) {512LLVM_DEBUG(dbgs() << "Block has no FP live-ins.\n");513return;514}515516// Depth-first iteration should ensure that we always have an assigned stack.517assert(Bundle.isFixed() && "Reached block before any predecessors");518519// Push the fixed live-in registers.520for (unsigned i = Bundle.FixCount; i > 0; --i) {521LLVM_DEBUG(dbgs() << "Live-in st(" << (i - 1) << "): %fp"522<< unsigned(Bundle.FixStack[i - 1]) << '\n');523pushReg(Bundle.FixStack[i-1]);524}525526// Kill off unwanted live-ins. This can happen with a critical edge.527// FIXME: We could keep these live registers around as zombies. They may need528// to be revived at the end of a short block. It might save a few instrs.529unsigned Mask = calcLiveInMask(MBB, /*RemoveFPs=*/true);530adjustLiveRegs(Mask, MBB->begin());531LLVM_DEBUG(MBB->dump());532}533534/// finishBlockStack - Revive live-outs that are implicitly defined out of535/// MBB. Shuffle live registers to match the expected fixed stack of any536/// predecessors, and ensure that all predecessors are expecting the same537/// stack.538void FPS::finishBlockStack() {539// The RET handling below takes care of return blocks for us.540if (MBB->succ_empty())541return;542543LLVM_DEBUG(dbgs() << "Setting up live-outs for " << printMBBReference(*MBB)544<< " derived from " << MBB->getName() << ".\n");545546// Get MBB's live-out bundle.547unsigned BundleIdx = Bundles->getBundle(MBB->getNumber(), true);548LiveBundle &Bundle = LiveBundles[BundleIdx];549550// We may need to kill and define some registers to match successors.551// FIXME: This can probably be combined with the shuffle below.552MachineBasicBlock::iterator Term = MBB->getFirstTerminator();553adjustLiveRegs(Bundle.Mask, Term);554555if (!Bundle.Mask) {556LLVM_DEBUG(dbgs() << "No live-outs.\n");557return;558}559560// Has the stack order been fixed yet?561LLVM_DEBUG(dbgs() << "LB#" << BundleIdx << ": ");562if (Bundle.isFixed()) {563LLVM_DEBUG(dbgs() << "Shuffling stack to match.\n");564shuffleStackTop(Bundle.FixStack, Bundle.FixCount, Term);565} else {566// Not fixed yet, we get to choose.567LLVM_DEBUG(dbgs() << "Fixing stack order now.\n");568Bundle.FixCount = StackTop;569for (unsigned i = 0; i < StackTop; ++i)570Bundle.FixStack[i] = getStackEntry(i);571}572}573574575//===----------------------------------------------------------------------===//576// Efficient Lookup Table Support577//===----------------------------------------------------------------------===//578579namespace {580struct TableEntry {581uint16_t from;582uint16_t to;583bool operator<(const TableEntry &TE) const { return from < TE.from; }584friend bool operator<(const TableEntry &TE, unsigned V) {585return TE.from < V;586}587friend bool LLVM_ATTRIBUTE_UNUSED operator<(unsigned V,588const TableEntry &TE) {589return V < TE.from;590}591};592}593594static int Lookup(ArrayRef<TableEntry> Table, unsigned Opcode) {595const TableEntry *I = llvm::lower_bound(Table, Opcode);596if (I != Table.end() && I->from == Opcode)597return I->to;598return -1;599}600601#ifdef NDEBUG602#define ASSERT_SORTED(TABLE)603#else604#define ASSERT_SORTED(TABLE) \605{ \606static std::atomic<bool> TABLE##Checked(false); \607if (!TABLE##Checked.load(std::memory_order_relaxed)) { \608assert(is_sorted(TABLE) && \609"All lookup tables must be sorted for efficient access!"); \610TABLE##Checked.store(true, std::memory_order_relaxed); \611} \612}613#endif614615//===----------------------------------------------------------------------===//616// Register File -> Register Stack Mapping Methods617//===----------------------------------------------------------------------===//618619// OpcodeTable - Sorted map of register instructions to their stack version.620// The first element is an register file pseudo instruction, the second is the621// concrete X86 instruction which uses the register stack.622//623static const TableEntry OpcodeTable[] = {624{ X86::ABS_Fp32 , X86::ABS_F },625{ X86::ABS_Fp64 , X86::ABS_F },626{ X86::ABS_Fp80 , X86::ABS_F },627{ X86::ADD_Fp32m , X86::ADD_F32m },628{ X86::ADD_Fp64m , X86::ADD_F64m },629{ X86::ADD_Fp64m32 , X86::ADD_F32m },630{ X86::ADD_Fp80m32 , X86::ADD_F32m },631{ X86::ADD_Fp80m64 , X86::ADD_F64m },632{ X86::ADD_FpI16m32 , X86::ADD_FI16m },633{ X86::ADD_FpI16m64 , X86::ADD_FI16m },634{ X86::ADD_FpI16m80 , X86::ADD_FI16m },635{ X86::ADD_FpI32m32 , X86::ADD_FI32m },636{ X86::ADD_FpI32m64 , X86::ADD_FI32m },637{ X86::ADD_FpI32m80 , X86::ADD_FI32m },638{ X86::CHS_Fp32 , X86::CHS_F },639{ X86::CHS_Fp64 , X86::CHS_F },640{ X86::CHS_Fp80 , X86::CHS_F },641{ X86::CMOVBE_Fp32 , X86::CMOVBE_F },642{ X86::CMOVBE_Fp64 , X86::CMOVBE_F },643{ X86::CMOVBE_Fp80 , X86::CMOVBE_F },644{ X86::CMOVB_Fp32 , X86::CMOVB_F },645{ X86::CMOVB_Fp64 , X86::CMOVB_F },646{ X86::CMOVB_Fp80 , X86::CMOVB_F },647{ X86::CMOVE_Fp32 , X86::CMOVE_F },648{ X86::CMOVE_Fp64 , X86::CMOVE_F },649{ X86::CMOVE_Fp80 , X86::CMOVE_F },650{ X86::CMOVNBE_Fp32 , X86::CMOVNBE_F },651{ X86::CMOVNBE_Fp64 , X86::CMOVNBE_F },652{ X86::CMOVNBE_Fp80 , X86::CMOVNBE_F },653{ X86::CMOVNB_Fp32 , X86::CMOVNB_F },654{ X86::CMOVNB_Fp64 , X86::CMOVNB_F },655{ X86::CMOVNB_Fp80 , X86::CMOVNB_F },656{ X86::CMOVNE_Fp32 , X86::CMOVNE_F },657{ X86::CMOVNE_Fp64 , X86::CMOVNE_F },658{ X86::CMOVNE_Fp80 , X86::CMOVNE_F },659{ X86::CMOVNP_Fp32 , X86::CMOVNP_F },660{ X86::CMOVNP_Fp64 , X86::CMOVNP_F },661{ X86::CMOVNP_Fp80 , X86::CMOVNP_F },662{ X86::CMOVP_Fp32 , X86::CMOVP_F },663{ X86::CMOVP_Fp64 , X86::CMOVP_F },664{ X86::CMOVP_Fp80 , X86::CMOVP_F },665{ X86::COM_FpIr32 , X86::COM_FIr },666{ X86::COM_FpIr64 , X86::COM_FIr },667{ X86::COM_FpIr80 , X86::COM_FIr },668{ X86::COM_Fpr32 , X86::COM_FST0r },669{ X86::COM_Fpr64 , X86::COM_FST0r },670{ X86::COM_Fpr80 , X86::COM_FST0r },671{ X86::DIVR_Fp32m , X86::DIVR_F32m },672{ X86::DIVR_Fp64m , X86::DIVR_F64m },673{ X86::DIVR_Fp64m32 , X86::DIVR_F32m },674{ X86::DIVR_Fp80m32 , X86::DIVR_F32m },675{ X86::DIVR_Fp80m64 , X86::DIVR_F64m },676{ X86::DIVR_FpI16m32, X86::DIVR_FI16m},677{ X86::DIVR_FpI16m64, X86::DIVR_FI16m},678{ X86::DIVR_FpI16m80, X86::DIVR_FI16m},679{ X86::DIVR_FpI32m32, X86::DIVR_FI32m},680{ X86::DIVR_FpI32m64, X86::DIVR_FI32m},681{ X86::DIVR_FpI32m80, X86::DIVR_FI32m},682{ X86::DIV_Fp32m , X86::DIV_F32m },683{ X86::DIV_Fp64m , X86::DIV_F64m },684{ X86::DIV_Fp64m32 , X86::DIV_F32m },685{ X86::DIV_Fp80m32 , X86::DIV_F32m },686{ X86::DIV_Fp80m64 , X86::DIV_F64m },687{ X86::DIV_FpI16m32 , X86::DIV_FI16m },688{ X86::DIV_FpI16m64 , X86::DIV_FI16m },689{ X86::DIV_FpI16m80 , X86::DIV_FI16m },690{ X86::DIV_FpI32m32 , X86::DIV_FI32m },691{ X86::DIV_FpI32m64 , X86::DIV_FI32m },692{ X86::DIV_FpI32m80 , X86::DIV_FI32m },693{ X86::ILD_Fp16m32 , X86::ILD_F16m },694{ X86::ILD_Fp16m64 , X86::ILD_F16m },695{ X86::ILD_Fp16m80 , X86::ILD_F16m },696{ X86::ILD_Fp32m32 , X86::ILD_F32m },697{ X86::ILD_Fp32m64 , X86::ILD_F32m },698{ X86::ILD_Fp32m80 , X86::ILD_F32m },699{ X86::ILD_Fp64m32 , X86::ILD_F64m },700{ X86::ILD_Fp64m64 , X86::ILD_F64m },701{ X86::ILD_Fp64m80 , X86::ILD_F64m },702{ X86::ISTT_Fp16m32 , X86::ISTT_FP16m},703{ X86::ISTT_Fp16m64 , X86::ISTT_FP16m},704{ X86::ISTT_Fp16m80 , X86::ISTT_FP16m},705{ X86::ISTT_Fp32m32 , X86::ISTT_FP32m},706{ X86::ISTT_Fp32m64 , X86::ISTT_FP32m},707{ X86::ISTT_Fp32m80 , X86::ISTT_FP32m},708{ X86::ISTT_Fp64m32 , X86::ISTT_FP64m},709{ X86::ISTT_Fp64m64 , X86::ISTT_FP64m},710{ X86::ISTT_Fp64m80 , X86::ISTT_FP64m},711{ X86::IST_Fp16m32 , X86::IST_F16m },712{ X86::IST_Fp16m64 , X86::IST_F16m },713{ X86::IST_Fp16m80 , X86::IST_F16m },714{ X86::IST_Fp32m32 , X86::IST_F32m },715{ X86::IST_Fp32m64 , X86::IST_F32m },716{ X86::IST_Fp32m80 , X86::IST_F32m },717{ X86::IST_Fp64m32 , X86::IST_FP64m },718{ X86::IST_Fp64m64 , X86::IST_FP64m },719{ X86::IST_Fp64m80 , X86::IST_FP64m },720{ X86::LD_Fp032 , X86::LD_F0 },721{ X86::LD_Fp064 , X86::LD_F0 },722{ X86::LD_Fp080 , X86::LD_F0 },723{ X86::LD_Fp132 , X86::LD_F1 },724{ X86::LD_Fp164 , X86::LD_F1 },725{ X86::LD_Fp180 , X86::LD_F1 },726{ X86::LD_Fp32m , X86::LD_F32m },727{ X86::LD_Fp32m64 , X86::LD_F32m },728{ X86::LD_Fp32m80 , X86::LD_F32m },729{ X86::LD_Fp64m , X86::LD_F64m },730{ X86::LD_Fp64m80 , X86::LD_F64m },731{ X86::LD_Fp80m , X86::LD_F80m },732{ X86::MUL_Fp32m , X86::MUL_F32m },733{ X86::MUL_Fp64m , X86::MUL_F64m },734{ X86::MUL_Fp64m32 , X86::MUL_F32m },735{ X86::MUL_Fp80m32 , X86::MUL_F32m },736{ X86::MUL_Fp80m64 , X86::MUL_F64m },737{ X86::MUL_FpI16m32 , X86::MUL_FI16m },738{ X86::MUL_FpI16m64 , X86::MUL_FI16m },739{ X86::MUL_FpI16m80 , X86::MUL_FI16m },740{ X86::MUL_FpI32m32 , X86::MUL_FI32m },741{ X86::MUL_FpI32m64 , X86::MUL_FI32m },742{ X86::MUL_FpI32m80 , X86::MUL_FI32m },743{ X86::SQRT_Fp32 , X86::SQRT_F },744{ X86::SQRT_Fp64 , X86::SQRT_F },745{ X86::SQRT_Fp80 , X86::SQRT_F },746{ X86::ST_Fp32m , X86::ST_F32m },747{ X86::ST_Fp64m , X86::ST_F64m },748{ X86::ST_Fp64m32 , X86::ST_F32m },749{ X86::ST_Fp80m32 , X86::ST_F32m },750{ X86::ST_Fp80m64 , X86::ST_F64m },751{ X86::ST_FpP80m , X86::ST_FP80m },752{ X86::SUBR_Fp32m , X86::SUBR_F32m },753{ X86::SUBR_Fp64m , X86::SUBR_F64m },754{ X86::SUBR_Fp64m32 , X86::SUBR_F32m },755{ X86::SUBR_Fp80m32 , X86::SUBR_F32m },756{ X86::SUBR_Fp80m64 , X86::SUBR_F64m },757{ X86::SUBR_FpI16m32, X86::SUBR_FI16m},758{ X86::SUBR_FpI16m64, X86::SUBR_FI16m},759{ X86::SUBR_FpI16m80, X86::SUBR_FI16m},760{ X86::SUBR_FpI32m32, X86::SUBR_FI32m},761{ X86::SUBR_FpI32m64, X86::SUBR_FI32m},762{ X86::SUBR_FpI32m80, X86::SUBR_FI32m},763{ X86::SUB_Fp32m , X86::SUB_F32m },764{ X86::SUB_Fp64m , X86::SUB_F64m },765{ X86::SUB_Fp64m32 , X86::SUB_F32m },766{ X86::SUB_Fp80m32 , X86::SUB_F32m },767{ X86::SUB_Fp80m64 , X86::SUB_F64m },768{ X86::SUB_FpI16m32 , X86::SUB_FI16m },769{ X86::SUB_FpI16m64 , X86::SUB_FI16m },770{ X86::SUB_FpI16m80 , X86::SUB_FI16m },771{ X86::SUB_FpI32m32 , X86::SUB_FI32m },772{ X86::SUB_FpI32m64 , X86::SUB_FI32m },773{ X86::SUB_FpI32m80 , X86::SUB_FI32m },774{ X86::TST_Fp32 , X86::TST_F },775{ X86::TST_Fp64 , X86::TST_F },776{ X86::TST_Fp80 , X86::TST_F },777{ X86::UCOM_FpIr32 , X86::UCOM_FIr },778{ X86::UCOM_FpIr64 , X86::UCOM_FIr },779{ X86::UCOM_FpIr80 , X86::UCOM_FIr },780{ X86::UCOM_Fpr32 , X86::UCOM_Fr },781{ X86::UCOM_Fpr64 , X86::UCOM_Fr },782{ X86::UCOM_Fpr80 , X86::UCOM_Fr },783{ X86::XAM_Fp32 , X86::XAM_F },784{ X86::XAM_Fp64 , X86::XAM_F },785{ X86::XAM_Fp80 , X86::XAM_F },786};787788static unsigned getConcreteOpcode(unsigned Opcode) {789ASSERT_SORTED(OpcodeTable);790int Opc = Lookup(OpcodeTable, Opcode);791assert(Opc != -1 && "FP Stack instruction not in OpcodeTable!");792return Opc;793}794795//===----------------------------------------------------------------------===//796// Helper Methods797//===----------------------------------------------------------------------===//798799// PopTable - Sorted map of instructions to their popping version. The first800// element is an instruction, the second is the version which pops.801//802static const TableEntry PopTable[] = {803{ X86::ADD_FrST0 , X86::ADD_FPrST0 },804805{ X86::COMP_FST0r, X86::FCOMPP },806{ X86::COM_FIr , X86::COM_FIPr },807{ X86::COM_FST0r , X86::COMP_FST0r },808809{ X86::DIVR_FrST0, X86::DIVR_FPrST0 },810{ X86::DIV_FrST0 , X86::DIV_FPrST0 },811812{ X86::IST_F16m , X86::IST_FP16m },813{ X86::IST_F32m , X86::IST_FP32m },814815{ X86::MUL_FrST0 , X86::MUL_FPrST0 },816817{ X86::ST_F32m , X86::ST_FP32m },818{ X86::ST_F64m , X86::ST_FP64m },819{ X86::ST_Frr , X86::ST_FPrr },820821{ X86::SUBR_FrST0, X86::SUBR_FPrST0 },822{ X86::SUB_FrST0 , X86::SUB_FPrST0 },823824{ X86::UCOM_FIr , X86::UCOM_FIPr },825826{ X86::UCOM_FPr , X86::UCOM_FPPr },827{ X86::UCOM_Fr , X86::UCOM_FPr },828};829830static bool doesInstructionSetFPSW(MachineInstr &MI) {831if (const MachineOperand *MO =832MI.findRegisterDefOperand(X86::FPSW, /*TRI=*/nullptr))833if (!MO->isDead())834return true;835return false;836}837838static MachineBasicBlock::iterator839getNextFPInstruction(MachineBasicBlock::iterator I) {840MachineBasicBlock &MBB = *I->getParent();841while (++I != MBB.end()) {842MachineInstr &MI = *I;843if (X86::isX87Instruction(MI))844return I;845}846return MBB.end();847}848849/// popStackAfter - Pop the current value off of the top of the FP stack after850/// the specified instruction. This attempts to be sneaky and combine the pop851/// into the instruction itself if possible. The iterator is left pointing to852/// the last instruction, be it a new pop instruction inserted, or the old853/// instruction if it was modified in place.854///855void FPS::popStackAfter(MachineBasicBlock::iterator &I) {856MachineInstr &MI = *I;857const DebugLoc &dl = MI.getDebugLoc();858ASSERT_SORTED(PopTable);859860popReg();861862// Check to see if there is a popping version of this instruction...863int Opcode = Lookup(PopTable, I->getOpcode());864if (Opcode != -1) {865I->setDesc(TII->get(Opcode));866if (Opcode == X86::FCOMPP || Opcode == X86::UCOM_FPPr)867I->removeOperand(0);868MI.dropDebugNumber();869} else { // Insert an explicit pop870// If this instruction sets FPSW, which is read in following instruction,871// insert pop after that reader.872if (doesInstructionSetFPSW(MI)) {873MachineBasicBlock &MBB = *MI.getParent();874MachineBasicBlock::iterator Next = getNextFPInstruction(I);875if (Next != MBB.end() && Next->readsRegister(X86::FPSW, /*TRI=*/nullptr))876I = Next;877}878I = BuildMI(*MBB, ++I, dl, TII->get(X86::ST_FPrr)).addReg(X86::ST0);879}880}881882/// freeStackSlotAfter - Free the specified register from the register stack, so883/// that it is no longer in a register. If the register is currently at the top884/// of the stack, we just pop the current instruction, otherwise we store the885/// current top-of-stack into the specified slot, then pop the top of stack.886void FPS::freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned FPRegNo) {887if (getStackEntry(0) == FPRegNo) { // already at the top of stack? easy.888popStackAfter(I);889return;890}891892// Otherwise, store the top of stack into the dead slot, killing the operand893// without having to add in an explicit xchg then pop.894//895I = freeStackSlotBefore(++I, FPRegNo);896}897898/// freeStackSlotBefore - Free the specified register without trying any899/// folding.900MachineBasicBlock::iterator901FPS::freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo) {902unsigned STReg = getSTReg(FPRegNo);903unsigned OldSlot = getSlot(FPRegNo);904unsigned TopReg = Stack[StackTop-1];905Stack[OldSlot] = TopReg;906RegMap[TopReg] = OldSlot;907RegMap[FPRegNo] = ~0;908Stack[--StackTop] = ~0;909return BuildMI(*MBB, I, DebugLoc(), TII->get(X86::ST_FPrr))910.addReg(STReg)911.getInstr();912}913914/// adjustLiveRegs - Kill and revive registers such that exactly the FP915/// registers with a bit in Mask are live.916void FPS::adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I) {917unsigned Defs = Mask;918unsigned Kills = 0;919for (unsigned i = 0; i < StackTop; ++i) {920unsigned RegNo = Stack[i];921if (!(Defs & (1 << RegNo)))922// This register is live, but we don't want it.923Kills |= (1 << RegNo);924else925// We don't need to imp-def this live register.926Defs &= ~(1 << RegNo);927}928assert((Kills & Defs) == 0 && "Register needs killing and def'ing?");929930// Produce implicit-defs for free by using killed registers.931while (Kills && Defs) {932unsigned KReg = llvm::countr_zero(Kills);933unsigned DReg = llvm::countr_zero(Defs);934LLVM_DEBUG(dbgs() << "Renaming %fp" << KReg << " as imp %fp" << DReg935<< "\n");936std::swap(Stack[getSlot(KReg)], Stack[getSlot(DReg)]);937std::swap(RegMap[KReg], RegMap[DReg]);938Kills &= ~(1 << KReg);939Defs &= ~(1 << DReg);940}941942// Kill registers by popping.943if (Kills && I != MBB->begin()) {944MachineBasicBlock::iterator I2 = std::prev(I);945while (StackTop) {946unsigned KReg = getStackEntry(0);947if (!(Kills & (1 << KReg)))948break;949LLVM_DEBUG(dbgs() << "Popping %fp" << KReg << "\n");950popStackAfter(I2);951Kills &= ~(1 << KReg);952}953}954955// Manually kill the rest.956while (Kills) {957unsigned KReg = llvm::countr_zero(Kills);958LLVM_DEBUG(dbgs() << "Killing %fp" << KReg << "\n");959freeStackSlotBefore(I, KReg);960Kills &= ~(1 << KReg);961}962963// Load zeros for all the imp-defs.964while(Defs) {965unsigned DReg = llvm::countr_zero(Defs);966LLVM_DEBUG(dbgs() << "Defining %fp" << DReg << " as 0\n");967BuildMI(*MBB, I, DebugLoc(), TII->get(X86::LD_F0));968pushReg(DReg);969Defs &= ~(1 << DReg);970}971972// Now we should have the correct registers live.973LLVM_DEBUG(dumpStack());974assert(StackTop == (unsigned)llvm::popcount(Mask) && "Live count mismatch");975}976977/// shuffleStackTop - emit fxch instructions before I to shuffle the top978/// FixCount entries into the order given by FixStack.979/// FIXME: Is there a better algorithm than insertion sort?980void FPS::shuffleStackTop(const unsigned char *FixStack,981unsigned FixCount,982MachineBasicBlock::iterator I) {983// Move items into place, starting from the desired stack bottom.984while (FixCount--) {985// Old register at position FixCount.986unsigned OldReg = getStackEntry(FixCount);987// Desired register at position FixCount.988unsigned Reg = FixStack[FixCount];989if (Reg == OldReg)990continue;991// (Reg st0) (OldReg st0) = (Reg OldReg st0)992moveToTop(Reg, I);993if (FixCount > 0)994moveToTop(OldReg, I);995}996LLVM_DEBUG(dumpStack());997}9989991000//===----------------------------------------------------------------------===//1001// Instruction transformation implementation1002//===----------------------------------------------------------------------===//10031004void FPS::handleCall(MachineBasicBlock::iterator &I) {1005MachineInstr &MI = *I;1006unsigned STReturns = 0;10071008bool ClobbersFPStack = false;1009for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {1010MachineOperand &Op = MI.getOperand(i);1011// Check if this call clobbers the FP stack.1012// is sufficient.1013if (Op.isRegMask()) {1014bool ClobbersFP0 = Op.clobbersPhysReg(X86::FP0);1015#ifndef NDEBUG1016static_assert(X86::FP7 - X86::FP0 == 7, "sequential FP regnumbers");1017for (unsigned i = 1; i != 8; ++i)1018assert(Op.clobbersPhysReg(X86::FP0 + i) == ClobbersFP0 &&1019"Inconsistent FP register clobber");1020#endif10211022if (ClobbersFP0)1023ClobbersFPStack = true;1024}10251026if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)1027continue;10281029assert(Op.isImplicit() && "Expected implicit def/use");10301031if (Op.isDef())1032STReturns |= 1 << getFPReg(Op);10331034// Remove the operand so that later passes don't see it.1035MI.removeOperand(i);1036--i;1037--e;1038}10391040// Most calls should have a regmask that clobbers the FP registers. If it1041// isn't present then the register allocator didn't spill the FP registers1042// so they are still on the stack.1043assert((ClobbersFPStack || STReturns == 0) &&1044"ST returns without FP stack clobber");1045if (!ClobbersFPStack)1046return;10471048unsigned N = llvm::countr_one(STReturns);10491050// FP registers used for function return must be consecutive starting at1051// FP01052assert(STReturns == 0 || (isMask_32(STReturns) && N <= 2));10531054// Reset the FP Stack - It is required because of possible leftovers from1055// passed arguments. The caller should assume that the FP stack is1056// returned empty (unless the callee returns values on FP stack).1057while (StackTop > 0)1058popReg();10591060for (unsigned I = 0; I < N; ++I)1061pushReg(N - I - 1);10621063// If this call has been modified, drop all variable values defined by it.1064// We can't track them once they've been stackified.1065if (STReturns)1066I->dropDebugNumber();1067}10681069/// If RET has an FP register use operand, pass the first one in ST(0) and1070/// the second one in ST(1).1071void FPS::handleReturn(MachineBasicBlock::iterator &I) {1072MachineInstr &MI = *I;10731074// Find the register operands.1075unsigned FirstFPRegOp = ~0U, SecondFPRegOp = ~0U;1076unsigned LiveMask = 0;10771078for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {1079MachineOperand &Op = MI.getOperand(i);1080if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)1081continue;1082// FP Register uses must be kills unless there are two uses of the same1083// register, in which case only one will be a kill.1084assert(Op.isUse() &&1085(Op.isKill() || // Marked kill.1086getFPReg(Op) == FirstFPRegOp || // Second instance.1087MI.killsRegister(Op.getReg(),1088/*TRI=*/nullptr)) && // Later use is marked kill.1089"Ret only defs operands, and values aren't live beyond it");10901091if (FirstFPRegOp == ~0U)1092FirstFPRegOp = getFPReg(Op);1093else {1094assert(SecondFPRegOp == ~0U && "More than two fp operands!");1095SecondFPRegOp = getFPReg(Op);1096}1097LiveMask |= (1 << getFPReg(Op));10981099// Remove the operand so that later passes don't see it.1100MI.removeOperand(i);1101--i;1102--e;1103}11041105// We may have been carrying spurious live-ins, so make sure only the1106// returned registers are left live.1107adjustLiveRegs(LiveMask, MI);1108if (!LiveMask) return; // Quick check to see if any are possible.11091110// There are only four possibilities here:1111// 1) we are returning a single FP value. In this case, it has to be in1112// ST(0) already, so just declare success by removing the value from the1113// FP Stack.1114if (SecondFPRegOp == ~0U) {1115// Assert that the top of stack contains the right FP register.1116assert(StackTop == 1 && FirstFPRegOp == getStackEntry(0) &&1117"Top of stack not the right register for RET!");11181119// Ok, everything is good, mark the value as not being on the stack1120// anymore so that our assertion about the stack being empty at end of1121// block doesn't fire.1122StackTop = 0;1123return;1124}11251126// Otherwise, we are returning two values:1127// 2) If returning the same value for both, we only have one thing in the FP1128// stack. Consider: RET FP1, FP11129if (StackTop == 1) {1130assert(FirstFPRegOp == SecondFPRegOp && FirstFPRegOp == getStackEntry(0)&&1131"Stack misconfiguration for RET!");11321133// Duplicate the TOS so that we return it twice. Just pick some other FPx1134// register to hold it.1135unsigned NewReg = ScratchFPReg;1136duplicateToTop(FirstFPRegOp, NewReg, MI);1137FirstFPRegOp = NewReg;1138}11391140/// Okay we know we have two different FPx operands now:1141assert(StackTop == 2 && "Must have two values live!");11421143/// 3) If SecondFPRegOp is currently in ST(0) and FirstFPRegOp is currently1144/// in ST(1). In this case, emit an fxch.1145if (getStackEntry(0) == SecondFPRegOp) {1146assert(getStackEntry(1) == FirstFPRegOp && "Unknown regs live");1147moveToTop(FirstFPRegOp, MI);1148}11491150/// 4) Finally, FirstFPRegOp must be in ST(0) and SecondFPRegOp must be in1151/// ST(1). Just remove both from our understanding of the stack and return.1152assert(getStackEntry(0) == FirstFPRegOp && "Unknown regs live");1153assert(getStackEntry(1) == SecondFPRegOp && "Unknown regs live");1154StackTop = 0;1155}11561157/// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>1158///1159void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {1160MachineInstr &MI = *I;1161unsigned DestReg = getFPReg(MI.getOperand(0));11621163// Change from the pseudo instruction to the concrete instruction.1164MI.removeOperand(0); // Remove the explicit ST(0) operand1165MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));1166MI.addOperand(1167MachineOperand::CreateReg(X86::ST0, /*isDef*/ true, /*isImp*/ true));11681169// Result gets pushed on the stack.1170pushReg(DestReg);11711172MI.dropDebugNumber();1173}11741175/// handleOneArgFP - fst <mem>, ST(0)1176///1177void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {1178MachineInstr &MI = *I;1179unsigned NumOps = MI.getDesc().getNumOperands();1180assert((NumOps == X86::AddrNumOperands + 1 || NumOps == 1) &&1181"Can only handle fst* & ftst instructions!");11821183// Is this the last use of the source register?1184unsigned Reg = getFPReg(MI.getOperand(NumOps - 1));1185bool KillsSrc = MI.killsRegister(X86::FP0 + Reg, /*TRI=*/nullptr);11861187// FISTP64m is strange because there isn't a non-popping versions.1188// If we have one _and_ we don't want to pop the operand, duplicate the value1189// on the stack instead of moving it. This ensure that popping the value is1190// always ok.1191// Ditto FISTTP16m, FISTTP32m, FISTTP64m, ST_FpP80m.1192//1193if (!KillsSrc && (MI.getOpcode() == X86::IST_Fp64m32 ||1194MI.getOpcode() == X86::ISTT_Fp16m32 ||1195MI.getOpcode() == X86::ISTT_Fp32m32 ||1196MI.getOpcode() == X86::ISTT_Fp64m32 ||1197MI.getOpcode() == X86::IST_Fp64m64 ||1198MI.getOpcode() == X86::ISTT_Fp16m64 ||1199MI.getOpcode() == X86::ISTT_Fp32m64 ||1200MI.getOpcode() == X86::ISTT_Fp64m64 ||1201MI.getOpcode() == X86::IST_Fp64m80 ||1202MI.getOpcode() == X86::ISTT_Fp16m80 ||1203MI.getOpcode() == X86::ISTT_Fp32m80 ||1204MI.getOpcode() == X86::ISTT_Fp64m80 ||1205MI.getOpcode() == X86::ST_FpP80m)) {1206duplicateToTop(Reg, ScratchFPReg, I);1207} else {1208moveToTop(Reg, I); // Move to the top of the stack...1209}12101211// Convert from the pseudo instruction to the concrete instruction.1212MI.removeOperand(NumOps - 1); // Remove explicit ST(0) operand1213MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));1214MI.addOperand(1215MachineOperand::CreateReg(X86::ST0, /*isDef*/ false, /*isImp*/ true));12161217if (MI.getOpcode() == X86::IST_FP64m || MI.getOpcode() == X86::ISTT_FP16m ||1218MI.getOpcode() == X86::ISTT_FP32m || MI.getOpcode() == X86::ISTT_FP64m ||1219MI.getOpcode() == X86::ST_FP80m) {1220if (StackTop == 0)1221report_fatal_error("Stack empty??");1222--StackTop;1223} else if (KillsSrc) { // Last use of operand?1224popStackAfter(I);1225}12261227MI.dropDebugNumber();1228}122912301231/// handleOneArgFPRW: Handle instructions that read from the top of stack and1232/// replace the value with a newly computed value. These instructions may have1233/// non-fp operands after their FP operands.1234///1235/// Examples:1236/// R1 = fchs R21237/// R1 = fadd R2, [mem]1238///1239void FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {1240MachineInstr &MI = *I;1241#ifndef NDEBUG1242unsigned NumOps = MI.getDesc().getNumOperands();1243assert(NumOps >= 2 && "FPRW instructions must have 2 ops!!");1244#endif12451246// Is this the last use of the source register?1247unsigned Reg = getFPReg(MI.getOperand(1));1248bool KillsSrc = MI.killsRegister(X86::FP0 + Reg, /*TRI=*/nullptr);12491250if (KillsSrc) {1251// If this is the last use of the source register, just make sure it's on1252// the top of the stack.1253moveToTop(Reg, I);1254if (StackTop == 0)1255report_fatal_error("Stack cannot be empty!");1256--StackTop;1257pushReg(getFPReg(MI.getOperand(0)));1258} else {1259// If this is not the last use of the source register, _copy_ it to the top1260// of the stack.1261duplicateToTop(Reg, getFPReg(MI.getOperand(0)), I);1262}12631264// Change from the pseudo instruction to the concrete instruction.1265MI.removeOperand(1); // Drop the source operand.1266MI.removeOperand(0); // Drop the destination operand.1267MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));1268MI.dropDebugNumber();1269}127012711272//===----------------------------------------------------------------------===//1273// Define tables of various ways to map pseudo instructions1274//12751276// ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)1277static const TableEntry ForwardST0Table[] = {1278{ X86::ADD_Fp32 , X86::ADD_FST0r },1279{ X86::ADD_Fp64 , X86::ADD_FST0r },1280{ X86::ADD_Fp80 , X86::ADD_FST0r },1281{ X86::DIV_Fp32 , X86::DIV_FST0r },1282{ X86::DIV_Fp64 , X86::DIV_FST0r },1283{ X86::DIV_Fp80 , X86::DIV_FST0r },1284{ X86::MUL_Fp32 , X86::MUL_FST0r },1285{ X86::MUL_Fp64 , X86::MUL_FST0r },1286{ X86::MUL_Fp80 , X86::MUL_FST0r },1287{ X86::SUB_Fp32 , X86::SUB_FST0r },1288{ X86::SUB_Fp64 , X86::SUB_FST0r },1289{ X86::SUB_Fp80 , X86::SUB_FST0r },1290};12911292// ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)1293static const TableEntry ReverseST0Table[] = {1294{ X86::ADD_Fp32 , X86::ADD_FST0r }, // commutative1295{ X86::ADD_Fp64 , X86::ADD_FST0r }, // commutative1296{ X86::ADD_Fp80 , X86::ADD_FST0r }, // commutative1297{ X86::DIV_Fp32 , X86::DIVR_FST0r },1298{ X86::DIV_Fp64 , X86::DIVR_FST0r },1299{ X86::DIV_Fp80 , X86::DIVR_FST0r },1300{ X86::MUL_Fp32 , X86::MUL_FST0r }, // commutative1301{ X86::MUL_Fp64 , X86::MUL_FST0r }, // commutative1302{ X86::MUL_Fp80 , X86::MUL_FST0r }, // commutative1303{ X86::SUB_Fp32 , X86::SUBR_FST0r },1304{ X86::SUB_Fp64 , X86::SUBR_FST0r },1305{ X86::SUB_Fp80 , X86::SUBR_FST0r },1306};13071308// ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)1309static const TableEntry ForwardSTiTable[] = {1310{ X86::ADD_Fp32 , X86::ADD_FrST0 }, // commutative1311{ X86::ADD_Fp64 , X86::ADD_FrST0 }, // commutative1312{ X86::ADD_Fp80 , X86::ADD_FrST0 }, // commutative1313{ X86::DIV_Fp32 , X86::DIVR_FrST0 },1314{ X86::DIV_Fp64 , X86::DIVR_FrST0 },1315{ X86::DIV_Fp80 , X86::DIVR_FrST0 },1316{ X86::MUL_Fp32 , X86::MUL_FrST0 }, // commutative1317{ X86::MUL_Fp64 , X86::MUL_FrST0 }, // commutative1318{ X86::MUL_Fp80 , X86::MUL_FrST0 }, // commutative1319{ X86::SUB_Fp32 , X86::SUBR_FrST0 },1320{ X86::SUB_Fp64 , X86::SUBR_FrST0 },1321{ X86::SUB_Fp80 , X86::SUBR_FrST0 },1322};13231324// ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)1325static const TableEntry ReverseSTiTable[] = {1326{ X86::ADD_Fp32 , X86::ADD_FrST0 },1327{ X86::ADD_Fp64 , X86::ADD_FrST0 },1328{ X86::ADD_Fp80 , X86::ADD_FrST0 },1329{ X86::DIV_Fp32 , X86::DIV_FrST0 },1330{ X86::DIV_Fp64 , X86::DIV_FrST0 },1331{ X86::DIV_Fp80 , X86::DIV_FrST0 },1332{ X86::MUL_Fp32 , X86::MUL_FrST0 },1333{ X86::MUL_Fp64 , X86::MUL_FrST0 },1334{ X86::MUL_Fp80 , X86::MUL_FrST0 },1335{ X86::SUB_Fp32 , X86::SUB_FrST0 },1336{ X86::SUB_Fp64 , X86::SUB_FrST0 },1337{ X86::SUB_Fp80 , X86::SUB_FrST0 },1338};133913401341/// handleTwoArgFP - Handle instructions like FADD and friends which are virtual1342/// instructions which need to be simplified and possibly transformed.1343///1344/// Result: ST(0) = fsub ST(0), ST(i)1345/// ST(i) = fsub ST(0), ST(i)1346/// ST(0) = fsubr ST(0), ST(i)1347/// ST(i) = fsubr ST(0), ST(i)1348///1349void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {1350ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);1351ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);1352MachineInstr &MI = *I;13531354unsigned NumOperands = MI.getDesc().getNumOperands();1355assert(NumOperands == 3 && "Illegal TwoArgFP instruction!");1356unsigned Dest = getFPReg(MI.getOperand(0));1357unsigned Op0 = getFPReg(MI.getOperand(NumOperands - 2));1358unsigned Op1 = getFPReg(MI.getOperand(NumOperands - 1));1359bool KillsOp0 = MI.killsRegister(X86::FP0 + Op0, /*TRI=*/nullptr);1360bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1, /*TRI=*/nullptr);1361const DebugLoc &dl = MI.getDebugLoc();13621363unsigned TOS = getStackEntry(0);13641365// One of our operands must be on the top of the stack. If neither is yet, we1366// need to move one.1367if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?1368// We can choose to move either operand to the top of the stack. If one of1369// the operands is killed by this instruction, we want that one so that we1370// can update right on top of the old version.1371if (KillsOp0) {1372moveToTop(Op0, I); // Move dead operand to TOS.1373TOS = Op0;1374} else if (KillsOp1) {1375moveToTop(Op1, I);1376TOS = Op1;1377} else {1378// All of the operands are live after this instruction executes, so we1379// cannot update on top of any operand. Because of this, we must1380// duplicate one of the stack elements to the top. It doesn't matter1381// which one we pick.1382//1383duplicateToTop(Op0, Dest, I);1384Op0 = TOS = Dest;1385KillsOp0 = true;1386}1387} else if (!KillsOp0 && !KillsOp1) {1388// If we DO have one of our operands at the top of the stack, but we don't1389// have a dead operand, we must duplicate one of the operands to a new slot1390// on the stack.1391duplicateToTop(Op0, Dest, I);1392Op0 = TOS = Dest;1393KillsOp0 = true;1394}13951396// Now we know that one of our operands is on the top of the stack, and at1397// least one of our operands is killed by this instruction.1398assert((TOS == Op0 || TOS == Op1) && (KillsOp0 || KillsOp1) &&1399"Stack conditions not set up right!");14001401// We decide which form to use based on what is on the top of the stack, and1402// which operand is killed by this instruction.1403ArrayRef<TableEntry> InstTable;1404bool isForward = TOS == Op0;1405bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);1406if (updateST0) {1407if (isForward)1408InstTable = ForwardST0Table;1409else1410InstTable = ReverseST0Table;1411} else {1412if (isForward)1413InstTable = ForwardSTiTable;1414else1415InstTable = ReverseSTiTable;1416}14171418int Opcode = Lookup(InstTable, MI.getOpcode());1419assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");14201421// NotTOS - The register which is not on the top of stack...1422unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;14231424// Replace the old instruction with a new instruction1425MBB->remove(&*I++);1426I = BuildMI(*MBB, I, dl, TII->get(Opcode)).addReg(getSTReg(NotTOS));14271428if (!MI.mayRaiseFPException())1429I->setFlag(MachineInstr::MIFlag::NoFPExcept);14301431// If both operands are killed, pop one off of the stack in addition to1432// overwriting the other one.1433if (KillsOp0 && KillsOp1 && Op0 != Op1) {1434assert(!updateST0 && "Should have updated other operand!");1435popStackAfter(I); // Pop the top of stack1436}14371438// Update stack information so that we know the destination register is now on1439// the stack.1440unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);1441assert(UpdatedSlot < StackTop && Dest < 7);1442Stack[UpdatedSlot] = Dest;1443RegMap[Dest] = UpdatedSlot;1444MBB->getParent()->deleteMachineInstr(&MI); // Remove the old instruction1445}14461447/// handleCompareFP - Handle FUCOM and FUCOMI instructions, which have two FP1448/// register arguments and no explicit destinations.1449///1450void FPS::handleCompareFP(MachineBasicBlock::iterator &I) {1451MachineInstr &MI = *I;14521453unsigned NumOperands = MI.getDesc().getNumOperands();1454assert(NumOperands == 2 && "Illegal FUCOM* instruction!");1455unsigned Op0 = getFPReg(MI.getOperand(NumOperands - 2));1456unsigned Op1 = getFPReg(MI.getOperand(NumOperands - 1));1457bool KillsOp0 = MI.killsRegister(X86::FP0 + Op0, /*TRI=*/nullptr);1458bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1, /*TRI=*/nullptr);14591460// Make sure the first operand is on the top of stack, the other one can be1461// anywhere.1462moveToTop(Op0, I);14631464// Change from the pseudo instruction to the concrete instruction.1465MI.getOperand(0).setReg(getSTReg(Op1));1466MI.removeOperand(1);1467MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));1468MI.dropDebugNumber();14691470// If any of the operands are killed by this instruction, free them.1471if (KillsOp0) freeStackSlotAfter(I, Op0);1472if (KillsOp1 && Op0 != Op1) freeStackSlotAfter(I, Op1);1473}14741475/// handleCondMovFP - Handle two address conditional move instructions. These1476/// instructions move a st(i) register to st(0) iff a condition is true. These1477/// instructions require that the first operand is at the top of the stack, but1478/// otherwise don't modify the stack at all.1479void FPS::handleCondMovFP(MachineBasicBlock::iterator &I) {1480MachineInstr &MI = *I;14811482unsigned Op0 = getFPReg(MI.getOperand(0));1483unsigned Op1 = getFPReg(MI.getOperand(2));1484bool KillsOp1 = MI.killsRegister(X86::FP0 + Op1, /*TRI=*/nullptr);14851486// The first operand *must* be on the top of the stack.1487moveToTop(Op0, I);14881489// Change the second operand to the stack register that the operand is in.1490// Change from the pseudo instruction to the concrete instruction.1491MI.removeOperand(0);1492MI.removeOperand(1);1493MI.getOperand(0).setReg(getSTReg(Op1));1494MI.setDesc(TII->get(getConcreteOpcode(MI.getOpcode())));1495MI.dropDebugNumber();14961497// If we kill the second operand, make sure to pop it from the stack.1498if (Op0 != Op1 && KillsOp1) {1499// Get this value off of the register stack.1500freeStackSlotAfter(I, Op1);1501}1502}150315041505/// handleSpecialFP - Handle special instructions which behave unlike other1506/// floating point instructions. This is primarily intended for use by pseudo1507/// instructions.1508///1509void FPS::handleSpecialFP(MachineBasicBlock::iterator &Inst) {1510MachineInstr &MI = *Inst;15111512if (MI.isCall()) {1513handleCall(Inst);1514return;1515}15161517if (MI.isReturn()) {1518handleReturn(Inst);1519return;1520}15211522switch (MI.getOpcode()) {1523default: llvm_unreachable("Unknown SpecialFP instruction!");1524case TargetOpcode::COPY: {1525// We handle three kinds of copies: FP <- FP, FP <- ST, and ST <- FP.1526const MachineOperand &MO1 = MI.getOperand(1);1527const MachineOperand &MO0 = MI.getOperand(0);1528bool KillsSrc = MI.killsRegister(MO1.getReg(), /*TRI=*/nullptr);15291530// FP <- FP copy.1531unsigned DstFP = getFPReg(MO0);1532unsigned SrcFP = getFPReg(MO1);1533assert(isLive(SrcFP) && "Cannot copy dead register");1534if (KillsSrc) {1535// If the input operand is killed, we can just change the owner of the1536// incoming stack slot into the result.1537unsigned Slot = getSlot(SrcFP);1538Stack[Slot] = DstFP;1539RegMap[DstFP] = Slot;1540} else {1541// For COPY we just duplicate the specified value to a new stack slot.1542// This could be made better, but would require substantial changes.1543duplicateToTop(SrcFP, DstFP, Inst);1544}1545break;1546}15471548case TargetOpcode::IMPLICIT_DEF: {1549// All FP registers must be explicitly defined, so load a 0 instead.1550unsigned Reg = MI.getOperand(0).getReg() - X86::FP0;1551LLVM_DEBUG(dbgs() << "Emitting LD_F0 for implicit FP" << Reg << '\n');1552BuildMI(*MBB, Inst, MI.getDebugLoc(), TII->get(X86::LD_F0));1553pushReg(Reg);1554break;1555}15561557case TargetOpcode::INLINEASM:1558case TargetOpcode::INLINEASM_BR: {1559// The inline asm MachineInstr currently only *uses* FP registers for the1560// 'f' constraint. These should be turned into the current ST(x) register1561// in the machine instr.1562//1563// There are special rules for x87 inline assembly. The compiler must know1564// exactly how many registers are popped and pushed implicitly by the asm.1565// Otherwise it is not possible to restore the stack state after the inline1566// asm.1567//1568// There are 3 kinds of input operands:1569//1570// 1. Popped inputs. These must appear at the stack top in ST0-STn. A1571// popped input operand must be in a fixed stack slot, and it is either1572// tied to an output operand, or in the clobber list. The MI has ST use1573// and def operands for these inputs.1574//1575// 2. Fixed inputs. These inputs appear in fixed stack slots, but are1576// preserved by the inline asm. The fixed stack slots must be STn-STm1577// following the popped inputs. A fixed input operand cannot be tied to1578// an output or appear in the clobber list. The MI has ST use operands1579// and no defs for these inputs.1580//1581// 3. Preserved inputs. These inputs use the "f" constraint which is1582// represented as an FP register. The inline asm won't change these1583// stack slots.1584//1585// Outputs must be in ST registers, FP outputs are not allowed. Clobbered1586// registers do not count as output operands. The inline asm changes the1587// stack as if it popped all the popped inputs and then pushed all the1588// output operands.15891590// Scan the assembly for ST registers used, defined and clobbered. We can1591// only tell clobbers from defs by looking at the asm descriptor.1592unsigned STUses = 0, STDefs = 0, STClobbers = 0;1593unsigned NumOps = 0;1594SmallSet<unsigned, 1> FRegIdx;1595unsigned RCID;15961597for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI.getNumOperands();1598i != e && MI.getOperand(i).isImm(); i += 1 + NumOps) {1599unsigned Flags = MI.getOperand(i).getImm();1600const InlineAsm::Flag F(Flags);16011602NumOps = F.getNumOperandRegisters();1603if (NumOps != 1)1604continue;1605const MachineOperand &MO = MI.getOperand(i + 1);1606if (!MO.isReg())1607continue;1608unsigned STReg = MO.getReg() - X86::FP0;1609if (STReg >= 8)1610continue;16111612// If the flag has a register class constraint, this must be an operand1613// with constraint "f". Record its index and continue.1614if (F.hasRegClassConstraint(RCID)) {1615FRegIdx.insert(i + 1);1616continue;1617}16181619switch (F.getKind()) {1620case InlineAsm::Kind::RegUse:1621STUses |= (1u << STReg);1622break;1623case InlineAsm::Kind::RegDef:1624case InlineAsm::Kind::RegDefEarlyClobber:1625STDefs |= (1u << STReg);1626break;1627case InlineAsm::Kind::Clobber:1628STClobbers |= (1u << STReg);1629break;1630default:1631break;1632}1633}16341635if (STUses && !isMask_32(STUses))1636MI.emitError("fixed input regs must be last on the x87 stack");1637unsigned NumSTUses = llvm::countr_one(STUses);16381639// Defs must be contiguous from the stack top. ST0-STn.1640if (STDefs && !isMask_32(STDefs)) {1641MI.emitError("output regs must be last on the x87 stack");1642STDefs = NextPowerOf2(STDefs) - 1;1643}1644unsigned NumSTDefs = llvm::countr_one(STDefs);16451646// So must the clobbered stack slots. ST0-STm, m >= n.1647if (STClobbers && !isMask_32(STDefs | STClobbers))1648MI.emitError("clobbers must be last on the x87 stack");16491650// Popped inputs are the ones that are also clobbered or defined.1651unsigned STPopped = STUses & (STDefs | STClobbers);1652if (STPopped && !isMask_32(STPopped))1653MI.emitError("implicitly popped regs must be last on the x87 stack");1654unsigned NumSTPopped = llvm::countr_one(STPopped);16551656LLVM_DEBUG(dbgs() << "Asm uses " << NumSTUses << " fixed regs, pops "1657<< NumSTPopped << ", and defines " << NumSTDefs1658<< " regs.\n");16591660#ifndef NDEBUG1661// If any input operand uses constraint "f", all output register1662// constraints must be early-clobber defs.1663for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I)1664if (FRegIdx.count(I)) {1665assert((1 << getFPReg(MI.getOperand(I)) & STDefs) == 0 &&1666"Operands with constraint \"f\" cannot overlap with defs");1667}1668#endif16691670// Collect all FP registers (register operands with constraints "t", "u",1671// and "f") to kill afer the instruction.1672unsigned FPKills = ((1u << NumFPRegs) - 1) & ~0xff;1673for (const MachineOperand &Op : MI.operands()) {1674if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)1675continue;1676unsigned FPReg = getFPReg(Op);16771678// If we kill this operand, make sure to pop it from the stack after the1679// asm. We just remember it for now, and pop them all off at the end in1680// a batch.1681if (Op.isUse() && Op.isKill())1682FPKills |= 1U << FPReg;1683}16841685// Do not include registers that are implicitly popped by defs/clobbers.1686FPKills &= ~(STDefs | STClobbers);16871688// Now we can rearrange the live registers to match what was requested.1689unsigned char STUsesArray[8];16901691for (unsigned I = 0; I < NumSTUses; ++I)1692STUsesArray[I] = I;16931694shuffleStackTop(STUsesArray, NumSTUses, Inst);1695LLVM_DEBUG({1696dbgs() << "Before asm: ";1697dumpStack();1698});16991700// With the stack layout fixed, rewrite the FP registers.1701for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {1702MachineOperand &Op = MI.getOperand(i);1703if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)1704continue;17051706unsigned FPReg = getFPReg(Op);17071708if (FRegIdx.count(i))1709// Operand with constraint "f".1710Op.setReg(getSTReg(FPReg));1711else1712// Operand with a single register class constraint ("t" or "u").1713Op.setReg(X86::ST0 + FPReg);1714}17151716// Simulate the inline asm popping its inputs and pushing its outputs.1717StackTop -= NumSTPopped;17181719for (unsigned i = 0; i < NumSTDefs; ++i)1720pushReg(NumSTDefs - i - 1);17211722// If this asm kills any FP registers (is the last use of them) we must1723// explicitly emit pop instructions for them. Do this now after the asm has1724// executed so that the ST(x) numbers are not off (which would happen if we1725// did this inline with operand rewriting).1726//1727// Note: this might be a non-optimal pop sequence. We might be able to do1728// better by trying to pop in stack order or something.1729while (FPKills) {1730unsigned FPReg = llvm::countr_zero(FPKills);1731if (isLive(FPReg))1732freeStackSlotAfter(Inst, FPReg);1733FPKills &= ~(1U << FPReg);1734}17351736// Don't delete the inline asm!1737return;1738}1739}17401741Inst = MBB->erase(Inst); // Remove the pseudo instruction17421743// We want to leave I pointing to the previous instruction, but what if we1744// just erased the first instruction?1745if (Inst == MBB->begin()) {1746LLVM_DEBUG(dbgs() << "Inserting dummy KILL\n");1747Inst = BuildMI(*MBB, Inst, DebugLoc(), TII->get(TargetOpcode::KILL));1748} else1749--Inst;1750}17511752void FPS::setKillFlags(MachineBasicBlock &MBB) const {1753const TargetRegisterInfo &TRI =1754*MBB.getParent()->getSubtarget().getRegisterInfo();1755LiveRegUnits LPR(TRI);17561757LPR.addLiveOuts(MBB);17581759for (MachineInstr &MI : llvm::reverse(MBB)) {1760if (MI.isDebugInstr())1761continue;17621763std::bitset<8> Defs;1764SmallVector<MachineOperand *, 2> Uses;17651766for (auto &MO : MI.operands()) {1767if (!MO.isReg())1768continue;17691770unsigned Reg = MO.getReg() - X86::FP0;17711772if (Reg >= 8)1773continue;17741775if (MO.isDef()) {1776Defs.set(Reg);1777if (LPR.available(MO.getReg()))1778MO.setIsDead();1779} else1780Uses.push_back(&MO);1781}17821783for (auto *MO : Uses)1784if (Defs.test(getFPReg(*MO)) || LPR.available(MO->getReg()))1785MO->setIsKill();17861787LPR.stepBackward(MI);1788}1789}179017911792