Rip JIT specific stuff out of TargetMachine, as per PR176
[oota-llvm.git] / lib / Target / X86 / X86FloatingPoint.cpp
1 //===-- FloatingPoint.cpp - Floating point Reg -> Stack converter ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the pass which converts floating point instructions from
11 // virtual registers into register stack instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "fp"
16 #include "X86.h"
17 #include "X86InstrInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
26 #include <algorithm>
27 #include <iostream>
28
29 namespace llvm {
30
31 namespace {
32   Statistic<> NumFXCH("x86-codegen", "Number of fxch instructions inserted");
33   Statistic<> NumFP  ("x86-codegen", "Number of floating point instructions");
34
35   struct FPS : public MachineFunctionPass {
36     virtual bool runOnMachineFunction(MachineFunction &MF);
37
38     virtual const char *getPassName() const { return "X86 FP Stackifier"; }
39
40     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.addRequired<LiveVariables>();
42       MachineFunctionPass::getAnalysisUsage(AU);
43     }
44   private:
45     LiveVariables     *LV;    // Live variable info for current function...
46     MachineBasicBlock *MBB;   // Current basic block
47     unsigned Stack[8];        // FP<n> Registers in each stack slot...
48     unsigned RegMap[8];       // Track which stack slot contains each register
49     unsigned StackTop;        // The current top of the FP stack.
50
51     void dumpStack() const {
52       std::cerr << "Stack contents:";
53       for (unsigned i = 0; i != StackTop; ++i) {
54         std::cerr << " FP" << Stack[i];
55         assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!"); 
56       }
57       std::cerr << "\n";
58     }
59   private:
60     // getSlot - Return the stack slot number a particular register number is
61     // in...
62     unsigned getSlot(unsigned RegNo) const {
63       assert(RegNo < 8 && "Regno out of range!");
64       return RegMap[RegNo];
65     }
66
67     // getStackEntry - Return the X86::FP<n> register in register ST(i)
68     unsigned getStackEntry(unsigned STi) const {
69       assert(STi < StackTop && "Access past stack top!");
70       return Stack[StackTop-1-STi];
71     }
72
73     // getSTReg - Return the X86::ST(i) register which contains the specified
74     // FP<RegNo> register
75     unsigned getSTReg(unsigned RegNo) const {
76       return StackTop - 1 - getSlot(RegNo) + llvm::X86::ST0;
77     }
78
79     // pushReg - Push the specifiex FP<n> register onto the stack
80     void pushReg(unsigned Reg) {
81       assert(Reg < 8 && "Register number out of range!");
82       assert(StackTop < 8 && "Stack overflow!");
83       Stack[StackTop] = Reg;
84       RegMap[Reg] = StackTop++;
85     }
86
87     bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
88     void moveToTop(unsigned RegNo, MachineBasicBlock::iterator &I) {
89       if (!isAtTop(RegNo)) {
90         unsigned Slot = getSlot(RegNo);
91         unsigned STReg = getSTReg(RegNo);
92         unsigned RegOnTop = getStackEntry(0);
93
94         // Swap the slots the regs are in
95         std::swap(RegMap[RegNo], RegMap[RegOnTop]);
96
97         // Swap stack slot contents
98         assert(RegMap[RegOnTop] < StackTop);
99         std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
100
101         // Emit an fxch to update the runtime processors version of the state
102         MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
103         I = 1+MBB->insert(I, MI);
104         NumFXCH++;
105       }
106     }
107
108     void duplicateToTop(unsigned RegNo, unsigned AsReg,
109                         MachineBasicBlock::iterator &I) {
110       unsigned STReg = getSTReg(RegNo);
111       pushReg(AsReg);   // New register on top of stack
112
113       MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
114       I = 1+MBB->insert(I, MI);
115     }
116
117     // popStackAfter - Pop the current value off of the top of the FP stack
118     // after the specified instruction.
119     void popStackAfter(MachineBasicBlock::iterator &I);
120
121     bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
122
123     void handleZeroArgFP(MachineBasicBlock::iterator &I);
124     void handleOneArgFP(MachineBasicBlock::iterator &I);
125     void handleTwoArgFP(MachineBasicBlock::iterator &I);
126     void handleSpecialFP(MachineBasicBlock::iterator &I);
127   };
128 }
129
130 FunctionPass *createX86FloatingPointStackifierPass() { return new FPS(); }
131
132 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
133 /// register references into FP stack references.
134 ///
135 bool FPS::runOnMachineFunction(MachineFunction &MF) {
136   LV = &getAnalysis<LiveVariables>();
137   StackTop = 0;
138
139   bool Changed = false;
140   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
141     Changed |= processBasicBlock(MF, *I);
142   return Changed;
143 }
144
145 /// processBasicBlock - Loop over all of the instructions in the basic block,
146 /// transforming FP instructions into their stack form.
147 ///
148 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
149   const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
150   bool Changed = false;
151   MBB = &BB;
152   
153   for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
154     MachineInstr *MI = *I;
155     MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
156     unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
157
158     if ((Flags & X86II::FPTypeMask) == 0) continue;  // Ignore non-fp insts!
159
160     ++NumFP;  // Keep track of # of pseudo instrs
161     DEBUG(std::cerr << "\nFPInst:\t";
162           MI->print(std::cerr, MF.getTarget()));
163
164     // Get dead variables list now because the MI pointer may be deleted as part
165     // of processing!
166     LiveVariables::killed_iterator IB = LV->dead_begin(MI);
167     LiveVariables::killed_iterator IE = LV->dead_end(MI);
168
169     DEBUG(const MRegisterInfo *MRI = MF.getTarget().getRegisterInfo();
170           LiveVariables::killed_iterator I = LV->killed_begin(MI);
171           LiveVariables::killed_iterator E = LV->killed_end(MI);
172           if (I != E) {
173             std::cerr << "Killed Operands:";
174             for (; I != E; ++I)
175               std::cerr << " %" << MRI->getName(I->second);
176             std::cerr << "\n";
177           });
178
179     switch (Flags & X86II::FPTypeMask) {
180     case X86II::ZeroArgFP: handleZeroArgFP(I); break;
181     case X86II::OneArgFP:  handleOneArgFP(I);  break;
182
183     case X86II::OneArgFPRW:   // ST(0) = fsqrt(ST(0))
184       assert(0 && "FP instr type not handled yet!");
185
186     case X86II::TwoArgFP:  handleTwoArgFP(I);  break;
187     case X86II::SpecialFP: handleSpecialFP(I); break;
188     default: assert(0 && "Unknown FP Type!");
189     }
190
191     // Check to see if any of the values defined by this instruction are dead
192     // after definition.  If so, pop them.
193     for (; IB != IE; ++IB) {
194       unsigned Reg = IB->second;
195       if (Reg >= X86::FP0 && Reg <= X86::FP6) {
196         DEBUG(std::cerr << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
197         ++I;                         // Insert fxch AFTER the instruction
198         moveToTop(Reg-X86::FP0, I);  // Insert fxch if necessary
199         --I;                         // Move to fxch or old instruction
200         popStackAfter(I);            // Pop the top of the stack, killing value
201       }
202     }
203     
204     // Print out all of the instructions expanded to if -debug
205     DEBUG(if (*I == PrevMI) {
206             std::cerr<< "Just deleted pseudo instruction\n";
207           } else {
208             MachineBasicBlock::iterator Start = I;
209             // Rewind to first instruction newly inserted.
210             while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
211             std::cerr << "Inserted instructions:\n\t";
212             (*Start)->print(std::cerr, MF.getTarget());
213             while (++Start != I+1);
214           }
215           dumpStack();
216           );
217
218     Changed = true;
219   }
220
221   assert(StackTop == 0 && "Stack not empty at end of basic block?");
222   return Changed;
223 }
224
225 //===----------------------------------------------------------------------===//
226 // Efficient Lookup Table Support
227 //===----------------------------------------------------------------------===//
228
229 struct TableEntry {
230   unsigned from;
231   unsigned to;
232   bool operator<(const TableEntry &TE) const { return from < TE.from; }
233   bool operator<(unsigned V) const { return from < V; }
234 };
235
236 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
237   for (unsigned i = 0; i != NumEntries-1; ++i)
238     if (!(Table[i] < Table[i+1])) return false;
239   return true;
240 }
241
242 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
243   const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
244   if (I != Table+N && I->from == Opcode)
245     return I->to;
246   return -1;
247 }
248
249 #define ARRAY_SIZE(TABLE)  \
250    (sizeof(TABLE)/sizeof(TABLE[0]))
251
252 #ifdef NDEBUG
253 #define ASSERT_SORTED(TABLE)
254 #else
255 #define ASSERT_SORTED(TABLE)                                              \
256   { static bool TABLE##Checked = false;                                   \
257     if (!TABLE##Checked)                                                  \
258        assert(TableIsSorted(TABLE, ARRAY_SIZE(TABLE)) &&                  \
259               "All lookup tables must be sorted for efficient access!");  \
260   }
261 #endif
262
263
264 //===----------------------------------------------------------------------===//
265 // Helper Methods
266 //===----------------------------------------------------------------------===//
267
268 // PopTable - Sorted map of instructions to their popping version.  The first
269 // element is an instruction, the second is the version which pops.
270 //
271 static const TableEntry PopTable[] = {
272   { X86::FADDrST0 , X86::FADDPrST0  },
273
274   { X86::FDIVRrST0, X86::FDIVRPrST0 },
275   { X86::FDIVrST0 , X86::FDIVPrST0  },
276
277   { X86::FISTr16  , X86::FISTPr16   },
278   { X86::FISTr32  , X86::FISTPr32   },
279
280   { X86::FMULrST0 , X86::FMULPrST0  },
281
282   { X86::FSTr32   , X86::FSTPr32    },
283   { X86::FSTr64   , X86::FSTPr64    },
284   { X86::FSTrr    , X86::FSTPrr     },
285
286   { X86::FSUBRrST0, X86::FSUBRPrST0 },
287   { X86::FSUBrST0 , X86::FSUBPrST0  },
288
289   { X86::FUCOMPr  , X86::FUCOMPPr   },
290   { X86::FUCOMr   , X86::FUCOMPr    },
291 };
292
293 /// popStackAfter - Pop the current value off of the top of the FP stack after
294 /// the specified instruction.  This attempts to be sneaky and combine the pop
295 /// into the instruction itself if possible.  The iterator is left pointing to
296 /// the last instruction, be it a new pop instruction inserted, or the old
297 /// instruction if it was modified in place.
298 ///
299 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
300   ASSERT_SORTED(PopTable);
301   assert(StackTop > 0 && "Cannot pop empty stack!");
302   RegMap[Stack[--StackTop]] = ~0;     // Update state
303
304   // Check to see if there is a popping version of this instruction...
305   int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
306   if (Opcode != -1) {
307     (*I)->setOpcode(Opcode);
308     if (Opcode == X86::FUCOMPPr)
309       (*I)->RemoveOperand(0);
310
311   } else {    // Insert an explicit pop
312     MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
313     I = MBB->insert(I+1, MI);
314   }
315 }
316
317 static unsigned getFPReg(const MachineOperand &MO) {
318   assert(MO.isPhysicalRegister() && "Expected an FP register!");
319   unsigned Reg = MO.getReg();
320   assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
321   return Reg - X86::FP0;
322 }
323
324
325 //===----------------------------------------------------------------------===//
326 // Instruction transformation implementation
327 //===----------------------------------------------------------------------===//
328
329 /// handleZeroArgFP - ST(0) = fld0    ST(0) = flds <mem>
330 //
331 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
332   MachineInstr *MI = *I;
333   unsigned DestReg = getFPReg(MI->getOperand(0));
334   MI->RemoveOperand(0);   // Remove the explicit ST(0) operand
335
336   // Result gets pushed on the stack...
337   pushReg(DestReg);
338 }
339
340 /// handleOneArgFP - fst ST(0), <mem>
341 //
342 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
343   MachineInstr *MI = *I;
344   assert(MI->getNumOperands() == 5 && "Can only handle fst* instructions!");
345
346   unsigned Reg = getFPReg(MI->getOperand(4));
347   bool KillsSrc = false;
348   for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
349          E = LV->killed_end(MI); KI != E; ++KI)
350     KillsSrc |= KI->second == X86::FP0+Reg;
351
352   // FSTPr80 and FISTPr64 are strange because there are no non-popping versions.
353   // If we have one _and_ we don't want to pop the operand, duplicate the value
354   // on the stack instead of moving it.  This ensure that popping the value is
355   // always ok.
356   //
357   if ((MI->getOpcode() == X86::FSTPr80 ||
358        MI->getOpcode() == X86::FISTPr64) && !KillsSrc) {
359     duplicateToTop(Reg, 7 /*temp register*/, I);
360   } else {
361     moveToTop(Reg, I);            // Move to the top of the stack...
362   }
363   MI->RemoveOperand(4);           // Remove explicit ST(0) operand
364   
365   if (MI->getOpcode() == X86::FSTPr80 || MI->getOpcode() == X86::FISTPr64) {
366     assert(StackTop > 0 && "Stack empty??");
367     --StackTop;
368   } else if (KillsSrc) { // Last use of operand?
369     popStackAfter(I);
370   }
371 }
372
373 //===----------------------------------------------------------------------===//
374 // Define tables of various ways to map pseudo instructions
375 //
376
377 // ForwardST0Table - Map: A = B op C  into: ST(0) = ST(0) op ST(i)
378 static const TableEntry ForwardST0Table[] = {
379   { X86::FpADD,  X86::FADDST0r  },
380   { X86::FpDIV,  X86::FDIVST0r  },
381   { X86::FpMUL,  X86::FMULST0r  },
382   { X86::FpSUB,  X86::FSUBST0r  },
383   { X86::FpUCOM, X86::FUCOMr    },
384 };
385
386 // ReverseST0Table - Map: A = B op C  into: ST(0) = ST(i) op ST(0)
387 static const TableEntry ReverseST0Table[] = {
388   { X86::FpADD,  X86::FADDST0r  },   // commutative
389   { X86::FpDIV,  X86::FDIVRST0r },
390   { X86::FpMUL,  X86::FMULST0r  },   // commutative
391   { X86::FpSUB,  X86::FSUBRST0r },
392   { X86::FpUCOM, ~0             },
393 };
394
395 // ForwardSTiTable - Map: A = B op C  into: ST(i) = ST(0) op ST(i)
396 static const TableEntry ForwardSTiTable[] = {
397   { X86::FpADD,  X86::FADDrST0  },   // commutative
398   { X86::FpDIV,  X86::FDIVRrST0 },
399   { X86::FpMUL,  X86::FMULrST0  },   // commutative
400   { X86::FpSUB,  X86::FSUBRrST0 },
401   { X86::FpUCOM, X86::FUCOMr    },
402 };
403
404 // ReverseSTiTable - Map: A = B op C  into: ST(i) = ST(i) op ST(0)
405 static const TableEntry ReverseSTiTable[] = {
406   { X86::FpADD,  X86::FADDrST0 },
407   { X86::FpDIV,  X86::FDIVrST0 },
408   { X86::FpMUL,  X86::FMULrST0 },
409   { X86::FpSUB,  X86::FSUBrST0 },
410   { X86::FpUCOM, ~0            },
411 };
412
413
414 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
415 /// instructions which need to be simplified and possibly transformed.
416 ///
417 /// Result: ST(0) = fsub  ST(0), ST(i)
418 ///         ST(i) = fsub  ST(0), ST(i)
419 ///         ST(0) = fsubr ST(0), ST(i)
420 ///         ST(i) = fsubr ST(0), ST(i)
421 ///
422 /// In addition to three address instructions, this also handles the FpUCOM
423 /// instruction which only has two operands, but no destination.  This
424 /// instruction is also annoying because there is no "reverse" form of it
425 /// available.
426 /// 
427 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
428   ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
429   ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
430   MachineInstr *MI = *I;
431
432   unsigned NumOperands = MI->getNumOperands();
433   assert(NumOperands == 3 ||
434          (NumOperands == 2 && MI->getOpcode() == X86::FpUCOM) &&
435          "Illegal TwoArgFP instruction!");
436   unsigned Dest = getFPReg(MI->getOperand(0));
437   unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
438   unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
439   bool KillsOp0 = false, KillsOp1 = false;
440
441   for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
442          E = LV->killed_end(MI); KI != E; ++KI) {
443     KillsOp0 |= (KI->second == X86::FP0+Op0);
444     KillsOp1 |= (KI->second == X86::FP0+Op1);
445   }
446
447   // If this is an FpUCOM instruction, we must make sure the first operand is on
448   // the top of stack, the other one can be anywhere...
449   if (MI->getOpcode() == X86::FpUCOM)
450     moveToTop(Op0, I);
451
452   unsigned TOS = getStackEntry(0);
453
454   // One of our operands must be on the top of the stack.  If neither is yet, we
455   // need to move one.
456   if (Op0 != TOS && Op1 != TOS) {   // No operand at TOS?
457     // We can choose to move either operand to the top of the stack.  If one of
458     // the operands is killed by this instruction, we want that one so that we
459     // can update right on top of the old version.
460     if (KillsOp0) {
461       moveToTop(Op0, I);         // Move dead operand to TOS.
462       TOS = Op0;
463     } else if (KillsOp1) {
464       moveToTop(Op1, I);
465       TOS = Op1;
466     } else {
467       // All of the operands are live after this instruction executes, so we
468       // cannot update on top of any operand.  Because of this, we must
469       // duplicate one of the stack elements to the top.  It doesn't matter
470       // which one we pick.
471       //
472       duplicateToTop(Op0, Dest, I);
473       Op0 = TOS = Dest;
474       KillsOp0 = true;
475     }
476   } else if (!KillsOp0 && !KillsOp1 && MI->getOpcode() != X86::FpUCOM)  {
477     // If we DO have one of our operands at the top of the stack, but we don't
478     // have a dead operand, we must duplicate one of the operands to a new slot
479     // on the stack.
480     duplicateToTop(Op0, Dest, I);
481     Op0 = TOS = Dest;
482     KillsOp0 = true;
483   }
484
485   // Now we know that one of our operands is on the top of the stack, and at
486   // least one of our operands is killed by this instruction.
487   assert((TOS == Op0 || TOS == Op1) &&
488          (KillsOp0 || KillsOp1 || MI->getOpcode() == X86::FpUCOM) &&
489          "Stack conditions not set up right!");
490
491   // We decide which form to use based on what is on the top of the stack, and
492   // which operand is killed by this instruction.
493   const TableEntry *InstTable;
494   bool isForward = TOS == Op0;
495   bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
496   if (updateST0) {
497     if (isForward)
498       InstTable = ForwardST0Table;
499     else
500       InstTable = ReverseST0Table;
501   } else {
502     if (isForward)
503       InstTable = ForwardSTiTable;
504     else
505       InstTable = ReverseSTiTable;
506   }
507   
508   int Opcode = Lookup(InstTable, ARRAY_SIZE(ForwardST0Table), MI->getOpcode());
509   assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
510
511   // NotTOS - The register which is not on the top of stack...
512   unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
513
514   // Replace the old instruction with a new instruction
515   *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
516
517   // If both operands are killed, pop one off of the stack in addition to
518   // overwriting the other one.
519   if (KillsOp0 && KillsOp1 && Op0 != Op1) {
520     assert(!updateST0 && "Should have updated other operand!");
521     popStackAfter(I);   // Pop the top of stack
522   }
523
524   // Insert an explicit pop of the "updated" operand for FUCOM 
525   if (MI->getOpcode() == X86::FpUCOM) {
526     if (KillsOp0 && !KillsOp1)
527       popStackAfter(I);   // If we kill the first operand, pop it!
528     else if (KillsOp1 && Op0 != Op1) {
529       if (getStackEntry(0) == Op1) {
530         popStackAfter(I);     // If it's right at the top of stack, just pop it
531       } else {
532         // Otherwise, move the top of stack into the dead slot, killing the
533         // operand without having to add in an explicit xchg then pop.
534         //
535         unsigned STReg    = getSTReg(Op1);
536         unsigned OldSlot  = getSlot(Op1);
537         unsigned TopReg   = Stack[StackTop-1];
538         Stack[OldSlot]    = TopReg;
539         RegMap[TopReg]    = OldSlot;
540         RegMap[Op1]       = ~0;
541         Stack[--StackTop] = ~0;
542         
543         MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
544         I = MBB->insert(I+1, MI);
545       }
546     }
547   }
548       
549   // Update stack information so that we know the destination register is now on
550   // the stack.
551   if (MI->getOpcode() != X86::FpUCOM) {  
552     unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
553     assert(UpdatedSlot < StackTop && Dest < 7);
554     Stack[UpdatedSlot]   = Dest;
555     RegMap[Dest]         = UpdatedSlot;
556   }
557   delete MI;   // Remove the old instruction
558 }
559
560
561 /// handleSpecialFP - Handle special instructions which behave unlike other
562 /// floating point instructions.  This is primarily intended for use by pseudo
563 /// instructions.
564 ///
565 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
566   MachineInstr *MI = *I;
567   switch (MI->getOpcode()) {
568   default: assert(0 && "Unknown SpecialFP instruction!");
569   case X86::FpGETRESULT:  // Appears immediately after a call returning FP type!
570     assert(StackTop == 0 && "Stack should be empty after a call!");
571     pushReg(getFPReg(MI->getOperand(0)));
572     break;
573   case X86::FpSETRESULT:
574     assert(StackTop == 1 && "Stack should have one element on it to return!");
575     --StackTop;   // "Forget" we have something on the top of stack!
576     break;
577   case X86::FpMOV: {
578     unsigned SrcReg = getFPReg(MI->getOperand(1));
579     unsigned DestReg = getFPReg(MI->getOperand(0));
580     bool KillsSrc = false;
581     for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
582            E = LV->killed_end(MI); KI != E; ++KI)
583       KillsSrc |= KI->second == X86::FP0+SrcReg;
584
585     if (KillsSrc) {
586       // If the input operand is killed, we can just change the owner of the
587       // incoming stack slot into the result.
588       unsigned Slot = getSlot(SrcReg);
589       assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
590       Stack[Slot] = DestReg;
591       RegMap[DestReg] = Slot;
592
593     } else {
594       // For FMOV we just duplicate the specified value to a new stack slot.
595       // This could be made better, but would require substantial changes.
596       duplicateToTop(SrcReg, DestReg, I);
597     }
598     break;
599   }
600   }
601
602   I = MBB->erase(I)-1;  // Remove the pseudo instruction
603 }
604
605 namespace {
606
607   struct FPK : public MachineFunctionPass {
608     virtual const char *getPassName() const { return "X86 FP Killer"; }
609     virtual bool runOnMachineFunction(MachineFunction &MF);
610       virtual void getAnalysisUsage(AnalysisUsage &AU) const {
611           AU.addPreserved<LiveVariables>();
612           AU.addRequired<LiveVariables>();
613           AU.addPreservedID(PHIEliminationID);
614           AU.addRequiredID(PHIEliminationID);
615           MachineFunctionPass::getAnalysisUsage(AU);
616       }
617   };
618 }
619
620 FunctionPass * createX86FloatingPointKillerPass() { return new FPK(); }
621
622 bool FPK::runOnMachineFunction(MachineFunction &MF)
623 {
624   const TargetInstrInfo& tii = MF.getTarget().getInstrInfo();;
625
626   for (MachineFunction::iterator
627            mbbi = MF.begin(), mbbe = MF.end(); mbbi != mbbe; ++mbbi) {
628     MachineBasicBlock& mbb = *mbbi;
629     MachineBasicBlock::reverse_iterator mii = mbb.rbegin();
630     // rewind to the last non terminating instruction
631     while (mii != mbb.rend() && tii.isTerminatorInstr((*mii)->getOpcode())) {
632       ++mii;
633     }
634     // add implicit def for all virtual floating point registers so that
635     // they are spilled at the end of each basic block, since our
636     // register stackifier doesn't handle them otherwise.
637     MachineInstr* instr = BuildMI(X86::IMPLICIT_DEF, 7)
638         .addReg(X86::FP6, MOTy::Def)
639         .addReg(X86::FP5, MOTy::Def)
640         .addReg(X86::FP4, MOTy::Def)
641         .addReg(X86::FP3, MOTy::Def)
642         .addReg(X86::FP2, MOTy::Def)
643         .addReg(X86::FP1, MOTy::Def)
644         .addReg(X86::FP0, MOTy::Def);
645         
646     mbb.insert(mii.base(), instr);
647     LiveVariables& lv = getAnalysis<LiveVariables>();
648     for (unsigned i = 0; i < instr->getNumOperands(); ++i) {
649         lv.HandlePhysRegDef(instr->getOperand(i).getAllocatedRegNum(), instr);
650         // force live variables to compute that these registers are dead
651         lv.HandlePhysRegDef(instr->getOperand(i).getAllocatedRegNum(), 0);
652     }
653   }
654   return true;
655 }
656
657 } // End llvm namespace