1193323Sed//===-- X86FloatingPoint.cpp - Floating point Reg -> Stack converter ------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the pass which converts floating point instructions from
11212904Sdim// pseudo registers into register stack instructions.  This pass uses live
12193323Sed// variable information to indicate where the FPn registers are used and their
13193323Sed// lifetimes.
14193323Sed//
15212904Sdim// The x87 hardware tracks liveness of the stack registers, so it is necessary
16212904Sdim// to implement exact liveness tracking between basic blocks. The CFG edges are
17212904Sdim// partitioned into bundles where the same FP registers must be live in
18212904Sdim// identical stack positions. Instructions are inserted at the end of each basic
19212904Sdim// block to rearrange the live registers to match the outgoing bundle.
20193323Sed//
21212904Sdim// This approach avoids splitting critical edges at the potential cost of more
22212904Sdim// live register shuffling instructions when critical edges are present.
23193323Sed//
24193323Sed//===----------------------------------------------------------------------===//
25193323Sed
26193323Sed#define DEBUG_TYPE "x86-codegen"
27193323Sed#include "X86.h"
28193323Sed#include "X86InstrInfo.h"
29198090Srdivacky#include "llvm/ADT/DepthFirstIterator.h"
30249423Sdim#include "llvm/ADT/STLExtras.h"
31198090Srdivacky#include "llvm/ADT/SmallPtrSet.h"
32198090Srdivacky#include "llvm/ADT/SmallVector.h"
33198090Srdivacky#include "llvm/ADT/Statistic.h"
34218893Sdim#include "llvm/CodeGen/EdgeBundles.h"
35193323Sed#include "llvm/CodeGen/MachineFunctionPass.h"
36193323Sed#include "llvm/CodeGen/MachineInstrBuilder.h"
37193323Sed#include "llvm/CodeGen/MachineRegisterInfo.h"
38193323Sed#include "llvm/CodeGen/Passes.h"
39249423Sdim#include "llvm/IR/InlineAsm.h"
40198090Srdivacky#include "llvm/Support/Debug.h"
41198090Srdivacky#include "llvm/Support/ErrorHandling.h"
42198090Srdivacky#include "llvm/Support/raw_ostream.h"
43193323Sed#include "llvm/Target/TargetInstrInfo.h"
44193323Sed#include "llvm/Target/TargetMachine.h"
45193323Sed#include <algorithm>
46193323Sedusing namespace llvm;
47193323Sed
48193323SedSTATISTIC(NumFXCH, "Number of fxch instructions inserted");
49193323SedSTATISTIC(NumFP  , "Number of floating point instructions");
50193323Sed
51193323Sednamespace {
52198892Srdivacky  struct FPS : public MachineFunctionPass {
53193323Sed    static char ID;
54212904Sdim    FPS() : MachineFunctionPass(ID) {
55218893Sdim      initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
56212904Sdim      // This is really only to keep valgrind quiet.
57212904Sdim      // The logic in isLive() is too much for it.
58212904Sdim      memset(Stack, 0, sizeof(Stack));
59212904Sdim      memset(RegMap, 0, sizeof(RegMap));
60212904Sdim    }
61193323Sed
62193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63198090Srdivacky      AU.setPreservesCFG();
64218893Sdim      AU.addRequired<EdgeBundles>();
65193323Sed      AU.addPreservedID(MachineLoopInfoID);
66193323Sed      AU.addPreservedID(MachineDominatorsID);
67193323Sed      MachineFunctionPass::getAnalysisUsage(AU);
68193323Sed    }
69193323Sed
70193323Sed    virtual bool runOnMachineFunction(MachineFunction &MF);
71193323Sed
72193323Sed    virtual const char *getPassName() const { return "X86 FP Stackifier"; }
73193323Sed
74193323Sed  private:
75193323Sed    const TargetInstrInfo *TII; // Machine instruction info.
76212904Sdim
77212904Sdim    // Two CFG edges are related if they leave the same block, or enter the same
78212904Sdim    // block. The transitive closure of an edge under this relation is a
79212904Sdim    // LiveBundle. It represents a set of CFG edges where the live FP stack
80212904Sdim    // registers must be allocated identically in the x87 stack.
81212904Sdim    //
82212904Sdim    // A LiveBundle is usually all the edges leaving a block, or all the edges
83212904Sdim    // entering a block, but it can contain more edges if critical edges are
84212904Sdim    // present.
85212904Sdim    //
86212904Sdim    // The set of live FP registers in a LiveBundle is calculated by bundleCFG,
87212904Sdim    // but the exact mapping of FP registers to stack slots is fixed later.
88212904Sdim    struct LiveBundle {
89212904Sdim      // Bit mask of live FP registers. Bit 0 = FP0, bit 1 = FP1, &c.
90212904Sdim      unsigned Mask;
91212904Sdim
92212904Sdim      // Number of pre-assigned live registers in FixStack. This is 0 when the
93212904Sdim      // stack order has not yet been fixed.
94212904Sdim      unsigned FixCount;
95212904Sdim
96212904Sdim      // Assigned stack order for live-in registers.
97212904Sdim      // FixStack[i] == getStackEntry(i) for all i < FixCount.
98212904Sdim      unsigned char FixStack[8];
99212904Sdim
100218893Sdim      LiveBundle() : Mask(0), FixCount(0) {}
101212904Sdim
102212904Sdim      // Have the live registers been assigned a stack order yet?
103212904Sdim      bool isFixed() const { return !Mask || FixCount; }
104212904Sdim    };
105212904Sdim
106212904Sdim    // Numbered LiveBundle structs. LiveBundles[0] is used for all CFG edges
107212904Sdim    // with no live FP registers.
108212904Sdim    SmallVector<LiveBundle, 8> LiveBundles;
109212904Sdim
110218893Sdim    // The edge bundle analysis provides indices into the LiveBundles vector.
111218893Sdim    EdgeBundles *Bundles;
112212904Sdim
113212904Sdim    // Return a bitmask of FP registers in block's live-in list.
114249423Sdim    static unsigned calcLiveInMask(MachineBasicBlock *MBB) {
115212904Sdim      unsigned Mask = 0;
116212904Sdim      for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
117212904Sdim           E = MBB->livein_end(); I != E; ++I) {
118263508Sdim        unsigned Reg = *I;
119263508Sdim        if (Reg < X86::FP0 || Reg > X86::FP6)
120263508Sdim          continue;
121263508Sdim        Mask |= 1 << (Reg - X86::FP0);
122212904Sdim      }
123212904Sdim      return Mask;
124212904Sdim    }
125212904Sdim
126212904Sdim    // Partition all the CFG edges into LiveBundles.
127212904Sdim    void bundleCFG(MachineFunction &MF);
128212904Sdim
129193323Sed    MachineBasicBlock *MBB;     // Current basic block
130224145Sdim
131224145Sdim    // The hardware keeps track of how many FP registers are live, so we have
132224145Sdim    // to model that exactly. Usually, each live register corresponds to an
133224145Sdim    // FP<n> register, but when dealing with calls, returns, and inline
134239462Sdim    // assembly, it is sometimes necessary to have live scratch registers.
135193323Sed    unsigned Stack[8];          // FP<n> Registers in each stack slot...
136193323Sed    unsigned StackTop;          // The current top of the FP stack.
137193323Sed
138224145Sdim    enum {
139224145Sdim      NumFPRegs = 16            // Including scratch pseudo-registers.
140224145Sdim    };
141224145Sdim
142224145Sdim    // For each live FP<n> register, point to its Stack[] entry.
143224145Sdim    // The first entries correspond to FP0-FP6, the rest are scratch registers
144224145Sdim    // used when we need slightly different live registers than what the
145224145Sdim    // register allocator thinks.
146224145Sdim    unsigned RegMap[NumFPRegs];
147224145Sdim
148224145Sdim    // Pending fixed registers - Inline assembly needs FP registers to appear
149224145Sdim    // in fixed stack slot positions. This is handled by copying FP registers
150224145Sdim    // to ST registers before the instruction, and copying back after the
151224145Sdim    // instruction.
152224145Sdim    //
153224145Sdim    // This is modeled with pending ST registers. NumPendingSTs is the number
154224145Sdim    // of ST registers (ST0-STn) we are tracking. PendingST[n] points to an FP
155224145Sdim    // register that holds the ST value. The ST registers are not moved into
156224145Sdim    // place until immediately before the instruction that needs them.
157224145Sdim    //
158224145Sdim    // It can happen that we need an ST register to be live when no FP register
159224145Sdim    // holds the value:
160224145Sdim    //
161224145Sdim    //   %ST0 = COPY %FP4<kill>
162224145Sdim    //
163224145Sdim    // When that happens, we allocate a scratch FP register to hold the ST
164224145Sdim    // value. That means every register in PendingST must be live.
165224145Sdim
166224145Sdim    unsigned NumPendingSTs;
167224145Sdim    unsigned char PendingST[8];
168224145Sdim
169212904Sdim    // Set up our stack model to match the incoming registers to MBB.
170212904Sdim    void setupBlockStack();
171212904Sdim
172212904Sdim    // Shuffle live registers to match the expectations of successor blocks.
173212904Sdim    void finishBlockStack();
174212904Sdim
175243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
176193323Sed    void dumpStack() const {
177202375Srdivacky      dbgs() << "Stack contents:";
178193323Sed      for (unsigned i = 0; i != StackTop; ++i) {
179202375Srdivacky        dbgs() << " FP" << Stack[i];
180193323Sed        assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
181193323Sed      }
182224145Sdim      for (unsigned i = 0; i != NumPendingSTs; ++i)
183224145Sdim        dbgs() << ", ST" << i << " in FP" << unsigned(PendingST[i]);
184202375Srdivacky      dbgs() << "\n";
185193323Sed    }
186243830Sdim#endif
187212904Sdim
188212904Sdim    /// getSlot - Return the stack slot number a particular register number is
189212904Sdim    /// in.
190193323Sed    unsigned getSlot(unsigned RegNo) const {
191224145Sdim      assert(RegNo < NumFPRegs && "Regno out of range!");
192193323Sed      return RegMap[RegNo];
193193323Sed    }
194193323Sed
195212904Sdim    /// isLive - Is RegNo currently live in the stack?
196212904Sdim    bool isLive(unsigned RegNo) const {
197212904Sdim      unsigned Slot = getSlot(RegNo);
198212904Sdim      return Slot < StackTop && Stack[Slot] == RegNo;
199212904Sdim    }
200212904Sdim
201212904Sdim    /// getScratchReg - Return an FP register that is not currently in use.
202249423Sdim    unsigned getScratchReg() const {
203224145Sdim      for (int i = NumFPRegs - 1; i >= 8; --i)
204212904Sdim        if (!isLive(i))
205212904Sdim          return i;
206212904Sdim      llvm_unreachable("Ran out of scratch FP registers");
207212904Sdim    }
208212904Sdim
209224145Sdim    /// isScratchReg - Returns trus if RegNo is a scratch FP register.
210249423Sdim    static bool isScratchReg(unsigned RegNo) {
211224145Sdim      return RegNo > 8 && RegNo < NumFPRegs;
212224145Sdim    }
213224145Sdim
214212904Sdim    /// getStackEntry - Return the X86::FP<n> register in register ST(i).
215193323Sed    unsigned getStackEntry(unsigned STi) const {
216218893Sdim      if (STi >= StackTop)
217218893Sdim        report_fatal_error("Access past stack top!");
218193323Sed      return Stack[StackTop-1-STi];
219193323Sed    }
220193323Sed
221212904Sdim    /// getSTReg - Return the X86::ST(i) register which contains the specified
222212904Sdim    /// FP<RegNo> register.
223193323Sed    unsigned getSTReg(unsigned RegNo) const {
224234353Sdim      return StackTop - 1 - getSlot(RegNo) + X86::ST0;
225193323Sed    }
226193323Sed
227193323Sed    // pushReg - Push the specified FP<n> register onto the stack.
228193323Sed    void pushReg(unsigned Reg) {
229224145Sdim      assert(Reg < NumFPRegs && "Register number out of range!");
230218893Sdim      if (StackTop >= 8)
231218893Sdim        report_fatal_error("Stack overflow!");
232193323Sed      Stack[StackTop] = Reg;
233193323Sed      RegMap[Reg] = StackTop++;
234193323Sed    }
235193323Sed
236193323Sed    bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
237193323Sed    void moveToTop(unsigned RegNo, MachineBasicBlock::iterator I) {
238212904Sdim      DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();
239193323Sed      if (isAtTop(RegNo)) return;
240212904Sdim
241193323Sed      unsigned STReg = getSTReg(RegNo);
242193323Sed      unsigned RegOnTop = getStackEntry(0);
243193323Sed
244193323Sed      // Swap the slots the regs are in.
245193323Sed      std::swap(RegMap[RegNo], RegMap[RegOnTop]);
246193323Sed
247193323Sed      // Swap stack slot contents.
248218893Sdim      if (RegMap[RegOnTop] >= StackTop)
249218893Sdim        report_fatal_error("Access past stack top!");
250193323Sed      std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
251193323Sed
252193323Sed      // Emit an fxch to update the runtime processors version of the state.
253193323Sed      BuildMI(*MBB, I, dl, TII->get(X86::XCH_F)).addReg(STReg);
254210299Sed      ++NumFXCH;
255193323Sed    }
256193323Sed
257193323Sed    void duplicateToTop(unsigned RegNo, unsigned AsReg, MachineInstr *I) {
258212904Sdim      DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();
259193323Sed      unsigned STReg = getSTReg(RegNo);
260193323Sed      pushReg(AsReg);   // New register on top of stack
261193323Sed
262193323Sed      BuildMI(*MBB, I, dl, TII->get(X86::LD_Frr)).addReg(STReg);
263193323Sed    }
264193323Sed
265226633Sdim    /// duplicatePendingSTBeforeKill - The instruction at I is about to kill
266226633Sdim    /// RegNo. If any PendingST registers still need the RegNo value, duplicate
267226633Sdim    /// them to new scratch registers.
268226633Sdim    void duplicatePendingSTBeforeKill(unsigned RegNo, MachineInstr *I) {
269226633Sdim      for (unsigned i = 0; i != NumPendingSTs; ++i) {
270226633Sdim        if (PendingST[i] != RegNo)
271226633Sdim          continue;
272226633Sdim        unsigned SR = getScratchReg();
273226633Sdim        DEBUG(dbgs() << "Duplicating pending ST" << i
274226633Sdim                     << " in FP" << RegNo << " to FP" << SR << '\n');
275226633Sdim        duplicateToTop(RegNo, SR, I);
276226633Sdim        PendingST[i] = SR;
277226633Sdim      }
278226633Sdim    }
279226633Sdim
280212904Sdim    /// popStackAfter - Pop the current value off of the top of the FP stack
281212904Sdim    /// after the specified instruction.
282193323Sed    void popStackAfter(MachineBasicBlock::iterator &I);
283193323Sed
284212904Sdim    /// freeStackSlotAfter - Free the specified register from the register
285212904Sdim    /// stack, so that it is no longer in a register.  If the register is
286212904Sdim    /// currently at the top of the stack, we just pop the current instruction,
287212904Sdim    /// otherwise we store the current top-of-stack into the specified slot,
288212904Sdim    /// then pop the top of stack.
289193323Sed    void freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned Reg);
290193323Sed
291212904Sdim    /// freeStackSlotBefore - Just the pop, no folding. Return the inserted
292212904Sdim    /// instruction.
293212904Sdim    MachineBasicBlock::iterator
294212904Sdim    freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo);
295212904Sdim
296212904Sdim    /// Adjust the live registers to be the set in Mask.
297212904Sdim    void adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I);
298212904Sdim
299224145Sdim    /// Shuffle the top FixCount stack entries such that FP reg FixStack[0] is
300212904Sdim    /// st(0), FP reg FixStack[1] is st(1) etc.
301212904Sdim    void shuffleStackTop(const unsigned char *FixStack, unsigned FixCount,
302212904Sdim                         MachineBasicBlock::iterator I);
303212904Sdim
304193323Sed    bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
305193323Sed
306193323Sed    void handleZeroArgFP(MachineBasicBlock::iterator &I);
307193323Sed    void handleOneArgFP(MachineBasicBlock::iterator &I);
308193323Sed    void handleOneArgFPRW(MachineBasicBlock::iterator &I);
309193323Sed    void handleTwoArgFP(MachineBasicBlock::iterator &I);
310193323Sed    void handleCompareFP(MachineBasicBlock::iterator &I);
311193323Sed    void handleCondMovFP(MachineBasicBlock::iterator &I);
312193323Sed    void handleSpecialFP(MachineBasicBlock::iterator &I);
313210299Sed
314224145Sdim    // Check if a COPY instruction is using FP registers.
315249423Sdim    static bool isFPCopy(MachineInstr *MI) {
316224145Sdim      unsigned DstReg = MI->getOperand(0).getReg();
317224145Sdim      unsigned SrcReg = MI->getOperand(1).getReg();
318224145Sdim
319224145Sdim      return X86::RFP80RegClass.contains(DstReg) ||
320224145Sdim        X86::RFP80RegClass.contains(SrcReg);
321224145Sdim    }
322193323Sed  };
323193323Sed  char FPS::ID = 0;
324193323Sed}
325193323Sed
326193323SedFunctionPass *llvm::createX86FloatingPointStackifierPass() { return new FPS(); }
327193323Sed
328193323Sed/// getFPReg - Return the X86::FPx register number for the specified operand.
329193323Sed/// For example, this returns 3 for X86::FP3.
330193323Sedstatic unsigned getFPReg(const MachineOperand &MO) {
331193323Sed  assert(MO.isReg() && "Expected an FP register!");
332193323Sed  unsigned Reg = MO.getReg();
333193323Sed  assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
334193323Sed  return Reg - X86::FP0;
335193323Sed}
336193323Sed
337193323Sed/// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
338193323Sed/// register references into FP stack references.
339193323Sed///
340193323Sedbool FPS::runOnMachineFunction(MachineFunction &MF) {
341193323Sed  // We only need to run this pass if there are any FP registers used in this
342193323Sed  // function.  If it is all integer, there is nothing for us to do!
343193323Sed  bool FPIsUsed = false;
344193323Sed
345193323Sed  assert(X86::FP6 == X86::FP0+6 && "Register enums aren't sorted right!");
346193323Sed  for (unsigned i = 0; i <= 6; ++i)
347193323Sed    if (MF.getRegInfo().isPhysRegUsed(X86::FP0+i)) {
348193323Sed      FPIsUsed = true;
349193323Sed      break;
350193323Sed    }
351193323Sed
352193323Sed  // Early exit.
353193323Sed  if (!FPIsUsed) return false;
354193323Sed
355218893Sdim  Bundles = &getAnalysis<EdgeBundles>();
356193323Sed  TII = MF.getTarget().getInstrInfo();
357212904Sdim
358212904Sdim  // Prepare cross-MBB liveness.
359212904Sdim  bundleCFG(MF);
360212904Sdim
361193323Sed  StackTop = 0;
362193323Sed
363193323Sed  // Process the function in depth first order so that we process at least one
364193323Sed  // of the predecessors for every reachable block in the function.
365193323Sed  SmallPtrSet<MachineBasicBlock*, 8> Processed;
366193323Sed  MachineBasicBlock *Entry = MF.begin();
367193323Sed
368193323Sed  bool Changed = false;
369193323Sed  for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8> >
370193323Sed         I = df_ext_begin(Entry, Processed), E = df_ext_end(Entry, Processed);
371193323Sed       I != E; ++I)
372193323Sed    Changed |= processBasicBlock(MF, **I);
373193323Sed
374198090Srdivacky  // Process any unreachable blocks in arbitrary order now.
375212904Sdim  if (MF.size() != Processed.size())
376212904Sdim    for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
377212904Sdim      if (Processed.insert(BB))
378212904Sdim        Changed |= processBasicBlock(MF, *BB);
379198090Srdivacky
380212904Sdim  LiveBundles.clear();
381212904Sdim
382193323Sed  return Changed;
383193323Sed}
384193323Sed
385212904Sdim/// bundleCFG - Scan all the basic blocks to determine consistent live-in and
386212904Sdim/// live-out sets for the FP registers. Consistent means that the set of
387212904Sdim/// registers live-out from a block is identical to the live-in set of all
388212904Sdim/// successors. This is not enforced by the normal live-in lists since
389212904Sdim/// registers may be implicitly defined, or not used by all successors.
390212904Sdimvoid FPS::bundleCFG(MachineFunction &MF) {
391212904Sdim  assert(LiveBundles.empty() && "Stale data in LiveBundles");
392218893Sdim  LiveBundles.resize(Bundles->getNumBundles());
393212904Sdim
394218893Sdim  // Gather the actual live-in masks for all MBBs.
395212904Sdim  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
396212904Sdim    MachineBasicBlock *MBB = I;
397212904Sdim    const unsigned Mask = calcLiveInMask(MBB);
398212904Sdim    if (!Mask)
399212904Sdim      continue;
400218893Sdim    // Update MBB ingoing bundle mask.
401218893Sdim    LiveBundles[Bundles->getBundle(MBB->getNumber(), false)].Mask |= Mask;
402212904Sdim  }
403212904Sdim}
404212904Sdim
405193323Sed/// processBasicBlock - Loop over all of the instructions in the basic block,
406193323Sed/// transforming FP instructions into their stack form.
407193323Sed///
408193323Sedbool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
409193323Sed  bool Changed = false;
410193323Sed  MBB = &BB;
411224145Sdim  NumPendingSTs = 0;
412193323Sed
413212904Sdim  setupBlockStack();
414212904Sdim
415193323Sed  for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
416193323Sed    MachineInstr *MI = I;
417210299Sed    uint64_t Flags = MI->getDesc().TSFlags;
418212904Sdim
419193323Sed    unsigned FPInstClass = Flags & X86II::FPTypeMask;
420203954Srdivacky    if (MI->isInlineAsm())
421193323Sed      FPInstClass = X86II::SpecialFP;
422210299Sed
423224145Sdim    if (MI->isCopy() && isFPCopy(MI))
424210299Sed      FPInstClass = X86II::SpecialFP;
425210299Sed
426226633Sdim    if (MI->isImplicitDef() &&
427226633Sdim        X86::RFP80RegClass.contains(MI->getOperand(0).getReg()))
428226633Sdim      FPInstClass = X86II::SpecialFP;
429226633Sdim
430193323Sed    if (FPInstClass == X86II::NotFP)
431193323Sed      continue;  // Efficiently ignore non-fp insts!
432193323Sed
433193323Sed    MachineInstr *PrevMI = 0;
434193323Sed    if (I != BB.begin())
435193323Sed      PrevMI = prior(I);
436193323Sed
437193323Sed    ++NumFP;  // Keep track of # of pseudo instrs
438202375Srdivacky    DEBUG(dbgs() << "\nFPInst:\t" << *MI);
439193323Sed
440193323Sed    // Get dead variables list now because the MI pointer may be deleted as part
441193323Sed    // of processing!
442193323Sed    SmallVector<unsigned, 8> DeadRegs;
443193323Sed    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
444193323Sed      const MachineOperand &MO = MI->getOperand(i);
445193323Sed      if (MO.isReg() && MO.isDead())
446193323Sed        DeadRegs.push_back(MO.getReg());
447193323Sed    }
448193323Sed
449193323Sed    switch (FPInstClass) {
450193323Sed    case X86II::ZeroArgFP:  handleZeroArgFP(I); break;
451193323Sed    case X86II::OneArgFP:   handleOneArgFP(I);  break;  // fstp ST(0)
452193323Sed    case X86II::OneArgFPRW: handleOneArgFPRW(I); break; // ST(0) = fsqrt(ST(0))
453193323Sed    case X86II::TwoArgFP:   handleTwoArgFP(I);  break;
454193323Sed    case X86II::CompareFP:  handleCompareFP(I); break;
455193323Sed    case X86II::CondMovFP:  handleCondMovFP(I); break;
456193323Sed    case X86II::SpecialFP:  handleSpecialFP(I); break;
457198090Srdivacky    default: llvm_unreachable("Unknown FP Type!");
458193323Sed    }
459193323Sed
460193323Sed    // Check to see if any of the values defined by this instruction are dead
461193323Sed    // after definition.  If so, pop them.
462193323Sed    for (unsigned i = 0, e = DeadRegs.size(); i != e; ++i) {
463193323Sed      unsigned Reg = DeadRegs[i];
464193323Sed      if (Reg >= X86::FP0 && Reg <= X86::FP6) {
465202375Srdivacky        DEBUG(dbgs() << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
466193323Sed        freeStackSlotAfter(I, Reg-X86::FP0);
467193323Sed      }
468193323Sed    }
469193323Sed
470193323Sed    // Print out all of the instructions expanded to if -debug
471193323Sed    DEBUG(
472193323Sed      MachineBasicBlock::iterator PrevI(PrevMI);
473193323Sed      if (I == PrevI) {
474202375Srdivacky        dbgs() << "Just deleted pseudo instruction\n";
475193323Sed      } else {
476193323Sed        MachineBasicBlock::iterator Start = I;
477193323Sed        // Rewind to first instruction newly inserted.
478193323Sed        while (Start != BB.begin() && prior(Start) != PrevI) --Start;
479202375Srdivacky        dbgs() << "Inserted instructions:\n\t";
480202375Srdivacky        Start->print(dbgs(), &MF.getTarget());
481200581Srdivacky        while (++Start != llvm::next(I)) {}
482193323Sed      }
483193323Sed      dumpStack();
484193323Sed    );
485226633Sdim    (void)PrevMI;
486193323Sed
487193323Sed    Changed = true;
488193323Sed  }
489193323Sed
490212904Sdim  finishBlockStack();
491212904Sdim
492193323Sed  return Changed;
493193323Sed}
494193323Sed
495218893Sdim/// setupBlockStack - Use the live bundles to set up our model of the stack
496212904Sdim/// to match predecessors' live out stack.
497212904Sdimvoid FPS::setupBlockStack() {
498212904Sdim  DEBUG(dbgs() << "\nSetting up live-ins for BB#" << MBB->getNumber()
499212904Sdim               << " derived from " << MBB->getName() << ".\n");
500212904Sdim  StackTop = 0;
501218893Sdim  // Get the live-in bundle for MBB.
502218893Sdim  const LiveBundle &Bundle =
503218893Sdim    LiveBundles[Bundles->getBundle(MBB->getNumber(), false)];
504212904Sdim
505212904Sdim  if (!Bundle.Mask) {
506212904Sdim    DEBUG(dbgs() << "Block has no FP live-ins.\n");
507212904Sdim    return;
508212904Sdim  }
509212904Sdim
510212904Sdim  // Depth-first iteration should ensure that we always have an assigned stack.
511212904Sdim  assert(Bundle.isFixed() && "Reached block before any predecessors");
512212904Sdim
513212904Sdim  // Push the fixed live-in registers.
514212904Sdim  for (unsigned i = Bundle.FixCount; i > 0; --i) {
515212904Sdim    MBB->addLiveIn(X86::ST0+i-1);
516212904Sdim    DEBUG(dbgs() << "Live-in st(" << (i-1) << "): %FP"
517212904Sdim                 << unsigned(Bundle.FixStack[i-1]) << '\n');
518212904Sdim    pushReg(Bundle.FixStack[i-1]);
519212904Sdim  }
520212904Sdim
521212904Sdim  // Kill off unwanted live-ins. This can happen with a critical edge.
522212904Sdim  // FIXME: We could keep these live registers around as zombies. They may need
523212904Sdim  // to be revived at the end of a short block. It might save a few instrs.
524212904Sdim  adjustLiveRegs(calcLiveInMask(MBB), MBB->begin());
525212904Sdim  DEBUG(MBB->dump());
526212904Sdim}
527212904Sdim
528212904Sdim/// finishBlockStack - Revive live-outs that are implicitly defined out of
529212904Sdim/// MBB. Shuffle live registers to match the expected fixed stack of any
530212904Sdim/// predecessors, and ensure that all predecessors are expecting the same
531212904Sdim/// stack.
532212904Sdimvoid FPS::finishBlockStack() {
533212904Sdim  // The RET handling below takes care of return blocks for us.
534212904Sdim  if (MBB->succ_empty())
535212904Sdim    return;
536212904Sdim
537212904Sdim  DEBUG(dbgs() << "Setting up live-outs for BB#" << MBB->getNumber()
538212904Sdim               << " derived from " << MBB->getName() << ".\n");
539212904Sdim
540218893Sdim  // Get MBB's live-out bundle.
541218893Sdim  unsigned BundleIdx = Bundles->getBundle(MBB->getNumber(), true);
542212904Sdim  LiveBundle &Bundle = LiveBundles[BundleIdx];
543212904Sdim
544212904Sdim  // We may need to kill and define some registers to match successors.
545212904Sdim  // FIXME: This can probably be combined with the shuffle below.
546212904Sdim  MachineBasicBlock::iterator Term = MBB->getFirstTerminator();
547212904Sdim  adjustLiveRegs(Bundle.Mask, Term);
548212904Sdim
549212904Sdim  if (!Bundle.Mask) {
550212904Sdim    DEBUG(dbgs() << "No live-outs.\n");
551212904Sdim    return;
552212904Sdim  }
553212904Sdim
554212904Sdim  // Has the stack order been fixed yet?
555212904Sdim  DEBUG(dbgs() << "LB#" << BundleIdx << ": ");
556212904Sdim  if (Bundle.isFixed()) {
557212904Sdim    DEBUG(dbgs() << "Shuffling stack to match.\n");
558212904Sdim    shuffleStackTop(Bundle.FixStack, Bundle.FixCount, Term);
559212904Sdim  } else {
560212904Sdim    // Not fixed yet, we get to choose.
561212904Sdim    DEBUG(dbgs() << "Fixing stack order now.\n");
562212904Sdim    Bundle.FixCount = StackTop;
563212904Sdim    for (unsigned i = 0; i < StackTop; ++i)
564212904Sdim      Bundle.FixStack[i] = getStackEntry(i);
565212904Sdim  }
566212904Sdim}
567212904Sdim
568212904Sdim
569193323Sed//===----------------------------------------------------------------------===//
570193323Sed// Efficient Lookup Table Support
571193323Sed//===----------------------------------------------------------------------===//
572193323Sed
573193323Sednamespace {
574193323Sed  struct TableEntry {
575234353Sdim    uint16_t from;
576234353Sdim    uint16_t to;
577193323Sed    bool operator<(const TableEntry &TE) const { return from < TE.from; }
578193323Sed    friend bool operator<(const TableEntry &TE, unsigned V) {
579193323Sed      return TE.from < V;
580193323Sed    }
581243830Sdim    friend bool LLVM_ATTRIBUTE_UNUSED operator<(unsigned V,
582243830Sdim                                                const TableEntry &TE) {
583193323Sed      return V < TE.from;
584193323Sed    }
585193323Sed  };
586193323Sed}
587193323Sed
588193323Sed#ifndef NDEBUG
589193323Sedstatic bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
590193323Sed  for (unsigned i = 0; i != NumEntries-1; ++i)
591193323Sed    if (!(Table[i] < Table[i+1])) return false;
592193323Sed  return true;
593193323Sed}
594193323Sed#endif
595193323Sed
596193323Sedstatic int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
597193323Sed  const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
598193323Sed  if (I != Table+N && I->from == Opcode)
599193323Sed    return I->to;
600193323Sed  return -1;
601193323Sed}
602193323Sed
603193323Sed#ifdef NDEBUG
604193323Sed#define ASSERT_SORTED(TABLE)
605193323Sed#else
606193323Sed#define ASSERT_SORTED(TABLE)                                              \
607193323Sed  { static bool TABLE##Checked = false;                                   \
608193323Sed    if (!TABLE##Checked) {                                                \
609193323Sed       assert(TableIsSorted(TABLE, array_lengthof(TABLE)) &&              \
610193323Sed              "All lookup tables must be sorted for efficient access!");  \
611193323Sed       TABLE##Checked = true;                                             \
612193323Sed    }                                                                     \
613193323Sed  }
614193323Sed#endif
615193323Sed
616193323Sed//===----------------------------------------------------------------------===//
617193323Sed// Register File -> Register Stack Mapping Methods
618193323Sed//===----------------------------------------------------------------------===//
619193323Sed
620193323Sed// OpcodeTable - Sorted map of register instructions to their stack version.
621193323Sed// The first element is an register file pseudo instruction, the second is the
622193323Sed// concrete X86 instruction which uses the register stack.
623193323Sed//
624193323Sedstatic const TableEntry OpcodeTable[] = {
625193323Sed  { X86::ABS_Fp32     , X86::ABS_F     },
626193323Sed  { X86::ABS_Fp64     , X86::ABS_F     },
627193323Sed  { X86::ABS_Fp80     , X86::ABS_F     },
628193323Sed  { X86::ADD_Fp32m    , X86::ADD_F32m  },
629193323Sed  { X86::ADD_Fp64m    , X86::ADD_F64m  },
630193323Sed  { X86::ADD_Fp64m32  , X86::ADD_F32m  },
631193323Sed  { X86::ADD_Fp80m32  , X86::ADD_F32m  },
632193323Sed  { X86::ADD_Fp80m64  , X86::ADD_F64m  },
633193323Sed  { X86::ADD_FpI16m32 , X86::ADD_FI16m },
634193323Sed  { X86::ADD_FpI16m64 , X86::ADD_FI16m },
635193323Sed  { X86::ADD_FpI16m80 , X86::ADD_FI16m },
636193323Sed  { X86::ADD_FpI32m32 , X86::ADD_FI32m },
637193323Sed  { X86::ADD_FpI32m64 , X86::ADD_FI32m },
638193323Sed  { X86::ADD_FpI32m80 , X86::ADD_FI32m },
639193323Sed  { X86::CHS_Fp32     , X86::CHS_F     },
640193323Sed  { X86::CHS_Fp64     , X86::CHS_F     },
641193323Sed  { X86::CHS_Fp80     , X86::CHS_F     },
642193323Sed  { X86::CMOVBE_Fp32  , X86::CMOVBE_F  },
643193323Sed  { X86::CMOVBE_Fp64  , X86::CMOVBE_F  },
644193323Sed  { X86::CMOVBE_Fp80  , X86::CMOVBE_F  },
645193323Sed  { X86::CMOVB_Fp32   , X86::CMOVB_F   },
646193323Sed  { X86::CMOVB_Fp64   , X86::CMOVB_F  },
647193323Sed  { X86::CMOVB_Fp80   , X86::CMOVB_F  },
648193323Sed  { X86::CMOVE_Fp32   , X86::CMOVE_F  },
649193323Sed  { X86::CMOVE_Fp64   , X86::CMOVE_F   },
650193323Sed  { X86::CMOVE_Fp80   , X86::CMOVE_F   },
651193323Sed  { X86::CMOVNBE_Fp32 , X86::CMOVNBE_F },
652193323Sed  { X86::CMOVNBE_Fp64 , X86::CMOVNBE_F },
653193323Sed  { X86::CMOVNBE_Fp80 , X86::CMOVNBE_F },
654193323Sed  { X86::CMOVNB_Fp32  , X86::CMOVNB_F  },
655193323Sed  { X86::CMOVNB_Fp64  , X86::CMOVNB_F  },
656193323Sed  { X86::CMOVNB_Fp80  , X86::CMOVNB_F  },
657193323Sed  { X86::CMOVNE_Fp32  , X86::CMOVNE_F  },
658193323Sed  { X86::CMOVNE_Fp64  , X86::CMOVNE_F  },
659193323Sed  { X86::CMOVNE_Fp80  , X86::CMOVNE_F  },
660193323Sed  { X86::CMOVNP_Fp32  , X86::CMOVNP_F  },
661193323Sed  { X86::CMOVNP_Fp64  , X86::CMOVNP_F  },
662193323Sed  { X86::CMOVNP_Fp80  , X86::CMOVNP_F  },
663193323Sed  { X86::CMOVP_Fp32   , X86::CMOVP_F   },
664193323Sed  { X86::CMOVP_Fp64   , X86::CMOVP_F   },
665193323Sed  { X86::CMOVP_Fp80   , X86::CMOVP_F   },
666193323Sed  { X86::COS_Fp32     , X86::COS_F     },
667193323Sed  { X86::COS_Fp64     , X86::COS_F     },
668193323Sed  { X86::COS_Fp80     , X86::COS_F     },
669193323Sed  { X86::DIVR_Fp32m   , X86::DIVR_F32m },
670193323Sed  { X86::DIVR_Fp64m   , X86::DIVR_F64m },
671193323Sed  { X86::DIVR_Fp64m32 , X86::DIVR_F32m },
672193323Sed  { X86::DIVR_Fp80m32 , X86::DIVR_F32m },
673193323Sed  { X86::DIVR_Fp80m64 , X86::DIVR_F64m },
674193323Sed  { X86::DIVR_FpI16m32, X86::DIVR_FI16m},
675193323Sed  { X86::DIVR_FpI16m64, X86::DIVR_FI16m},
676193323Sed  { X86::DIVR_FpI16m80, X86::DIVR_FI16m},
677193323Sed  { X86::DIVR_FpI32m32, X86::DIVR_FI32m},
678193323Sed  { X86::DIVR_FpI32m64, X86::DIVR_FI32m},
679193323Sed  { X86::DIVR_FpI32m80, X86::DIVR_FI32m},
680193323Sed  { X86::DIV_Fp32m    , X86::DIV_F32m  },
681193323Sed  { X86::DIV_Fp64m    , X86::DIV_F64m  },
682193323Sed  { X86::DIV_Fp64m32  , X86::DIV_F32m  },
683193323Sed  { X86::DIV_Fp80m32  , X86::DIV_F32m  },
684193323Sed  { X86::DIV_Fp80m64  , X86::DIV_F64m  },
685193323Sed  { X86::DIV_FpI16m32 , X86::DIV_FI16m },
686193323Sed  { X86::DIV_FpI16m64 , X86::DIV_FI16m },
687193323Sed  { X86::DIV_FpI16m80 , X86::DIV_FI16m },
688193323Sed  { X86::DIV_FpI32m32 , X86::DIV_FI32m },
689193323Sed  { X86::DIV_FpI32m64 , X86::DIV_FI32m },
690193323Sed  { X86::DIV_FpI32m80 , X86::DIV_FI32m },
691193323Sed  { X86::ILD_Fp16m32  , X86::ILD_F16m  },
692193323Sed  { X86::ILD_Fp16m64  , X86::ILD_F16m  },
693193323Sed  { X86::ILD_Fp16m80  , X86::ILD_F16m  },
694193323Sed  { X86::ILD_Fp32m32  , X86::ILD_F32m  },
695193323Sed  { X86::ILD_Fp32m64  , X86::ILD_F32m  },
696193323Sed  { X86::ILD_Fp32m80  , X86::ILD_F32m  },
697193323Sed  { X86::ILD_Fp64m32  , X86::ILD_F64m  },
698193323Sed  { X86::ILD_Fp64m64  , X86::ILD_F64m  },
699193323Sed  { X86::ILD_Fp64m80  , X86::ILD_F64m  },
700193323Sed  { X86::ISTT_Fp16m32 , X86::ISTT_FP16m},
701193323Sed  { X86::ISTT_Fp16m64 , X86::ISTT_FP16m},
702193323Sed  { X86::ISTT_Fp16m80 , X86::ISTT_FP16m},
703193323Sed  { X86::ISTT_Fp32m32 , X86::ISTT_FP32m},
704193323Sed  { X86::ISTT_Fp32m64 , X86::ISTT_FP32m},
705193323Sed  { X86::ISTT_Fp32m80 , X86::ISTT_FP32m},
706193323Sed  { X86::ISTT_Fp64m32 , X86::ISTT_FP64m},
707193323Sed  { X86::ISTT_Fp64m64 , X86::ISTT_FP64m},
708193323Sed  { X86::ISTT_Fp64m80 , X86::ISTT_FP64m},
709193323Sed  { X86::IST_Fp16m32  , X86::IST_F16m  },
710193323Sed  { X86::IST_Fp16m64  , X86::IST_F16m  },
711193323Sed  { X86::IST_Fp16m80  , X86::IST_F16m  },
712193323Sed  { X86::IST_Fp32m32  , X86::IST_F32m  },
713193323Sed  { X86::IST_Fp32m64  , X86::IST_F32m  },
714193323Sed  { X86::IST_Fp32m80  , X86::IST_F32m  },
715193323Sed  { X86::IST_Fp64m32  , X86::IST_FP64m },
716193323Sed  { X86::IST_Fp64m64  , X86::IST_FP64m },
717193323Sed  { X86::IST_Fp64m80  , X86::IST_FP64m },
718193323Sed  { X86::LD_Fp032     , X86::LD_F0     },
719193323Sed  { X86::LD_Fp064     , X86::LD_F0     },
720193323Sed  { X86::LD_Fp080     , X86::LD_F0     },
721193323Sed  { X86::LD_Fp132     , X86::LD_F1     },
722193323Sed  { X86::LD_Fp164     , X86::LD_F1     },
723193323Sed  { X86::LD_Fp180     , X86::LD_F1     },
724193323Sed  { X86::LD_Fp32m     , X86::LD_F32m   },
725193323Sed  { X86::LD_Fp32m64   , X86::LD_F32m   },
726193323Sed  { X86::LD_Fp32m80   , X86::LD_F32m   },
727193323Sed  { X86::LD_Fp64m     , X86::LD_F64m   },
728193323Sed  { X86::LD_Fp64m80   , X86::LD_F64m   },
729193323Sed  { X86::LD_Fp80m     , X86::LD_F80m   },
730193323Sed  { X86::MUL_Fp32m    , X86::MUL_F32m  },
731193323Sed  { X86::MUL_Fp64m    , X86::MUL_F64m  },
732193323Sed  { X86::MUL_Fp64m32  , X86::MUL_F32m  },
733193323Sed  { X86::MUL_Fp80m32  , X86::MUL_F32m  },
734193323Sed  { X86::MUL_Fp80m64  , X86::MUL_F64m  },
735193323Sed  { X86::MUL_FpI16m32 , X86::MUL_FI16m },
736193323Sed  { X86::MUL_FpI16m64 , X86::MUL_FI16m },
737193323Sed  { X86::MUL_FpI16m80 , X86::MUL_FI16m },
738193323Sed  { X86::MUL_FpI32m32 , X86::MUL_FI32m },
739193323Sed  { X86::MUL_FpI32m64 , X86::MUL_FI32m },
740193323Sed  { X86::MUL_FpI32m80 , X86::MUL_FI32m },
741193323Sed  { X86::SIN_Fp32     , X86::SIN_F     },
742193323Sed  { X86::SIN_Fp64     , X86::SIN_F     },
743193323Sed  { X86::SIN_Fp80     , X86::SIN_F     },
744193323Sed  { X86::SQRT_Fp32    , X86::SQRT_F    },
745193323Sed  { X86::SQRT_Fp64    , X86::SQRT_F    },
746193323Sed  { X86::SQRT_Fp80    , X86::SQRT_F    },
747193323Sed  { X86::ST_Fp32m     , X86::ST_F32m   },
748193323Sed  { X86::ST_Fp64m     , X86::ST_F64m   },
749193323Sed  { X86::ST_Fp64m32   , X86::ST_F32m   },
750193323Sed  { X86::ST_Fp80m32   , X86::ST_F32m   },
751193323Sed  { X86::ST_Fp80m64   , X86::ST_F64m   },
752193323Sed  { X86::ST_FpP80m    , X86::ST_FP80m  },
753193323Sed  { X86::SUBR_Fp32m   , X86::SUBR_F32m },
754193323Sed  { X86::SUBR_Fp64m   , X86::SUBR_F64m },
755193323Sed  { X86::SUBR_Fp64m32 , X86::SUBR_F32m },
756193323Sed  { X86::SUBR_Fp80m32 , X86::SUBR_F32m },
757193323Sed  { X86::SUBR_Fp80m64 , X86::SUBR_F64m },
758193323Sed  { X86::SUBR_FpI16m32, X86::SUBR_FI16m},
759193323Sed  { X86::SUBR_FpI16m64, X86::SUBR_FI16m},
760193323Sed  { X86::SUBR_FpI16m80, X86::SUBR_FI16m},
761193323Sed  { X86::SUBR_FpI32m32, X86::SUBR_FI32m},
762193323Sed  { X86::SUBR_FpI32m64, X86::SUBR_FI32m},
763193323Sed  { X86::SUBR_FpI32m80, X86::SUBR_FI32m},
764193323Sed  { X86::SUB_Fp32m    , X86::SUB_F32m  },
765193323Sed  { X86::SUB_Fp64m    , X86::SUB_F64m  },
766193323Sed  { X86::SUB_Fp64m32  , X86::SUB_F32m  },
767193323Sed  { X86::SUB_Fp80m32  , X86::SUB_F32m  },
768193323Sed  { X86::SUB_Fp80m64  , X86::SUB_F64m  },
769193323Sed  { X86::SUB_FpI16m32 , X86::SUB_FI16m },
770193323Sed  { X86::SUB_FpI16m64 , X86::SUB_FI16m },
771193323Sed  { X86::SUB_FpI16m80 , X86::SUB_FI16m },
772193323Sed  { X86::SUB_FpI32m32 , X86::SUB_FI32m },
773193323Sed  { X86::SUB_FpI32m64 , X86::SUB_FI32m },
774193323Sed  { X86::SUB_FpI32m80 , X86::SUB_FI32m },
775193323Sed  { X86::TST_Fp32     , X86::TST_F     },
776193323Sed  { X86::TST_Fp64     , X86::TST_F     },
777193323Sed  { X86::TST_Fp80     , X86::TST_F     },
778193323Sed  { X86::UCOM_FpIr32  , X86::UCOM_FIr  },
779193323Sed  { X86::UCOM_FpIr64  , X86::UCOM_FIr  },
780193323Sed  { X86::UCOM_FpIr80  , X86::UCOM_FIr  },
781193323Sed  { X86::UCOM_Fpr32   , X86::UCOM_Fr   },
782193323Sed  { X86::UCOM_Fpr64   , X86::UCOM_Fr   },
783193323Sed  { X86::UCOM_Fpr80   , X86::UCOM_Fr   },
784193323Sed};
785193323Sed
786193323Sedstatic unsigned getConcreteOpcode(unsigned Opcode) {
787193323Sed  ASSERT_SORTED(OpcodeTable);
788193323Sed  int Opc = Lookup(OpcodeTable, array_lengthof(OpcodeTable), Opcode);
789193323Sed  assert(Opc != -1 && "FP Stack instruction not in OpcodeTable!");
790193323Sed  return Opc;
791193323Sed}
792193323Sed
793193323Sed//===----------------------------------------------------------------------===//
794193323Sed// Helper Methods
795193323Sed//===----------------------------------------------------------------------===//
796193323Sed
797193323Sed// PopTable - Sorted map of instructions to their popping version.  The first
798193323Sed// element is an instruction, the second is the version which pops.
799193323Sed//
800193323Sedstatic const TableEntry PopTable[] = {
801193323Sed  { X86::ADD_FrST0 , X86::ADD_FPrST0  },
802193323Sed
803193323Sed  { X86::DIVR_FrST0, X86::DIVR_FPrST0 },
804193323Sed  { X86::DIV_FrST0 , X86::DIV_FPrST0  },
805193323Sed
806193323Sed  { X86::IST_F16m  , X86::IST_FP16m   },
807193323Sed  { X86::IST_F32m  , X86::IST_FP32m   },
808193323Sed
809193323Sed  { X86::MUL_FrST0 , X86::MUL_FPrST0  },
810193323Sed
811193323Sed  { X86::ST_F32m   , X86::ST_FP32m    },
812193323Sed  { X86::ST_F64m   , X86::ST_FP64m    },
813193323Sed  { X86::ST_Frr    , X86::ST_FPrr     },
814193323Sed
815193323Sed  { X86::SUBR_FrST0, X86::SUBR_FPrST0 },
816193323Sed  { X86::SUB_FrST0 , X86::SUB_FPrST0  },
817193323Sed
818193323Sed  { X86::UCOM_FIr  , X86::UCOM_FIPr   },
819193323Sed
820193323Sed  { X86::UCOM_FPr  , X86::UCOM_FPPr   },
821193323Sed  { X86::UCOM_Fr   , X86::UCOM_FPr    },
822193323Sed};
823193323Sed
824193323Sed/// popStackAfter - Pop the current value off of the top of the FP stack after
825193323Sed/// the specified instruction.  This attempts to be sneaky and combine the pop
826193323Sed/// into the instruction itself if possible.  The iterator is left pointing to
827193323Sed/// the last instruction, be it a new pop instruction inserted, or the old
828193323Sed/// instruction if it was modified in place.
829193323Sed///
830193323Sedvoid FPS::popStackAfter(MachineBasicBlock::iterator &I) {
831193323Sed  MachineInstr* MI = I;
832193323Sed  DebugLoc dl = MI->getDebugLoc();
833193323Sed  ASSERT_SORTED(PopTable);
834218893Sdim  if (StackTop == 0)
835218893Sdim    report_fatal_error("Cannot pop empty stack!");
836193323Sed  RegMap[Stack[--StackTop]] = ~0;     // Update state
837193323Sed
838193323Sed  // Check to see if there is a popping version of this instruction...
839193323Sed  int Opcode = Lookup(PopTable, array_lengthof(PopTable), I->getOpcode());
840193323Sed  if (Opcode != -1) {
841193323Sed    I->setDesc(TII->get(Opcode));
842193323Sed    if (Opcode == X86::UCOM_FPPr)
843193323Sed      I->RemoveOperand(0);
844193323Sed  } else {    // Insert an explicit pop
845193323Sed    I = BuildMI(*MBB, ++I, dl, TII->get(X86::ST_FPrr)).addReg(X86::ST0);
846193323Sed  }
847193323Sed}
848193323Sed
849193323Sed/// freeStackSlotAfter - Free the specified register from the register stack, so
850193323Sed/// that it is no longer in a register.  If the register is currently at the top
851193323Sed/// of the stack, we just pop the current instruction, otherwise we store the
852193323Sed/// current top-of-stack into the specified slot, then pop the top of stack.
853193323Sedvoid FPS::freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned FPRegNo) {
854193323Sed  if (getStackEntry(0) == FPRegNo) {  // already at the top of stack? easy.
855193323Sed    popStackAfter(I);
856193323Sed    return;
857193323Sed  }
858193323Sed
859193323Sed  // Otherwise, store the top of stack into the dead slot, killing the operand
860193323Sed  // without having to add in an explicit xchg then pop.
861193323Sed  //
862212904Sdim  I = freeStackSlotBefore(++I, FPRegNo);
863212904Sdim}
864212904Sdim
865212904Sdim/// freeStackSlotBefore - Free the specified register without trying any
866212904Sdim/// folding.
867212904SdimMachineBasicBlock::iterator
868212904SdimFPS::freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo) {
869193323Sed  unsigned STReg    = getSTReg(FPRegNo);
870193323Sed  unsigned OldSlot  = getSlot(FPRegNo);
871193323Sed  unsigned TopReg   = Stack[StackTop-1];
872193323Sed  Stack[OldSlot]    = TopReg;
873193323Sed  RegMap[TopReg]    = OldSlot;
874193323Sed  RegMap[FPRegNo]   = ~0;
875193323Sed  Stack[--StackTop] = ~0;
876212904Sdim  return BuildMI(*MBB, I, DebugLoc(), TII->get(X86::ST_FPrr)).addReg(STReg);
877193323Sed}
878193323Sed
879212904Sdim/// adjustLiveRegs - Kill and revive registers such that exactly the FP
880212904Sdim/// registers with a bit in Mask are live.
881212904Sdimvoid FPS::adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I) {
882212904Sdim  unsigned Defs = Mask;
883212904Sdim  unsigned Kills = 0;
884212904Sdim  for (unsigned i = 0; i < StackTop; ++i) {
885212904Sdim    unsigned RegNo = Stack[i];
886212904Sdim    if (!(Defs & (1 << RegNo)))
887212904Sdim      // This register is live, but we don't want it.
888212904Sdim      Kills |= (1 << RegNo);
889212904Sdim    else
890212904Sdim      // We don't need to imp-def this live register.
891212904Sdim      Defs &= ~(1 << RegNo);
892212904Sdim  }
893212904Sdim  assert((Kills & Defs) == 0 && "Register needs killing and def'ing?");
894193323Sed
895212904Sdim  // Produce implicit-defs for free by using killed registers.
896212904Sdim  while (Kills && Defs) {
897263508Sdim    unsigned KReg = countTrailingZeros(Kills);
898263508Sdim    unsigned DReg = countTrailingZeros(Defs);
899212904Sdim    DEBUG(dbgs() << "Renaming %FP" << KReg << " as imp %FP" << DReg << "\n");
900212904Sdim    std::swap(Stack[getSlot(KReg)], Stack[getSlot(DReg)]);
901212904Sdim    std::swap(RegMap[KReg], RegMap[DReg]);
902212904Sdim    Kills &= ~(1 << KReg);
903212904Sdim    Defs &= ~(1 << DReg);
904212904Sdim  }
905212904Sdim
906212904Sdim  // Kill registers by popping.
907212904Sdim  if (Kills && I != MBB->begin()) {
908212904Sdim    MachineBasicBlock::iterator I2 = llvm::prior(I);
909224145Sdim    while (StackTop) {
910212904Sdim      unsigned KReg = getStackEntry(0);
911212904Sdim      if (!(Kills & (1 << KReg)))
912212904Sdim        break;
913212904Sdim      DEBUG(dbgs() << "Popping %FP" << KReg << "\n");
914212904Sdim      popStackAfter(I2);
915212904Sdim      Kills &= ~(1 << KReg);
916212904Sdim    }
917212904Sdim  }
918212904Sdim
919212904Sdim  // Manually kill the rest.
920212904Sdim  while (Kills) {
921263508Sdim    unsigned KReg = countTrailingZeros(Kills);
922212904Sdim    DEBUG(dbgs() << "Killing %FP" << KReg << "\n");
923212904Sdim    freeStackSlotBefore(I, KReg);
924212904Sdim    Kills &= ~(1 << KReg);
925212904Sdim  }
926212904Sdim
927212904Sdim  // Load zeros for all the imp-defs.
928212904Sdim  while(Defs) {
929263508Sdim    unsigned DReg = countTrailingZeros(Defs);
930212904Sdim    DEBUG(dbgs() << "Defining %FP" << DReg << " as 0\n");
931212904Sdim    BuildMI(*MBB, I, DebugLoc(), TII->get(X86::LD_F0));
932212904Sdim    pushReg(DReg);
933212904Sdim    Defs &= ~(1 << DReg);
934212904Sdim  }
935212904Sdim
936212904Sdim  // Now we should have the correct registers live.
937212904Sdim  DEBUG(dumpStack());
938212904Sdim  assert(StackTop == CountPopulation_32(Mask) && "Live count mismatch");
939212904Sdim}
940212904Sdim
941212904Sdim/// shuffleStackTop - emit fxch instructions before I to shuffle the top
942212904Sdim/// FixCount entries into the order given by FixStack.
943212904Sdim/// FIXME: Is there a better algorithm than insertion sort?
944212904Sdimvoid FPS::shuffleStackTop(const unsigned char *FixStack,
945212904Sdim                          unsigned FixCount,
946212904Sdim                          MachineBasicBlock::iterator I) {
947212904Sdim  // Move items into place, starting from the desired stack bottom.
948212904Sdim  while (FixCount--) {
949212904Sdim    // Old register at position FixCount.
950212904Sdim    unsigned OldReg = getStackEntry(FixCount);
951212904Sdim    // Desired register at position FixCount.
952212904Sdim    unsigned Reg = FixStack[FixCount];
953212904Sdim    if (Reg == OldReg)
954212904Sdim      continue;
955212904Sdim    // (Reg st0) (OldReg st0) = (Reg OldReg st0)
956212904Sdim    moveToTop(Reg, I);
957224145Sdim    if (FixCount > 0)
958224145Sdim      moveToTop(OldReg, I);
959212904Sdim  }
960212904Sdim  DEBUG(dumpStack());
961212904Sdim}
962212904Sdim
963212904Sdim
964193323Sed//===----------------------------------------------------------------------===//
965193323Sed// Instruction transformation implementation
966193323Sed//===----------------------------------------------------------------------===//
967193323Sed
968193323Sed/// handleZeroArgFP - ST(0) = fld0    ST(0) = flds <mem>
969193323Sed///
970193323Sedvoid FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
971193323Sed  MachineInstr *MI = I;
972193323Sed  unsigned DestReg = getFPReg(MI->getOperand(0));
973193323Sed
974193323Sed  // Change from the pseudo instruction to the concrete instruction.
975193323Sed  MI->RemoveOperand(0);   // Remove the explicit ST(0) operand
976193323Sed  MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
977239462Sdim
978193323Sed  // Result gets pushed on the stack.
979193323Sed  pushReg(DestReg);
980193323Sed}
981193323Sed
982193323Sed/// handleOneArgFP - fst <mem>, ST(0)
983193323Sed///
984193323Sedvoid FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
985193323Sed  MachineInstr *MI = I;
986193323Sed  unsigned NumOps = MI->getDesc().getNumOperands();
987210299Sed  assert((NumOps == X86::AddrNumOperands + 1 || NumOps == 1) &&
988193323Sed         "Can only handle fst* & ftst instructions!");
989193323Sed
990193323Sed  // Is this the last use of the source register?
991193323Sed  unsigned Reg = getFPReg(MI->getOperand(NumOps-1));
992193323Sed  bool KillsSrc = MI->killsRegister(X86::FP0+Reg);
993193323Sed
994226633Sdim  if (KillsSrc)
995226633Sdim    duplicatePendingSTBeforeKill(Reg, I);
996226633Sdim
997193323Sed  // FISTP64m is strange because there isn't a non-popping versions.
998193323Sed  // If we have one _and_ we don't want to pop the operand, duplicate the value
999193323Sed  // on the stack instead of moving it.  This ensure that popping the value is
1000193323Sed  // always ok.
1001193323Sed  // Ditto FISTTP16m, FISTTP32m, FISTTP64m, ST_FpP80m.
1002193323Sed  //
1003193323Sed  if (!KillsSrc &&
1004193323Sed      (MI->getOpcode() == X86::IST_Fp64m32 ||
1005193323Sed       MI->getOpcode() == X86::ISTT_Fp16m32 ||
1006193323Sed       MI->getOpcode() == X86::ISTT_Fp32m32 ||
1007193323Sed       MI->getOpcode() == X86::ISTT_Fp64m32 ||
1008193323Sed       MI->getOpcode() == X86::IST_Fp64m64 ||
1009193323Sed       MI->getOpcode() == X86::ISTT_Fp16m64 ||
1010193323Sed       MI->getOpcode() == X86::ISTT_Fp32m64 ||
1011193323Sed       MI->getOpcode() == X86::ISTT_Fp64m64 ||
1012193323Sed       MI->getOpcode() == X86::IST_Fp64m80 ||
1013193323Sed       MI->getOpcode() == X86::ISTT_Fp16m80 ||
1014193323Sed       MI->getOpcode() == X86::ISTT_Fp32m80 ||
1015193323Sed       MI->getOpcode() == X86::ISTT_Fp64m80 ||
1016193323Sed       MI->getOpcode() == X86::ST_FpP80m)) {
1017212904Sdim    duplicateToTop(Reg, getScratchReg(), I);
1018193323Sed  } else {
1019193323Sed    moveToTop(Reg, I);            // Move to the top of the stack...
1020193323Sed  }
1021239462Sdim
1022193323Sed  // Convert from the pseudo instruction to the concrete instruction.
1023193323Sed  MI->RemoveOperand(NumOps-1);    // Remove explicit ST(0) operand
1024193323Sed  MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1025193323Sed
1026193323Sed  if (MI->getOpcode() == X86::IST_FP64m ||
1027193323Sed      MI->getOpcode() == X86::ISTT_FP16m ||
1028193323Sed      MI->getOpcode() == X86::ISTT_FP32m ||
1029193323Sed      MI->getOpcode() == X86::ISTT_FP64m ||
1030193323Sed      MI->getOpcode() == X86::ST_FP80m) {
1031218893Sdim    if (StackTop == 0)
1032218893Sdim      report_fatal_error("Stack empty??");
1033193323Sed    --StackTop;
1034193323Sed  } else if (KillsSrc) { // Last use of operand?
1035193323Sed    popStackAfter(I);
1036193323Sed  }
1037193323Sed}
1038193323Sed
1039193323Sed
1040193323Sed/// handleOneArgFPRW: Handle instructions that read from the top of stack and
1041193323Sed/// replace the value with a newly computed value.  These instructions may have
1042193323Sed/// non-fp operands after their FP operands.
1043193323Sed///
1044193323Sed///  Examples:
1045193323Sed///     R1 = fchs R2
1046193323Sed///     R1 = fadd R2, [mem]
1047193323Sed///
1048193323Sedvoid FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {
1049193323Sed  MachineInstr *MI = I;
1050193323Sed#ifndef NDEBUG
1051193323Sed  unsigned NumOps = MI->getDesc().getNumOperands();
1052193323Sed  assert(NumOps >= 2 && "FPRW instructions must have 2 ops!!");
1053193323Sed#endif
1054193323Sed
1055193323Sed  // Is this the last use of the source register?
1056193323Sed  unsigned Reg = getFPReg(MI->getOperand(1));
1057193323Sed  bool KillsSrc = MI->killsRegister(X86::FP0+Reg);
1058193323Sed
1059193323Sed  if (KillsSrc) {
1060226633Sdim    duplicatePendingSTBeforeKill(Reg, I);
1061193323Sed    // If this is the last use of the source register, just make sure it's on
1062193323Sed    // the top of the stack.
1063193323Sed    moveToTop(Reg, I);
1064218893Sdim    if (StackTop == 0)
1065218893Sdim      report_fatal_error("Stack cannot be empty!");
1066193323Sed    --StackTop;
1067193323Sed    pushReg(getFPReg(MI->getOperand(0)));
1068193323Sed  } else {
1069193323Sed    // If this is not the last use of the source register, _copy_ it to the top
1070193323Sed    // of the stack.
1071193323Sed    duplicateToTop(Reg, getFPReg(MI->getOperand(0)), I);
1072193323Sed  }
1073193323Sed
1074193323Sed  // Change from the pseudo instruction to the concrete instruction.
1075193323Sed  MI->RemoveOperand(1);   // Drop the source operand.
1076193323Sed  MI->RemoveOperand(0);   // Drop the destination operand.
1077193323Sed  MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1078193323Sed}
1079193323Sed
1080193323Sed
1081193323Sed//===----------------------------------------------------------------------===//
1082193323Sed// Define tables of various ways to map pseudo instructions
1083193323Sed//
1084193323Sed
1085193323Sed// ForwardST0Table - Map: A = B op C  into: ST(0) = ST(0) op ST(i)
1086193323Sedstatic const TableEntry ForwardST0Table[] = {
1087193323Sed  { X86::ADD_Fp32  , X86::ADD_FST0r },
1088193323Sed  { X86::ADD_Fp64  , X86::ADD_FST0r },
1089193323Sed  { X86::ADD_Fp80  , X86::ADD_FST0r },
1090193323Sed  { X86::DIV_Fp32  , X86::DIV_FST0r },
1091193323Sed  { X86::DIV_Fp64  , X86::DIV_FST0r },
1092193323Sed  { X86::DIV_Fp80  , X86::DIV_FST0r },
1093193323Sed  { X86::MUL_Fp32  , X86::MUL_FST0r },
1094193323Sed  { X86::MUL_Fp64  , X86::MUL_FST0r },
1095193323Sed  { X86::MUL_Fp80  , X86::MUL_FST0r },
1096193323Sed  { X86::SUB_Fp32  , X86::SUB_FST0r },
1097193323Sed  { X86::SUB_Fp64  , X86::SUB_FST0r },
1098193323Sed  { X86::SUB_Fp80  , X86::SUB_FST0r },
1099193323Sed};
1100193323Sed
1101193323Sed// ReverseST0Table - Map: A = B op C  into: ST(0) = ST(i) op ST(0)
1102193323Sedstatic const TableEntry ReverseST0Table[] = {
1103193323Sed  { X86::ADD_Fp32  , X86::ADD_FST0r  },   // commutative
1104193323Sed  { X86::ADD_Fp64  , X86::ADD_FST0r  },   // commutative
1105193323Sed  { X86::ADD_Fp80  , X86::ADD_FST0r  },   // commutative
1106193323Sed  { X86::DIV_Fp32  , X86::DIVR_FST0r },
1107193323Sed  { X86::DIV_Fp64  , X86::DIVR_FST0r },
1108193323Sed  { X86::DIV_Fp80  , X86::DIVR_FST0r },
1109193323Sed  { X86::MUL_Fp32  , X86::MUL_FST0r  },   // commutative
1110193323Sed  { X86::MUL_Fp64  , X86::MUL_FST0r  },   // commutative
1111193323Sed  { X86::MUL_Fp80  , X86::MUL_FST0r  },   // commutative
1112193323Sed  { X86::SUB_Fp32  , X86::SUBR_FST0r },
1113193323Sed  { X86::SUB_Fp64  , X86::SUBR_FST0r },
1114193323Sed  { X86::SUB_Fp80  , X86::SUBR_FST0r },
1115193323Sed};
1116193323Sed
1117193323Sed// ForwardSTiTable - Map: A = B op C  into: ST(i) = ST(0) op ST(i)
1118193323Sedstatic const TableEntry ForwardSTiTable[] = {
1119193323Sed  { X86::ADD_Fp32  , X86::ADD_FrST0  },   // commutative
1120193323Sed  { X86::ADD_Fp64  , X86::ADD_FrST0  },   // commutative
1121193323Sed  { X86::ADD_Fp80  , X86::ADD_FrST0  },   // commutative
1122193323Sed  { X86::DIV_Fp32  , X86::DIVR_FrST0 },
1123193323Sed  { X86::DIV_Fp64  , X86::DIVR_FrST0 },
1124193323Sed  { X86::DIV_Fp80  , X86::DIVR_FrST0 },
1125193323Sed  { X86::MUL_Fp32  , X86::MUL_FrST0  },   // commutative
1126193323Sed  { X86::MUL_Fp64  , X86::MUL_FrST0  },   // commutative
1127193323Sed  { X86::MUL_Fp80  , X86::MUL_FrST0  },   // commutative
1128193323Sed  { X86::SUB_Fp32  , X86::SUBR_FrST0 },
1129193323Sed  { X86::SUB_Fp64  , X86::SUBR_FrST0 },
1130193323Sed  { X86::SUB_Fp80  , X86::SUBR_FrST0 },
1131193323Sed};
1132193323Sed
1133193323Sed// ReverseSTiTable - Map: A = B op C  into: ST(i) = ST(i) op ST(0)
1134193323Sedstatic const TableEntry ReverseSTiTable[] = {
1135193323Sed  { X86::ADD_Fp32  , X86::ADD_FrST0 },
1136193323Sed  { X86::ADD_Fp64  , X86::ADD_FrST0 },
1137193323Sed  { X86::ADD_Fp80  , X86::ADD_FrST0 },
1138193323Sed  { X86::DIV_Fp32  , X86::DIV_FrST0 },
1139193323Sed  { X86::DIV_Fp64  , X86::DIV_FrST0 },
1140193323Sed  { X86::DIV_Fp80  , X86::DIV_FrST0 },
1141193323Sed  { X86::MUL_Fp32  , X86::MUL_FrST0 },
1142193323Sed  { X86::MUL_Fp64  , X86::MUL_FrST0 },
1143193323Sed  { X86::MUL_Fp80  , X86::MUL_FrST0 },
1144193323Sed  { X86::SUB_Fp32  , X86::SUB_FrST0 },
1145193323Sed  { X86::SUB_Fp64  , X86::SUB_FrST0 },
1146193323Sed  { X86::SUB_Fp80  , X86::SUB_FrST0 },
1147193323Sed};
1148193323Sed
1149193323Sed
1150193323Sed/// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
1151193323Sed/// instructions which need to be simplified and possibly transformed.
1152193323Sed///
1153193323Sed/// Result: ST(0) = fsub  ST(0), ST(i)
1154193323Sed///         ST(i) = fsub  ST(0), ST(i)
1155193323Sed///         ST(0) = fsubr ST(0), ST(i)
1156193323Sed///         ST(i) = fsubr ST(0), ST(i)
1157193323Sed///
1158193323Sedvoid FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
1159193323Sed  ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
1160193323Sed  ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
1161193323Sed  MachineInstr *MI = I;
1162193323Sed
1163193323Sed  unsigned NumOperands = MI->getDesc().getNumOperands();
1164193323Sed  assert(NumOperands == 3 && "Illegal TwoArgFP instruction!");
1165193323Sed  unsigned Dest = getFPReg(MI->getOperand(0));
1166193323Sed  unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
1167193323Sed  unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
1168193323Sed  bool KillsOp0 = MI->killsRegister(X86::FP0+Op0);
1169193323Sed  bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1170193323Sed  DebugLoc dl = MI->getDebugLoc();
1171193323Sed
1172193323Sed  unsigned TOS = getStackEntry(0);
1173193323Sed
1174193323Sed  // One of our operands must be on the top of the stack.  If neither is yet, we
1175193323Sed  // need to move one.
1176193323Sed  if (Op0 != TOS && Op1 != TOS) {   // No operand at TOS?
1177193323Sed    // We can choose to move either operand to the top of the stack.  If one of
1178193323Sed    // the operands is killed by this instruction, we want that one so that we
1179193323Sed    // can update right on top of the old version.
1180193323Sed    if (KillsOp0) {
1181193323Sed      moveToTop(Op0, I);         // Move dead operand to TOS.
1182193323Sed      TOS = Op0;
1183193323Sed    } else if (KillsOp1) {
1184193323Sed      moveToTop(Op1, I);
1185193323Sed      TOS = Op1;
1186193323Sed    } else {
1187193323Sed      // All of the operands are live after this instruction executes, so we
1188193323Sed      // cannot update on top of any operand.  Because of this, we must
1189193323Sed      // duplicate one of the stack elements to the top.  It doesn't matter
1190193323Sed      // which one we pick.
1191193323Sed      //
1192193323Sed      duplicateToTop(Op0, Dest, I);
1193193323Sed      Op0 = TOS = Dest;
1194193323Sed      KillsOp0 = true;
1195193323Sed    }
1196193323Sed  } else if (!KillsOp0 && !KillsOp1) {
1197193323Sed    // If we DO have one of our operands at the top of the stack, but we don't
1198193323Sed    // have a dead operand, we must duplicate one of the operands to a new slot
1199193323Sed    // on the stack.
1200193323Sed    duplicateToTop(Op0, Dest, I);
1201193323Sed    Op0 = TOS = Dest;
1202193323Sed    KillsOp0 = true;
1203193323Sed  }
1204193323Sed
1205193323Sed  // Now we know that one of our operands is on the top of the stack, and at
1206193323Sed  // least one of our operands is killed by this instruction.
1207193323Sed  assert((TOS == Op0 || TOS == Op1) && (KillsOp0 || KillsOp1) &&
1208193323Sed         "Stack conditions not set up right!");
1209193323Sed
1210193323Sed  // We decide which form to use based on what is on the top of the stack, and
1211193323Sed  // which operand is killed by this instruction.
1212193323Sed  const TableEntry *InstTable;
1213193323Sed  bool isForward = TOS == Op0;
1214193323Sed  bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
1215193323Sed  if (updateST0) {
1216193323Sed    if (isForward)
1217193323Sed      InstTable = ForwardST0Table;
1218193323Sed    else
1219193323Sed      InstTable = ReverseST0Table;
1220193323Sed  } else {
1221193323Sed    if (isForward)
1222193323Sed      InstTable = ForwardSTiTable;
1223193323Sed    else
1224193323Sed      InstTable = ReverseSTiTable;
1225193323Sed  }
1226193323Sed
1227193323Sed  int Opcode = Lookup(InstTable, array_lengthof(ForwardST0Table),
1228193323Sed                      MI->getOpcode());
1229193323Sed  assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
1230193323Sed
1231193323Sed  // NotTOS - The register which is not on the top of stack...
1232193323Sed  unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
1233193323Sed
1234193323Sed  // Replace the old instruction with a new instruction
1235193323Sed  MBB->remove(I++);
1236193323Sed  I = BuildMI(*MBB, I, dl, TII->get(Opcode)).addReg(getSTReg(NotTOS));
1237193323Sed
1238193323Sed  // If both operands are killed, pop one off of the stack in addition to
1239193323Sed  // overwriting the other one.
1240193323Sed  if (KillsOp0 && KillsOp1 && Op0 != Op1) {
1241193323Sed    assert(!updateST0 && "Should have updated other operand!");
1242193323Sed    popStackAfter(I);   // Pop the top of stack
1243193323Sed  }
1244193323Sed
1245193323Sed  // Update stack information so that we know the destination register is now on
1246193323Sed  // the stack.
1247193323Sed  unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
1248193323Sed  assert(UpdatedSlot < StackTop && Dest < 7);
1249193323Sed  Stack[UpdatedSlot]   = Dest;
1250193323Sed  RegMap[Dest]         = UpdatedSlot;
1251193323Sed  MBB->getParent()->DeleteMachineInstr(MI); // Remove the old instruction
1252193323Sed}
1253193323Sed
1254193323Sed/// handleCompareFP - Handle FUCOM and FUCOMI instructions, which have two FP
1255193323Sed/// register arguments and no explicit destinations.
1256193323Sed///
1257193323Sedvoid FPS::handleCompareFP(MachineBasicBlock::iterator &I) {
1258193323Sed  ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
1259193323Sed  ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
1260193323Sed  MachineInstr *MI = I;
1261193323Sed
1262193323Sed  unsigned NumOperands = MI->getDesc().getNumOperands();
1263193323Sed  assert(NumOperands == 2 && "Illegal FUCOM* instruction!");
1264193323Sed  unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
1265193323Sed  unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
1266193323Sed  bool KillsOp0 = MI->killsRegister(X86::FP0+Op0);
1267193323Sed  bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1268193323Sed
1269193323Sed  // Make sure the first operand is on the top of stack, the other one can be
1270193323Sed  // anywhere.
1271193323Sed  moveToTop(Op0, I);
1272193323Sed
1273193323Sed  // Change from the pseudo instruction to the concrete instruction.
1274193323Sed  MI->getOperand(0).setReg(getSTReg(Op1));
1275193323Sed  MI->RemoveOperand(1);
1276193323Sed  MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1277193323Sed
1278193323Sed  // If any of the operands are killed by this instruction, free them.
1279193323Sed  if (KillsOp0) freeStackSlotAfter(I, Op0);
1280193323Sed  if (KillsOp1 && Op0 != Op1) freeStackSlotAfter(I, Op1);
1281193323Sed}
1282193323Sed
1283193323Sed/// handleCondMovFP - Handle two address conditional move instructions.  These
1284193323Sed/// instructions move a st(i) register to st(0) iff a condition is true.  These
1285193323Sed/// instructions require that the first operand is at the top of the stack, but
1286193323Sed/// otherwise don't modify the stack at all.
1287193323Sedvoid FPS::handleCondMovFP(MachineBasicBlock::iterator &I) {
1288193323Sed  MachineInstr *MI = I;
1289193323Sed
1290193323Sed  unsigned Op0 = getFPReg(MI->getOperand(0));
1291193323Sed  unsigned Op1 = getFPReg(MI->getOperand(2));
1292193323Sed  bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1293193323Sed
1294193323Sed  // The first operand *must* be on the top of the stack.
1295193323Sed  moveToTop(Op0, I);
1296193323Sed
1297193323Sed  // Change the second operand to the stack register that the operand is in.
1298193323Sed  // Change from the pseudo instruction to the concrete instruction.
1299193323Sed  MI->RemoveOperand(0);
1300193323Sed  MI->RemoveOperand(1);
1301193323Sed  MI->getOperand(0).setReg(getSTReg(Op1));
1302193323Sed  MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1303239462Sdim
1304193323Sed  // If we kill the second operand, make sure to pop it from the stack.
1305193323Sed  if (Op0 != Op1 && KillsOp1) {
1306193323Sed    // Get this value off of the register stack.
1307193323Sed    freeStackSlotAfter(I, Op1);
1308193323Sed  }
1309193323Sed}
1310193323Sed
1311193323Sed
1312193323Sed/// handleSpecialFP - Handle special instructions which behave unlike other
1313193323Sed/// floating point instructions.  This is primarily intended for use by pseudo
1314193323Sed/// instructions.
1315193323Sed///
1316193323Sedvoid FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
1317193323Sed  MachineInstr *MI = I;
1318193323Sed  switch (MI->getOpcode()) {
1319198090Srdivacky  default: llvm_unreachable("Unknown SpecialFP instruction!");
1320224145Sdim  case TargetOpcode::COPY: {
1321224145Sdim    // We handle three kinds of copies: FP <- FP, FP <- ST, and ST <- FP.
1322224145Sdim    const MachineOperand &MO1 = MI->getOperand(1);
1323224145Sdim    const MachineOperand &MO0 = MI->getOperand(0);
1324224145Sdim    unsigned DstST = MO0.getReg() - X86::ST0;
1325224145Sdim    unsigned SrcST = MO1.getReg() - X86::ST0;
1326224145Sdim    bool KillsSrc = MI->killsRegister(MO1.getReg());
1327193323Sed
1328224145Sdim    // ST = COPY FP. Set up a pending ST register.
1329224145Sdim    if (DstST < 8) {
1330224145Sdim      unsigned SrcFP = getFPReg(MO1);
1331224145Sdim      assert(isLive(SrcFP) && "Cannot copy dead register");
1332224145Sdim      assert(!MO0.isDead() && "Cannot copy to dead ST register");
1333224145Sdim
1334224145Sdim      // Unallocated STs are marked as the nonexistent FP255.
1335224145Sdim      while (NumPendingSTs <= DstST)
1336224145Sdim        PendingST[NumPendingSTs++] = NumFPRegs;
1337224145Sdim
1338224145Sdim      // STi could still be live from a previous inline asm.
1339224145Sdim      if (isScratchReg(PendingST[DstST])) {
1340224145Sdim        DEBUG(dbgs() << "Clobbering old ST in FP" << unsigned(PendingST[DstST])
1341224145Sdim                     << '\n');
1342224145Sdim        freeStackSlotBefore(MI, PendingST[DstST]);
1343224145Sdim      }
1344224145Sdim
1345224145Sdim      // When the source is killed, allocate a scratch FP register.
1346224145Sdim      if (KillsSrc) {
1347226633Sdim        duplicatePendingSTBeforeKill(SrcFP, I);
1348224145Sdim        unsigned Slot = getSlot(SrcFP);
1349224145Sdim        unsigned SR = getScratchReg();
1350224145Sdim        PendingST[DstST] = SR;
1351224145Sdim        Stack[Slot] = SR;
1352224145Sdim        RegMap[SR] = Slot;
1353224145Sdim      } else
1354224145Sdim        PendingST[DstST] = SrcFP;
1355193323Sed      break;
1356224145Sdim    }
1357195340Sed
1358224145Sdim    // FP = COPY ST. Extract fixed stack value.
1359224145Sdim    // Any instruction defining ST registers must have assigned them to a
1360224145Sdim    // scratch register.
1361224145Sdim    if (SrcST < 8) {
1362224145Sdim      unsigned DstFP = getFPReg(MO0);
1363224145Sdim      assert(!isLive(DstFP) && "Cannot copy ST to live FP register");
1364224145Sdim      assert(NumPendingSTs > SrcST && "Cannot copy from dead ST register");
1365224145Sdim      unsigned SrcFP = PendingST[SrcST];
1366224145Sdim      assert(isScratchReg(SrcFP) && "Expected ST in a scratch register");
1367224145Sdim      assert(isLive(SrcFP) && "Scratch holding ST is dead");
1368224145Sdim
1369224145Sdim      // DstFP steals the stack slot from SrcFP.
1370224145Sdim      unsigned Slot = getSlot(SrcFP);
1371224145Sdim      Stack[Slot] = DstFP;
1372224145Sdim      RegMap[DstFP] = Slot;
1373224145Sdim
1374224145Sdim      // Always treat the ST as killed.
1375224145Sdim      PendingST[SrcST] = NumFPRegs;
1376224145Sdim      while (NumPendingSTs && PendingST[NumPendingSTs - 1] == NumFPRegs)
1377224145Sdim        --NumPendingSTs;
1378224145Sdim      break;
1379194612Sed    }
1380193323Sed
1381224145Sdim    // FP <- FP copy.
1382224145Sdim    unsigned DstFP = getFPReg(MO0);
1383224145Sdim    unsigned SrcFP = getFPReg(MO1);
1384224145Sdim    assert(isLive(SrcFP) && "Cannot copy dead register");
1385224145Sdim    if (KillsSrc) {
1386193323Sed      // If the input operand is killed, we can just change the owner of the
1387193323Sed      // incoming stack slot into the result.
1388224145Sdim      unsigned Slot = getSlot(SrcFP);
1389224145Sdim      Stack[Slot] = DstFP;
1390224145Sdim      RegMap[DstFP] = Slot;
1391193323Sed    } else {
1392224145Sdim      // For COPY we just duplicate the specified value to a new stack slot.
1393193323Sed      // This could be made better, but would require substantial changes.
1394224145Sdim      duplicateToTop(SrcFP, DstFP, I);
1395193323Sed    }
1396224145Sdim    break;
1397224145Sdim  }
1398224145Sdim
1399226633Sdim  case TargetOpcode::IMPLICIT_DEF: {
1400226633Sdim    // All FP registers must be explicitly defined, so load a 0 instead.
1401226633Sdim    unsigned Reg = MI->getOperand(0).getReg() - X86::FP0;
1402226633Sdim    DEBUG(dbgs() << "Emitting LD_F0 for implicit FP" << Reg << '\n');
1403226633Sdim    BuildMI(*MBB, I, MI->getDebugLoc(), TII->get(X86::LD_F0));
1404226633Sdim    pushReg(Reg);
1405226633Sdim    break;
1406226633Sdim  }
1407226633Sdim
1408224145Sdim  case X86::FpPOP_RETVAL: {
1409224145Sdim    // The FpPOP_RETVAL instruction is used after calls that return a value on
1410224145Sdim    // the floating point stack. We cannot model this with ST defs since CALL
1411224145Sdim    // instructions have fixed clobber lists. This instruction is interpreted
1412224145Sdim    // to mean that there is one more live register on the stack than we
1413224145Sdim    // thought.
1414224145Sdim    //
1415224145Sdim    // This means that StackTop does not match the hardware stack between a
1416224145Sdim    // call and the FpPOP_RETVAL instructions.  We do tolerate FP instructions
1417224145Sdim    // between CALL and FpPOP_RETVAL as long as they don't overflow the
1418224145Sdim    // hardware stack.
1419224145Sdim    unsigned DstFP = getFPReg(MI->getOperand(0));
1420224145Sdim
1421224145Sdim    // Move existing stack elements up to reflect reality.
1422224145Sdim    assert(StackTop < 8 && "Stack overflowed before FpPOP_RETVAL");
1423224145Sdim    if (StackTop) {
1424224145Sdim      std::copy_backward(Stack, Stack + StackTop, Stack + StackTop + 1);
1425224145Sdim      for (unsigned i = 0; i != NumFPRegs; ++i)
1426224145Sdim        ++RegMap[i];
1427193323Sed    }
1428224145Sdim    ++StackTop;
1429224145Sdim
1430224145Sdim    // DstFP is the new bottom of the stack.
1431224145Sdim    Stack[0] = DstFP;
1432224145Sdim    RegMap[DstFP] = 0;
1433224145Sdim
1434224145Sdim    // DstFP will be killed by processBasicBlock if this was a dead def.
1435193323Sed    break;
1436224145Sdim  }
1437224145Sdim
1438203954Srdivacky  case TargetOpcode::INLINEASM: {
1439193323Sed    // The inline asm MachineInstr currently only *uses* FP registers for the
1440193323Sed    // 'f' constraint.  These should be turned into the current ST(x) register
1441224145Sdim    // in the machine instr.
1442224145Sdim    //
1443224145Sdim    // There are special rules for x87 inline assembly. The compiler must know
1444224145Sdim    // exactly how many registers are popped and pushed implicitly by the asm.
1445224145Sdim    // Otherwise it is not possible to restore the stack state after the inline
1446224145Sdim    // asm.
1447224145Sdim    //
1448224145Sdim    // There are 3 kinds of input operands:
1449224145Sdim    //
1450224145Sdim    // 1. Popped inputs. These must appear at the stack top in ST0-STn. A
1451224145Sdim    //    popped input operand must be in a fixed stack slot, and it is either
1452224145Sdim    //    tied to an output operand, or in the clobber list. The MI has ST use
1453224145Sdim    //    and def operands for these inputs.
1454224145Sdim    //
1455224145Sdim    // 2. Fixed inputs. These inputs appear in fixed stack slots, but are
1456224145Sdim    //    preserved by the inline asm. The fixed stack slots must be STn-STm
1457224145Sdim    //    following the popped inputs. A fixed input operand cannot be tied to
1458224145Sdim    //    an output or appear in the clobber list. The MI has ST use operands
1459224145Sdim    //    and no defs for these inputs.
1460224145Sdim    //
1461224145Sdim    // 3. Preserved inputs. These inputs use the "f" constraint which is
1462224145Sdim    //    represented as an FP register. The inline asm won't change these
1463224145Sdim    //    stack slots.
1464224145Sdim    //
1465224145Sdim    // Outputs must be in ST registers, FP outputs are not allowed. Clobbered
1466224145Sdim    // registers do not count as output operands. The inline asm changes the
1467224145Sdim    // stack as if it popped all the popped inputs and then pushed all the
1468224145Sdim    // output operands.
1469224145Sdim
1470224145Sdim    // Scan the assembly for ST registers used, defined and clobbered. We can
1471224145Sdim    // only tell clobbers from defs by looking at the asm descriptor.
1472224145Sdim    unsigned STUses = 0, STDefs = 0, STClobbers = 0, STDeadDefs = 0;
1473224145Sdim    unsigned NumOps = 0;
1474224145Sdim    for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI->getNumOperands();
1475224145Sdim         i != e && MI->getOperand(i).isImm(); i += 1 + NumOps) {
1476224145Sdim      unsigned Flags = MI->getOperand(i).getImm();
1477224145Sdim      NumOps = InlineAsm::getNumOperandRegisters(Flags);
1478224145Sdim      if (NumOps != 1)
1479224145Sdim        continue;
1480224145Sdim      const MachineOperand &MO = MI->getOperand(i + 1);
1481224145Sdim      if (!MO.isReg())
1482224145Sdim        continue;
1483224145Sdim      unsigned STReg = MO.getReg() - X86::ST0;
1484224145Sdim      if (STReg >= 8)
1485224145Sdim        continue;
1486224145Sdim
1487224145Sdim      switch (InlineAsm::getKind(Flags)) {
1488224145Sdim      case InlineAsm::Kind_RegUse:
1489224145Sdim        STUses |= (1u << STReg);
1490224145Sdim        break;
1491224145Sdim      case InlineAsm::Kind_RegDef:
1492224145Sdim      case InlineAsm::Kind_RegDefEarlyClobber:
1493224145Sdim        STDefs |= (1u << STReg);
1494224145Sdim        if (MO.isDead())
1495224145Sdim          STDeadDefs |= (1u << STReg);
1496224145Sdim        break;
1497224145Sdim      case InlineAsm::Kind_Clobber:
1498224145Sdim        STClobbers |= (1u << STReg);
1499224145Sdim        break;
1500224145Sdim      default:
1501224145Sdim        break;
1502224145Sdim      }
1503224145Sdim    }
1504224145Sdim
1505224145Sdim    if (STUses && !isMask_32(STUses))
1506224145Sdim      MI->emitError("fixed input regs must be last on the x87 stack");
1507224145Sdim    unsigned NumSTUses = CountTrailingOnes_32(STUses);
1508224145Sdim
1509224145Sdim    // Defs must be contiguous from the stack top. ST0-STn.
1510224145Sdim    if (STDefs && !isMask_32(STDefs)) {
1511224145Sdim      MI->emitError("output regs must be last on the x87 stack");
1512224145Sdim      STDefs = NextPowerOf2(STDefs) - 1;
1513224145Sdim    }
1514224145Sdim    unsigned NumSTDefs = CountTrailingOnes_32(STDefs);
1515224145Sdim
1516224145Sdim    // So must the clobbered stack slots. ST0-STm, m >= n.
1517224145Sdim    if (STClobbers && !isMask_32(STDefs | STClobbers))
1518224145Sdim      MI->emitError("clobbers must be last on the x87 stack");
1519224145Sdim
1520224145Sdim    // Popped inputs are the ones that are also clobbered or defined.
1521224145Sdim    unsigned STPopped = STUses & (STDefs | STClobbers);
1522224145Sdim    if (STPopped && !isMask_32(STPopped))
1523224145Sdim      MI->emitError("implicitly popped regs must be last on the x87 stack");
1524224145Sdim    unsigned NumSTPopped = CountTrailingOnes_32(STPopped);
1525224145Sdim
1526224145Sdim    DEBUG(dbgs() << "Asm uses " << NumSTUses << " fixed regs, pops "
1527224145Sdim                 << NumSTPopped << ", and defines " << NumSTDefs << " regs.\n");
1528224145Sdim
1529224145Sdim    // Scan the instruction for FP uses corresponding to "f" constraints.
1530224145Sdim    // Collect FP registers to kill afer the instruction.
1531224145Sdim    // Always kill all the scratch regs.
1532224145Sdim    unsigned FPKills = ((1u << NumFPRegs) - 1) & ~0xff;
1533224145Sdim    unsigned FPUsed = 0;
1534193323Sed    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1535193323Sed      MachineOperand &Op = MI->getOperand(i);
1536193323Sed      if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)
1537193323Sed        continue;
1538224145Sdim      if (!Op.isUse())
1539224145Sdim        MI->emitError("illegal \"f\" output constraint");
1540193323Sed      unsigned FPReg = getFPReg(Op);
1541224145Sdim      FPUsed |= 1U << FPReg;
1542224145Sdim
1543193323Sed      // If we kill this operand, make sure to pop it from the stack after the
1544193323Sed      // asm.  We just remember it for now, and pop them all off at the end in
1545193323Sed      // a batch.
1546193323Sed      if (Op.isKill())
1547224145Sdim        FPKills |= 1U << FPReg;
1548193323Sed    }
1549193323Sed
1550224145Sdim    // The popped inputs will be killed by the instruction, so duplicate them
1551224145Sdim    // if the FP register needs to be live after the instruction, or if it is
1552224145Sdim    // used in the instruction itself. We effectively treat the popped inputs
1553224145Sdim    // as early clobbers.
1554224145Sdim    for (unsigned i = 0; i < NumSTPopped; ++i) {
1555224145Sdim      if ((FPKills & ~FPUsed) & (1u << PendingST[i]))
1556224145Sdim        continue;
1557224145Sdim      unsigned SR = getScratchReg();
1558224145Sdim      duplicateToTop(PendingST[i], SR, I);
1559224145Sdim      DEBUG(dbgs() << "Duplicating ST" << i << " in FP"
1560224145Sdim                   << unsigned(PendingST[i]) << " to avoid clobbering it.\n");
1561224145Sdim      PendingST[i] = SR;
1562224145Sdim    }
1563224145Sdim
1564224145Sdim    // Make sure we have a unique live register for every fixed use. Some of
1565224145Sdim    // them could be undef uses, and we need to emit LD_F0 instructions.
1566224145Sdim    for (unsigned i = 0; i < NumSTUses; ++i) {
1567224145Sdim      if (i < NumPendingSTs && PendingST[i] < NumFPRegs) {
1568224145Sdim        // Check for shared assignments.
1569224145Sdim        for (unsigned j = 0; j < i; ++j) {
1570224145Sdim          if (PendingST[j] != PendingST[i])
1571224145Sdim            continue;
1572224145Sdim          // STi and STj are inn the same register, create a copy.
1573224145Sdim          unsigned SR = getScratchReg();
1574224145Sdim          duplicateToTop(PendingST[i], SR, I);
1575224145Sdim          DEBUG(dbgs() << "Duplicating ST" << i << " in FP"
1576224145Sdim                       << unsigned(PendingST[i])
1577224145Sdim                       << " to avoid collision with ST" << j << '\n');
1578224145Sdim          PendingST[i] = SR;
1579224145Sdim        }
1580224145Sdim        continue;
1581224145Sdim      }
1582224145Sdim      unsigned SR = getScratchReg();
1583224145Sdim      DEBUG(dbgs() << "Emitting LD_F0 for ST" << i << " in FP" << SR << '\n');
1584224145Sdim      BuildMI(*MBB, I, MI->getDebugLoc(), TII->get(X86::LD_F0));
1585224145Sdim      pushReg(SR);
1586224145Sdim      PendingST[i] = SR;
1587224145Sdim      if (NumPendingSTs == i)
1588224145Sdim        ++NumPendingSTs;
1589224145Sdim    }
1590224145Sdim    assert(NumPendingSTs >= NumSTUses && "Fixed registers should be assigned");
1591224145Sdim
1592224145Sdim    // Now we can rearrange the live registers to match what was requested.
1593224145Sdim    shuffleStackTop(PendingST, NumPendingSTs, I);
1594224145Sdim    DEBUG({dbgs() << "Before asm: "; dumpStack();});
1595224145Sdim
1596224145Sdim    // With the stack layout fixed, rewrite the FP registers.
1597224145Sdim    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1598224145Sdim      MachineOperand &Op = MI->getOperand(i);
1599224145Sdim      if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)
1600224145Sdim        continue;
1601224145Sdim      unsigned FPReg = getFPReg(Op);
1602224145Sdim      Op.setReg(getSTReg(FPReg));
1603224145Sdim    }
1604224145Sdim
1605224145Sdim    // Simulate the inline asm popping its inputs and pushing its outputs.
1606224145Sdim    StackTop -= NumSTPopped;
1607224145Sdim
1608224145Sdim    // Hold the fixed output registers in scratch FP registers. They will be
1609224145Sdim    // transferred to real FP registers by copies.
1610224145Sdim    NumPendingSTs = 0;
1611224145Sdim    for (unsigned i = 0; i < NumSTDefs; ++i) {
1612224145Sdim      unsigned SR = getScratchReg();
1613224145Sdim      pushReg(SR);
1614224145Sdim      FPKills &= ~(1u << SR);
1615224145Sdim    }
1616224145Sdim    for (unsigned i = 0; i < NumSTDefs; ++i)
1617224145Sdim      PendingST[NumPendingSTs++] = getStackEntry(i);
1618224145Sdim    DEBUG({dbgs() << "After asm: "; dumpStack();});
1619224145Sdim
1620224145Sdim    // If any of the ST defs were dead, pop them immediately. Our caller only
1621224145Sdim    // handles dead FP defs.
1622224145Sdim    MachineBasicBlock::iterator InsertPt = MI;
1623224145Sdim    for (unsigned i = 0; STDefs & (1u << i); ++i) {
1624224145Sdim      if (!(STDeadDefs & (1u << i)))
1625224145Sdim        continue;
1626224145Sdim      freeStackSlotAfter(InsertPt, PendingST[i]);
1627224145Sdim      PendingST[i] = NumFPRegs;
1628224145Sdim    }
1629224145Sdim    while (NumPendingSTs && PendingST[NumPendingSTs - 1] == NumFPRegs)
1630224145Sdim      --NumPendingSTs;
1631224145Sdim
1632193323Sed    // If this asm kills any FP registers (is the last use of them) we must
1633193323Sed    // explicitly emit pop instructions for them.  Do this now after the asm has
1634193323Sed    // executed so that the ST(x) numbers are not off (which would happen if we
1635193323Sed    // did this inline with operand rewriting).
1636193323Sed    //
1637193323Sed    // Note: this might be a non-optimal pop sequence.  We might be able to do
1638193323Sed    // better by trying to pop in stack order or something.
1639224145Sdim    while (FPKills) {
1640263508Sdim      unsigned FPReg = countTrailingZeros(FPKills);
1641224145Sdim      if (isLive(FPReg))
1642224145Sdim        freeStackSlotAfter(InsertPt, FPReg);
1643224145Sdim      FPKills &= ~(1U << FPReg);
1644207618Srdivacky    }
1645193323Sed    // Don't delete the inline asm!
1646193323Sed    return;
1647193323Sed  }
1648224145Sdim
1649234353Sdim  case X86::WIN_FTOL_32:
1650234353Sdim  case X86::WIN_FTOL_64: {
1651234353Sdim    // Push the operand into ST0.
1652234353Sdim    MachineOperand &Op = MI->getOperand(0);
1653234353Sdim    assert(Op.isUse() && Op.isReg() &&
1654234353Sdim      Op.getReg() >= X86::FP0 && Op.getReg() <= X86::FP6);
1655234353Sdim    unsigned FPReg = getFPReg(Op);
1656234353Sdim    if (Op.isKill())
1657234353Sdim      moveToTop(FPReg, I);
1658234353Sdim    else
1659234353Sdim      duplicateToTop(FPReg, FPReg, I);
1660234353Sdim
1661234353Sdim    // Emit the call. This will pop the operand.
1662234353Sdim    BuildMI(*MBB, I, MI->getDebugLoc(), TII->get(X86::CALLpcrel32))
1663234353Sdim      .addExternalSymbol("_ftol2")
1664234353Sdim      .addReg(X86::ST0, RegState::ImplicitKill)
1665263508Sdim      .addReg(X86::ECX, RegState::ImplicitDefine)
1666234353Sdim      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
1667234353Sdim      .addReg(X86::EDX, RegState::Define | RegState::Implicit)
1668234353Sdim      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
1669234353Sdim    --StackTop;
1670234353Sdim
1671234353Sdim    break;
1672234353Sdim  }
1673234353Sdim
1674193323Sed  case X86::RET:
1675193323Sed  case X86::RETI:
1676193323Sed    // If RET has an FP register use operand, pass the first one in ST(0) and
1677193323Sed    // the second one in ST(1).
1678212904Sdim
1679193323Sed    // Find the register operands.
1680193323Sed    unsigned FirstFPRegOp = ~0U, SecondFPRegOp = ~0U;
1681212904Sdim    unsigned LiveMask = 0;
1682212904Sdim
1683193323Sed    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1684193323Sed      MachineOperand &Op = MI->getOperand(i);
1685193323Sed      if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)
1686193323Sed        continue;
1687193323Sed      // FP Register uses must be kills unless there are two uses of the same
1688193323Sed      // register, in which case only one will be a kill.
1689193323Sed      assert(Op.isUse() &&
1690193323Sed             (Op.isKill() ||                        // Marked kill.
1691193323Sed              getFPReg(Op) == FirstFPRegOp ||       // Second instance.
1692193323Sed              MI->killsRegister(Op.getReg())) &&    // Later use is marked kill.
1693193323Sed             "Ret only defs operands, and values aren't live beyond it");
1694193323Sed
1695193323Sed      if (FirstFPRegOp == ~0U)
1696193323Sed        FirstFPRegOp = getFPReg(Op);
1697193323Sed      else {
1698193323Sed        assert(SecondFPRegOp == ~0U && "More than two fp operands!");
1699193323Sed        SecondFPRegOp = getFPReg(Op);
1700193323Sed      }
1701212904Sdim      LiveMask |= (1 << getFPReg(Op));
1702193323Sed
1703193323Sed      // Remove the operand so that later passes don't see it.
1704193323Sed      MI->RemoveOperand(i);
1705193323Sed      --i, --e;
1706193323Sed    }
1707212904Sdim
1708212904Sdim    // We may have been carrying spurious live-ins, so make sure only the returned
1709212904Sdim    // registers are left live.
1710212904Sdim    adjustLiveRegs(LiveMask, MI);
1711212904Sdim    if (!LiveMask) return;  // Quick check to see if any are possible.
1712212904Sdim
1713193323Sed    // There are only four possibilities here:
1714193323Sed    // 1) we are returning a single FP value.  In this case, it has to be in
1715193323Sed    //    ST(0) already, so just declare success by removing the value from the
1716193323Sed    //    FP Stack.
1717193323Sed    if (SecondFPRegOp == ~0U) {
1718193323Sed      // Assert that the top of stack contains the right FP register.
1719193323Sed      assert(StackTop == 1 && FirstFPRegOp == getStackEntry(0) &&
1720193323Sed             "Top of stack not the right register for RET!");
1721239462Sdim
1722193323Sed      // Ok, everything is good, mark the value as not being on the stack
1723193323Sed      // anymore so that our assertion about the stack being empty at end of
1724193323Sed      // block doesn't fire.
1725193323Sed      StackTop = 0;
1726193323Sed      return;
1727193323Sed    }
1728239462Sdim
1729193323Sed    // Otherwise, we are returning two values:
1730193323Sed    // 2) If returning the same value for both, we only have one thing in the FP
1731193323Sed    //    stack.  Consider:  RET FP1, FP1
1732193323Sed    if (StackTop == 1) {
1733193323Sed      assert(FirstFPRegOp == SecondFPRegOp && FirstFPRegOp == getStackEntry(0)&&
1734193323Sed             "Stack misconfiguration for RET!");
1735239462Sdim
1736193323Sed      // Duplicate the TOS so that we return it twice.  Just pick some other FPx
1737193323Sed      // register to hold it.
1738212904Sdim      unsigned NewReg = getScratchReg();
1739193323Sed      duplicateToTop(FirstFPRegOp, NewReg, MI);
1740193323Sed      FirstFPRegOp = NewReg;
1741193323Sed    }
1742239462Sdim
1743193323Sed    /// Okay we know we have two different FPx operands now:
1744193323Sed    assert(StackTop == 2 && "Must have two values live!");
1745239462Sdim
1746193323Sed    /// 3) If SecondFPRegOp is currently in ST(0) and FirstFPRegOp is currently
1747193323Sed    ///    in ST(1).  In this case, emit an fxch.
1748193323Sed    if (getStackEntry(0) == SecondFPRegOp) {
1749193323Sed      assert(getStackEntry(1) == FirstFPRegOp && "Unknown regs live");
1750193323Sed      moveToTop(FirstFPRegOp, MI);
1751193323Sed    }
1752239462Sdim
1753193323Sed    /// 4) Finally, FirstFPRegOp must be in ST(0) and SecondFPRegOp must be in
1754193323Sed    /// ST(1).  Just remove both from our understanding of the stack and return.
1755193323Sed    assert(getStackEntry(0) == FirstFPRegOp && "Unknown regs live");
1756193323Sed    assert(getStackEntry(1) == SecondFPRegOp && "Unknown regs live");
1757193323Sed    StackTop = 0;
1758193323Sed    return;
1759193323Sed  }
1760193323Sed
1761193323Sed  I = MBB->erase(I);  // Remove the pseudo instruction
1762212904Sdim
1763212904Sdim  // We want to leave I pointing to the previous instruction, but what if we
1764212904Sdim  // just erased the first instruction?
1765212904Sdim  if (I == MBB->begin()) {
1766212904Sdim    DEBUG(dbgs() << "Inserting dummy KILL\n");
1767212904Sdim    I = BuildMI(*MBB, I, DebugLoc(), TII->get(TargetOpcode::KILL));
1768212904Sdim  } else
1769212904Sdim    --I;
1770193323Sed}
1771