bearch: Introduce be_foreach_out().
[libfirm] / ir / be / ia32 / ia32_x87.c
1 /*
2  * Copyright (C) 1995-2010 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       This file implements the x87 support and virtual to stack
23  *              register translation for the ia32 backend.
24  * @author      Michael Beck
25  */
26 #include "config.h"
27
28 #include <assert.h>
29
30 #include "irnode_t.h"
31 #include "irop_t.h"
32 #include "irprog.h"
33 #include "iredges_t.h"
34 #include "irgmod.h"
35 #include "ircons.h"
36 #include "irgwalk.h"
37 #include "obst.h"
38 #include "pmap.h"
39 #include "array_t.h"
40 #include "pdeq.h"
41 #include "irprintf.h"
42 #include "debug.h"
43 #include "error.h"
44
45 #include "belive_t.h"
46 #include "besched.h"
47 #include "benode.h"
48 #include "bearch_ia32_t.h"
49 #include "ia32_new_nodes.h"
50 #include "gen_ia32_new_nodes.h"
51 #include "gen_ia32_regalloc_if.h"
52 #include "ia32_x87.h"
53 #include "ia32_architecture.h"
54
55 #define N_FLOAT_REGS  (N_ia32_fp_REGS-1)  // exclude NOREG
56
57 /** the debug handle */
58 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
59
60 /* Forward declaration. */
61 typedef struct x87_simulator x87_simulator;
62
63 /**
64  * An entry on the simulated x87 stack.
65  */
66 typedef struct st_entry {
67         int      reg_idx; /**< the virtual register index of this stack value */
68         ir_node *node;    /**< the node that produced this value */
69 } st_entry;
70
71 /**
72  * The x87 state.
73  */
74 typedef struct x87_state {
75         st_entry       st[N_FLOAT_REGS]; /**< the register stack */
76         int            depth;            /**< the current stack depth */
77         x87_simulator *sim;              /**< The simulator. */
78 } x87_state;
79
80 /** An empty state, used for blocks without fp instructions. */
81 static x87_state empty = { { {0, NULL}, }, 0, NULL };
82
83 /**
84  * Return values of the instruction simulator functions.
85  */
86 enum {
87         NO_NODE_ADDED = 0,  /**< No node that needs simulation was added. */
88         NODE_ADDED    = 1   /**< A node that must be simulated was added by the simulator
89                                  in the schedule AFTER the current node. */
90 };
91
92 /**
93  * The type of an instruction simulator function.
94  *
95  * @param state  the x87 state
96  * @param n      the node to be simulated
97  *
98  * @return NODE_ADDED    if a node was added AFTER n in schedule that MUST be
99  *                       simulated further
100  *         NO_NODE_ADDED otherwise
101  */
102 typedef int (*sim_func)(x87_state *state, ir_node *n);
103
104 /**
105  * A block state: Every block has a x87 state at the beginning and at the end.
106  */
107 typedef struct blk_state {
108         x87_state *begin;   /**< state at the begin or NULL if not assigned */
109         x87_state *end;     /**< state at the end or NULL if not assigned */
110 } blk_state;
111
112 /** liveness bitset for fp registers. */
113 typedef unsigned char fp_liveness;
114
115 /**
116  * The x87 simulator.
117  */
118 struct x87_simulator {
119         struct obstack obst;       /**< An obstack for fast allocating. */
120         pmap          *blk_states; /**< Map blocks to states. */
121         be_lv_t       *lv;         /**< intrablock liveness. */
122         fp_liveness   *live;       /**< Liveness information. */
123         unsigned       n_idx;      /**< The cached get_irg_last_idx() result. */
124         waitq         *worklist;   /**< Worklist of blocks that must be processed. */
125 };
126
127 /**
128  * Returns the current stack depth.
129  *
130  * @param state  the x87 state
131  *
132  * @return the x87 stack depth
133  */
134 static int x87_get_depth(const x87_state *state)
135 {
136         return state->depth;
137 }
138
139 static st_entry *x87_get_entry(x87_state *const state, int const pos)
140 {
141         assert(0 <= pos && pos < state->depth);
142         return &state->st[N_FLOAT_REGS - state->depth + pos];
143 }
144
145 /**
146  * Return the virtual register index at st(pos).
147  *
148  * @param state  the x87 state
149  * @param pos    a stack position
150  *
151  * @return the fp register index that produced the value at st(pos)
152  */
153 static int x87_get_st_reg(const x87_state *state, int pos)
154 {
155         return x87_get_entry((x87_state*)state, pos)->reg_idx;
156 }
157
158 #ifdef DEBUG_libfirm
159 /**
160  * Dump the stack for debugging.
161  *
162  * @param state  the x87 state
163  */
164 static void x87_dump_stack(const x87_state *state)
165 {
166         for (int i = state->depth; i-- != 0;) {
167                 st_entry const *const entry = x87_get_entry((x87_state*)state, i);
168                 DB((dbg, LEVEL_2, "vf%d(%+F) ", entry->reg_idx, entry->node));
169         }
170         DB((dbg, LEVEL_2, "<-- TOS\n"));
171 }
172 #endif /* DEBUG_libfirm */
173
174 /**
175  * Set a virtual register to st(pos).
176  *
177  * @param state    the x87 state
178  * @param reg_idx  the fp register index that should be set
179  * @param node     the IR node that produces the value of the fp register
180  * @param pos      the stack position where the new value should be entered
181  */
182 static void x87_set_st(x87_state *state, int reg_idx, ir_node *node, int pos)
183 {
184         st_entry *const entry = x87_get_entry(state, pos);
185         entry->reg_idx = reg_idx;
186         entry->node    = node;
187
188         DB((dbg, LEVEL_2, "After SET_REG: "));
189         DEBUG_ONLY(x87_dump_stack(state);)
190 }
191
192 /**
193  * Swap st(0) with st(pos).
194  *
195  * @param state    the x87 state
196  * @param pos      the stack position to change the tos with
197  */
198 static void x87_fxch(x87_state *state, int pos)
199 {
200         st_entry *const a = x87_get_entry(state, pos);
201         st_entry *const b = x87_get_entry(state, 0);
202         st_entry  const t = *a;
203         *a = *b;
204         *b = t;
205
206         DB((dbg, LEVEL_2, "After FXCH: "));
207         DEBUG_ONLY(x87_dump_stack(state);)
208 }
209
210 /**
211  * Convert a virtual register to the stack index.
212  *
213  * @param state    the x87 state
214  * @param reg_idx  the register fp index
215  *
216  * @return the stack position where the register is stacked
217  *         or -1 if the virtual register was not found
218  */
219 static int x87_on_stack(const x87_state *state, int reg_idx)
220 {
221         for (int i = 0; i < state->depth; ++i) {
222                 if (x87_get_st_reg(state, i) == reg_idx)
223                         return i;
224         }
225         return -1;
226 }
227
228 /**
229  * Push a virtual Register onto the stack, double pushes are NOT allowed.
230  *
231  * @param state     the x87 state
232  * @param reg_idx   the register fp index
233  * @param node      the node that produces the value of the fp register
234  */
235 static void x87_push(x87_state *state, int reg_idx, ir_node *node)
236 {
237         assert(x87_on_stack(state, reg_idx) == -1 && "double push");
238         assert(state->depth < N_FLOAT_REGS && "stack overrun");
239
240         ++state->depth;
241         st_entry *const entry = x87_get_entry(state, 0);
242         entry->reg_idx = reg_idx;
243         entry->node    = node;
244
245         DB((dbg, LEVEL_2, "After PUSH: ")); DEBUG_ONLY(x87_dump_stack(state);)
246 }
247
248 /**
249  * Pop a virtual Register from the stack.
250  *
251  * @param state     the x87 state
252  */
253 static void x87_pop(x87_state *state)
254 {
255         assert(state->depth > 0 && "stack underrun");
256
257         --state->depth;
258
259         DB((dbg, LEVEL_2, "After POP: ")); DEBUG_ONLY(x87_dump_stack(state);)
260 }
261
262 /**
263  * Empty the fpu stack
264  *
265  * @param state     the x87 state
266  */
267 static void x87_emms(x87_state *state)
268 {
269         state->depth = 0;
270 }
271
272 /**
273  * Returns the block state of a block.
274  *
275  * @param sim    the x87 simulator handle
276  * @param block  the current block
277  *
278  * @return the block state
279  */
280 static blk_state *x87_get_bl_state(x87_simulator *sim, ir_node *block)
281 {
282         blk_state *res = pmap_get(blk_state, sim->blk_states, block);
283
284         if (res == NULL) {
285                 res = OALLOC(&sim->obst, blk_state);
286                 res->begin = NULL;
287                 res->end   = NULL;
288
289                 pmap_insert(sim->blk_states, block, res);
290         }
291
292         return res;
293 }
294
295 /**
296  * Clone a x87 state.
297  *
298  * @param sim    the x87 simulator handle
299  * @param src    the x87 state that will be cloned
300  *
301  * @return a cloned copy of the src state
302  */
303 static x87_state *x87_clone_state(x87_simulator *sim, const x87_state *src)
304 {
305         x87_state *const res = OALLOC(&sim->obst, x87_state);
306         *res = *src;
307         return res;
308 }
309
310 /**
311  * Returns the first Proj of a mode_T node having a given mode.
312  *
313  * @param n  the mode_T node
314  * @param m  the desired mode of the Proj
315  * @return The first Proj of mode @p m found.
316  */
317 static ir_node *get_irn_Proj_for_mode(ir_node *n, ir_mode *m)
318 {
319         assert(get_irn_mode(n) == mode_T && "Need mode_T node");
320
321         foreach_out_edge(n, edge) {
322                 ir_node *proj = get_edge_src_irn(edge);
323                 if (get_irn_mode(proj) == m)
324                         return proj;
325         }
326
327         panic("Proj not found");
328 }
329
330 /**
331  * Wrap the arch_* function here so we can check for errors.
332  */
333 static inline const arch_register_t *x87_get_irn_register(const ir_node *irn)
334 {
335         const arch_register_t *res = arch_get_irn_register(irn);
336
337         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_fp]);
338         return res;
339 }
340
341 static inline const arch_register_t *x87_irn_get_register(const ir_node *irn,
342                                                           int pos)
343 {
344         const arch_register_t *res = arch_get_irn_register_out(irn, pos);
345
346         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_fp]);
347         return res;
348 }
349
350 static inline const arch_register_t *get_st_reg(int index)
351 {
352         return &ia32_registers[REG_ST0 + index];
353 }
354
355 /**
356  * Create a fxch node before another node.
357  *
358  * @param state   the x87 state
359  * @param n       the node after the fxch
360  * @param pos     exchange st(pos) with st(0)
361  */
362 static void x87_create_fxch(x87_state *state, ir_node *n, int pos)
363 {
364         x87_fxch(state, pos);
365
366         ir_node         *const block = get_nodes_block(n);
367         ir_node         *const fxch  = new_bd_ia32_fxch(NULL, block);
368         ia32_x87_attr_t *const attr  = get_ia32_x87_attr(fxch);
369         attr->reg = get_st_reg(pos);
370
371         keep_alive(fxch);
372
373         sched_add_before(n, fxch);
374         DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fxch), attr->reg->name));
375 }
376
377 /* -------------- x87 perm --------------- */
378
379 /**
380  * Calculate the necessary permutations to reach dst_state.
381  *
382  * These permutations are done with fxch instructions and placed
383  * at the end of the block.
384  *
385  * Note that critical edges are removed here, so we need only
386  * a shuffle if the current block has only one successor.
387  *
388  * @param block      the current block
389  * @param state      the current x87 stack state, might be modified
390  * @param dst_state  destination state
391  *
392  * @return state
393  */
394 static x87_state *x87_shuffle(ir_node *block, x87_state *state, const x87_state *dst_state)
395 {
396         int      i, n_cycles, k, ri;
397         unsigned cycles[4], all_mask;
398         char     cycle_idx[4][8];
399
400         assert(state->depth == dst_state->depth);
401
402         /* Some mathematics here:
403          * If we have a cycle of length n that includes the tos,
404          * we need n-1 exchange operations.
405          * We can always add the tos and restore it, so we need
406          * n+1 exchange operations for a cycle not containing the tos.
407          * So, the maximum of needed operations is for a cycle of 7
408          * not including the tos == 8.
409          * This is the same number of ops we would need for using stores,
410          * so exchange is cheaper (we save the loads).
411          * On the other hand, we might need an additional exchange
412          * in the next block to bring one operand on top, so the
413          * number of ops in the first case is identical.
414          * Further, no more than 4 cycles can exists (4 x 2). */
415         all_mask = (1 << (state->depth)) - 1;
416
417         for (n_cycles = 0; all_mask; ++n_cycles) {
418                 int src_idx, dst_idx;
419
420                 /* find the first free slot */
421                 for (i = 0; i < state->depth; ++i) {
422                         if (all_mask & (1 << i)) {
423                                 all_mask &= ~(1 << i);
424
425                                 /* check if there are differences here */
426                                 if (x87_get_st_reg(state, i) != x87_get_st_reg(dst_state, i))
427                                         break;
428                         }
429                 }
430
431                 if (! all_mask) {
432                         /* no more cycles found */
433                         break;
434                 }
435
436                 k = 0;
437                 cycles[n_cycles] = (1 << i);
438                 cycle_idx[n_cycles][k++] = i;
439                 for (src_idx = i; ; src_idx = dst_idx) {
440                         dst_idx = x87_on_stack(dst_state, x87_get_st_reg(state, src_idx));
441
442                         if ((all_mask & (1 << dst_idx)) == 0)
443                                 break;
444
445                         cycle_idx[n_cycles][k++] = dst_idx;
446                         cycles[n_cycles] |=  (1 << dst_idx);
447                         all_mask       &= ~(1 << dst_idx);
448                 }
449                 cycle_idx[n_cycles][k] = -1;
450         }
451
452         if (n_cycles <= 0) {
453                 /* no permutation needed */
454                 return state;
455         }
456
457         /* Hmm: permutation needed */
458         DB((dbg, LEVEL_2, "\n%+F needs permutation: from\n", block));
459         DEBUG_ONLY(x87_dump_stack(state);)
460         DB((dbg, LEVEL_2, "                  to\n"));
461         DEBUG_ONLY(x87_dump_stack(dst_state);)
462
463
464 #ifdef DEBUG_libfirm
465         DB((dbg, LEVEL_2, "Need %d cycles\n", n_cycles));
466         for (ri = 0; ri < n_cycles; ++ri) {
467                 DB((dbg, LEVEL_2, " Ring %d:\n ", ri));
468                 for (k = 0; cycle_idx[ri][k] != -1; ++k)
469                         DB((dbg, LEVEL_2, " st%d ->", cycle_idx[ri][k]));
470                 DB((dbg, LEVEL_2, "\n"));
471         }
472 #endif
473
474         /*
475          * Find the place node must be insert.
476          * We have only one successor block, so the last instruction should
477          * be a jump.
478          */
479         ir_node *const before = sched_last(block);
480         assert(is_cfop(before));
481
482         /* now do the permutations */
483         for (ri = 0; ri < n_cycles; ++ri) {
484                 if ((cycles[ri] & 1) == 0) {
485                         /* this cycle does not include the tos */
486                         x87_create_fxch(state, before, cycle_idx[ri][0]);
487                 }
488                 for (k = 1; cycle_idx[ri][k] != -1; ++k) {
489                         x87_create_fxch(state, before, cycle_idx[ri][k]);
490                 }
491                 if ((cycles[ri] & 1) == 0) {
492                         /* this cycle does not include the tos */
493                         x87_create_fxch(state, before, cycle_idx[ri][0]);
494                 }
495         }
496         return state;
497 }
498
499 /**
500  * Create a fpush before node n.
501  *
502  * @param state     the x87 state
503  * @param n         the node after the fpush
504  * @param pos       push st(pos) on stack
505  * @param val       the value to push
506  */
507 static void x87_create_fpush(x87_state *state, ir_node *n, int pos, int const out_reg_idx, ir_node *const val)
508 {
509         x87_push(state, out_reg_idx, val);
510
511         ir_node         *const fpush = new_bd_ia32_fpush(NULL, get_nodes_block(n));
512         ia32_x87_attr_t *const attr  = get_ia32_x87_attr(fpush);
513         attr->reg = get_st_reg(pos);
514
515         keep_alive(fpush);
516         sched_add_before(n, fpush);
517
518         DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fpush), attr->reg->name));
519 }
520
521 /**
522  * Create a fpop before node n.
523  * This overwrites st(pos) with st(0) and pops st(0).
524  *
525  * @param state   the x87 state
526  * @param n       the node after the fpop
527  * @param pos     the index of the entry to remove the register stack
528  *
529  * @return the fpop node
530  */
531 static ir_node *x87_create_fpop(x87_state *const state, ir_node *const n, int const pos)
532 {
533         if (pos != 0) {
534                 st_entry *const dst = x87_get_entry(state, pos);
535                 st_entry *const src = x87_get_entry(state, 0);
536                 *dst = *src;
537         }
538         x87_pop(state);
539         ir_node *const block = get_nodes_block(n);
540         ir_node *const fpop  = pos == 0 && ia32_cg_config.use_ffreep ?
541                 new_bd_ia32_ffreep(NULL, block) :
542                 new_bd_ia32_fpop(  NULL, block);
543         ia32_x87_attr_t *const attr = get_ia32_x87_attr(fpop);
544         attr->reg = get_st_reg(pos);
545
546         keep_alive(fpop);
547         sched_add_before(n, fpop);
548         DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fpop), attr->reg->name));
549         return fpop;
550 }
551
552 /* --------------------------------- liveness ------------------------------------------ */
553
554 /**
555  * The liveness transfer function.
556  * Updates a live set over a single step from a given node to its predecessor.
557  * Everything defined at the node is removed from the set, the uses of the node get inserted.
558  *
559  * @param irn      The node at which liveness should be computed.
560  * @param live     The bitset of registers live before @p irn. This set gets modified by updating it to
561  *                 the registers live after irn.
562  *
563  * @return The live bitset.
564  */
565 static fp_liveness fp_liveness_transfer(ir_node *irn, fp_liveness live)
566 {
567         int i, n;
568         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_fp];
569
570         if (get_irn_mode(irn) == mode_T) {
571                 foreach_out_edge(irn, edge) {
572                         ir_node *proj = get_edge_src_irn(edge);
573
574                         if (arch_irn_consider_in_reg_alloc(cls, proj)) {
575                                 const arch_register_t *reg = x87_get_irn_register(proj);
576                                 live &= ~(1 << reg->index);
577                         }
578                 }
579         } else if (arch_irn_consider_in_reg_alloc(cls, irn)) {
580                 const arch_register_t *reg = x87_get_irn_register(irn);
581                 live &= ~(1 << reg->index);
582         }
583
584         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
585                 ir_node *op = get_irn_n(irn, i);
586
587                 if (mode_is_float(get_irn_mode(op)) &&
588                                 arch_irn_consider_in_reg_alloc(cls, op)) {
589                         const arch_register_t *reg = x87_get_irn_register(op);
590                         live |= 1 << reg->index;
591                 }
592         }
593         return live;
594 }
595
596 /**
597  * Put all live virtual registers at the end of a block into a bitset.
598  *
599  * @param sim      the simulator handle
600  * @param bl       the block
601  *
602  * @return The live bitset at the end of this block
603  */
604 static fp_liveness fp_liveness_end_of_block(x87_simulator *sim, const ir_node *block)
605 {
606         fp_liveness live = 0;
607         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_fp];
608         const be_lv_t *lv = sim->lv;
609
610         be_lv_foreach(lv, block, be_lv_state_end, node) {
611                 const arch_register_t *reg;
612                 if (!arch_irn_consider_in_reg_alloc(cls, node))
613                         continue;
614
615                 reg = x87_get_irn_register(node);
616                 live |= 1 << reg->index;
617         }
618
619         return live;
620 }
621
622 /** get the register mask from an arch_register */
623 #define REGMASK(reg)    (1 << (reg->index))
624
625 /**
626  * Return a bitset of argument registers which are live at the end of a node.
627  *
628  * @param sim    the simulator handle
629  * @param pos    the node
630  * @param kill   kill mask for the output registers
631  *
632  * @return The live bitset.
633  */
634 static unsigned fp_live_args_after(x87_simulator *sim, const ir_node *pos, unsigned kill)
635 {
636         unsigned idx = get_irn_idx(pos);
637
638         assert(idx < sim->n_idx);
639         return sim->live[idx] & ~kill;
640 }
641
642 /**
643  * Calculate the liveness for a whole block and cache it.
644  *
645  * @param sim   the simulator handle
646  * @param block the block
647  */
648 static void update_liveness(x87_simulator *sim, ir_node *block)
649 {
650         fp_liveness live = fp_liveness_end_of_block(sim, block);
651         unsigned idx;
652
653         /* now iterate through the block backward and cache the results */
654         sched_foreach_reverse(block, irn) {
655                 /* stop at the first Phi: this produces the live-in */
656                 if (is_Phi(irn))
657                         break;
658
659                 idx = get_irn_idx(irn);
660                 sim->live[idx] = live;
661
662                 live = fp_liveness_transfer(irn, live);
663         }
664         idx = get_irn_idx(block);
665         sim->live[idx] = live;
666 }
667
668 /**
669  * Returns true if a register is live in a set.
670  *
671  * @param reg_idx  the fp register index
672  * @param live     a live bitset
673  */
674 #define is_fp_live(reg_idx, live) ((live) & (1 << (reg_idx)))
675
676 #ifdef DEBUG_libfirm
677 /**
678  * Dump liveness info.
679  *
680  * @param live  the live bitset
681  */
682 static void fp_dump_live(fp_liveness live)
683 {
684         int i;
685
686         DB((dbg, LEVEL_2, "Live after: "));
687         for (i = 0; i < 8; ++i) {
688                 if (live & (1 << i)) {
689                         DB((dbg, LEVEL_2, "vf%d ", i));
690                 }
691         }
692         DB((dbg, LEVEL_2, "\n"));
693 }
694 #endif /* DEBUG_libfirm */
695
696 /* --------------------------------- simulators ---------------------------------------- */
697
698 /**
699  * Simulate a virtual binop.
700  *
701  * @param state  the x87 state
702  * @param n      the node that should be simulated (and patched)
703  *
704  * @return NO_NODE_ADDED
705  */
706 static int sim_binop(x87_state *const state, ir_node *const n)
707 {
708         x87_simulator         *sim     = state->sim;
709         ir_node               *op1     = get_irn_n(n, n_ia32_binary_left);
710         ir_node               *op2     = get_irn_n(n, n_ia32_binary_right);
711         const arch_register_t *op1_reg = x87_get_irn_register(op1);
712         const arch_register_t *op2_reg = x87_get_irn_register(op2);
713         const arch_register_t *out     = x87_irn_get_register(n, pn_ia32_res);
714         int reg_index_1                = op1_reg->index;
715         int reg_index_2                = op2_reg->index;
716         fp_liveness            live    = fp_live_args_after(sim, n, REGMASK(out));
717         int                    op1_live_after;
718         int                    op2_live_after;
719
720         DB((dbg, LEVEL_1, ">>> %+F %s, %s -> %s\n", n, op1_reg->name, op2_reg->name, out->name));
721         DEBUG_ONLY(fp_dump_live(live);)
722         DB((dbg, LEVEL_1, "Stack before: "));
723         DEBUG_ONLY(x87_dump_stack(state);)
724
725         int op1_idx = x87_on_stack(state, reg_index_1);
726         assert(op1_idx >= 0);
727         op1_live_after = is_fp_live(reg_index_1, live);
728
729         int                    op2_idx;
730         int                    out_idx;
731         bool                   pop         = false;
732         int              const out_reg_idx = out->index;
733         ia32_x87_attr_t *const attr        = get_ia32_x87_attr(n);
734         if (reg_index_2 != REG_FP_FP_NOREG) {
735                 /* second operand is a fp register */
736                 op2_idx = x87_on_stack(state, reg_index_2);
737                 assert(op2_idx >= 0);
738                 op2_live_after = is_fp_live(reg_index_2, live);
739
740                 if (op2_live_after) {
741                         /* Second operand is live. */
742
743                         if (op1_live_after) {
744                                 /* Both operands are live: push the first one.
745                                  * This works even for op1 == op2. */
746                                 x87_create_fpush(state, n, op1_idx, out_reg_idx, op1);
747                                 /* now do fxxx (tos=tos X op) */
748                                 op1_idx = 0;
749                                 op2_idx += 1;
750                                 out_idx = 0;
751                         } else {
752                                 /* Second live, first operand is dead: Overwrite first. */
753                                 if (op1_idx != 0 && op2_idx != 0) {
754                                         /* Bring one operand to tos. */
755                                         x87_create_fxch(state, n, op1_idx);
756                                         op1_idx = 0;
757                                 }
758                                 out_idx = op1_idx;
759                         }
760                 } else {
761                         /* Second operand is dead. */
762                         if (op1_live_after) {
763                                 /* First operand is live, second is dead: Overwrite second. */
764                                 if (op1_idx != 0 && op2_idx != 0) {
765                                         /* Bring one operand to tos. */
766                                         x87_create_fxch(state, n, op2_idx);
767                                         op2_idx = 0;
768                                 }
769                                 out_idx = op2_idx;
770                         } else {
771                                 /* Both operands are dead. */
772                                 if (op1_idx == op2_idx) {
773                                         /* Operands are identical: no pop. */
774                                         if (op1_idx != 0) {
775                                                 x87_create_fxch(state, n, op1_idx);
776                                                 op1_idx = 0;
777                                                 op2_idx = 0;
778                                         }
779                                 } else {
780                                         if (op1_idx != 0 && op2_idx != 0) {
781                                                 /* Bring one operand to tos. Heuristically swap the operand not at
782                                                  * st(1) to tos. This way, if any operand was at st(1), the result
783                                                  * will end up in the new st(0) after the implicit pop. If the next
784                                                  * operation uses the result, then no fxch will be necessary. */
785                                                 if (op1_idx != 1) {
786                                                         x87_create_fxch(state, n, op1_idx);
787                                                         op1_idx = 0;
788                                                 } else {
789                                                         x87_create_fxch(state, n, op2_idx);
790                                                         op2_idx = 0;
791                                                 }
792                                         }
793                                         pop = true;
794                                 }
795                                 out_idx = op1_idx != 0 ? op1_idx : op2_idx;
796                         }
797                 }
798         } else {
799                 /* second operand is an address mode */
800                 if (op1_live_after) {
801                         /* first operand is live: push it here */
802                         x87_create_fpush(state, n, op1_idx, out_reg_idx, op1);
803                 } else {
804                         /* first operand is dead: bring it to tos */
805                         if (op1_idx != 0)
806                                 x87_create_fxch(state, n, op1_idx);
807                 }
808
809                 op1_idx = attr->attr.data.ins_permuted ? -1 :  0;
810                 op2_idx = attr->attr.data.ins_permuted ?  0 : -1;
811                 out_idx = 0;
812         }
813         assert(op1_idx == 0       || op2_idx == 0);
814         assert(out_idx == op1_idx || out_idx == op2_idx);
815
816         x87_set_st(state, out_reg_idx, n, out_idx);
817         if (pop)
818                 x87_pop(state);
819
820         /* patch the operation */
821         int const reg_idx = op1_idx != 0 ? op1_idx : op2_idx;
822         attr->reg                    = reg_idx >= 0 ? get_st_reg(reg_idx) : NULL;
823         attr->attr.data.ins_permuted = op1_idx != 0;
824         attr->res_in_reg             = out_idx != 0;
825         attr->pop                    = pop;
826
827         DEBUG_ONLY(
828                 char const *const l = op1_idx >= 0 ? get_st_reg(op1_idx)->name : "[AM]";
829                 char const *const r = op2_idx >= 0 ? get_st_reg(op2_idx)->name : "[AM]";
830                 char const *const o = get_st_reg(out_idx)->name;
831                 DB((dbg, LEVEL_1, "<<< %s %s, %s -> %s\n", get_irn_opname(n), l, r, o));
832         );
833
834         return NO_NODE_ADDED;
835 }
836
837 /**
838  * Simulate a virtual Unop.
839  *
840  * @param state  the x87 state
841  * @param n      the node that should be simulated (and patched)
842  *
843  * @return NO_NODE_ADDED
844  */
845 static int sim_unop(x87_state *state, ir_node *n)
846 {
847         arch_register_t const *const out  = x87_get_irn_register(n);
848         unsigned               const live = fp_live_args_after(state->sim, n, REGMASK(out));
849         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, out->name));
850         DEBUG_ONLY(fp_dump_live(live);)
851
852         ir_node               *const op1         = get_irn_n(n, 0);
853         arch_register_t const *const op1_reg     = x87_get_irn_register(op1);
854         int                    const op1_reg_idx = op1_reg->index;
855         int                    const op1_idx     = x87_on_stack(state, op1_reg_idx);
856         int                    const out_reg_idx = out->index;
857         if (is_fp_live(op1_reg_idx, live)) {
858                 /* push the operand here */
859                 x87_create_fpush(state, n, op1_idx, out_reg_idx, op1);
860         } else {
861                 /* operand is dead, bring it to tos */
862                 if (op1_idx != 0) {
863                         x87_create_fxch(state, n, op1_idx);
864                 }
865         }
866
867         x87_set_st(state, out_reg_idx, n, 0);
868         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), get_st_reg(0)->name));
869
870         return NO_NODE_ADDED;
871 }
872
873 /**
874  * Simulate a virtual Load instruction.
875  *
876  * @param state  the x87 state
877  * @param n      the node that should be simulated (and patched)
878  *
879  * @return NO_NODE_ADDED
880  */
881 static int sim_load(x87_state *state, ir_node *n)
882 {
883         assert((int)pn_ia32_fld_res == (int)pn_ia32_fild_res
884             && (int)pn_ia32_fld_res == (int)pn_ia32_fld1_res
885             && (int)pn_ia32_fld_res == (int)pn_ia32_fldz_res);
886         const arch_register_t *out = x87_irn_get_register(n, pn_ia32_fld_res);
887
888         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, out->name));
889         x87_push(state, out->index, n);
890         assert(out == x87_irn_get_register(n, pn_ia32_fld_res));
891         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), get_st_reg(0)->name));
892
893         return NO_NODE_ADDED;
894 }
895
896 /**
897  * Rewire all users of @p old_val to @new_val iff they are scheduled after @p store.
898  *
899  * @param store   The store
900  * @param old_val The former value
901  * @param new_val The new value
902  */
903 static void collect_and_rewire_users(ir_node *store, ir_node *old_val, ir_node *new_val)
904 {
905         foreach_out_edge_safe(old_val, edge) {
906                 ir_node *user = get_edge_src_irn(edge);
907                 /* if the user is scheduled after the store: rewire */
908                 if (sched_is_scheduled(user) && sched_comes_after(store, user)) {
909                         set_irn_n(user, get_edge_src_pos(edge), new_val);
910                 }
911         }
912 }
913
914 /**
915  * Simulate a virtual Store.
916  *
917  * @param state  the x87 state
918  * @param n      the node that should be simulated (and patched)
919  */
920 static int sim_store(x87_state *state, ir_node *n)
921 {
922         ir_node               *const val = get_irn_n(n, n_ia32_fst_val);
923         arch_register_t const *const op2 = x87_get_irn_register(val);
924         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, op2->name));
925
926         bool           do_pop          = false;
927         int            insn            = NO_NODE_ADDED;
928         int      const op2_reg_idx     = op2->index;
929         int      const op2_idx         = x87_on_stack(state, op2_reg_idx);
930         unsigned const live            = fp_live_args_after(state->sim, n, 0);
931         int      const live_after_node = is_fp_live(op2_reg_idx, live);
932         assert(op2_idx >= 0);
933         if (live_after_node) {
934                 /* Problem: fst doesn't support 80bit modes (spills), only fstp does
935                  *          fist doesn't support 64bit mode, only fistp
936                  * Solution:
937                  *   - stack not full: push value and fstp
938                  *   - stack full: fstp value and load again
939                  * Note that we cannot test on mode_E, because floats might be 80bit ... */
940                 ir_mode *const mode = get_ia32_ls_mode(n);
941                 if (get_mode_size_bits(mode) > (mode_is_int(mode) ? 32 : 64)) {
942                         if (x87_get_depth(state) < N_FLOAT_REGS) {
943                                 /* ok, we have a free register: push + fstp */
944                                 x87_create_fpush(state, n, op2_idx, REG_FP_FP_NOREG, val);
945                                 do_pop = true;
946                         } else {
947                                 /* stack full here: need fstp + load */
948                                 do_pop = true;
949
950                                 ir_node *const block = get_nodes_block(n);
951                                 ir_node *const mem   = get_irn_Proj_for_mode(n, mode_M);
952                                 ir_node *const vfld  = new_bd_ia32_fld(NULL, block, get_irn_n(n, 0), get_irn_n(n, 1), mem, mode);
953
954                                 /* copy all attributes */
955                                 set_ia32_frame_ent(vfld, get_ia32_frame_ent(n));
956                                 if (is_ia32_use_frame(n))
957                                         set_ia32_use_frame(vfld);
958                                 set_ia32_op_type(vfld, ia32_AddrModeS);
959                                 add_ia32_am_offs_int(vfld, get_ia32_am_offs_int(n));
960                                 set_ia32_am_sc(vfld, get_ia32_am_sc(n));
961                                 set_ia32_ls_mode(vfld, mode);
962
963                                 ir_node *const rproj = new_r_Proj(vfld, mode, pn_ia32_fld_res);
964                                 ir_node *const mproj = new_r_Proj(vfld, mode_M, pn_ia32_fld_M);
965
966                                 arch_set_irn_register(rproj, op2);
967
968                                 /* reroute all former users of the store memory to the load memory */
969                                 edges_reroute_except(mem, mproj, vfld);
970
971                                 sched_add_after(n, vfld);
972
973                                 /* rewire all users, scheduled after the store, to the loaded value */
974                                 collect_and_rewire_users(n, val, rproj);
975
976                                 insn = NODE_ADDED;
977                         }
978                 } else {
979                         /* we can only store the tos to memory */
980                         if (op2_idx != 0)
981                                 x87_create_fxch(state, n, op2_idx);
982                 }
983         } else {
984                 /* we can only store the tos to memory */
985                 if (op2_idx != 0)
986                         x87_create_fxch(state, n, op2_idx);
987
988                 do_pop = true;
989         }
990
991         if (do_pop)
992                 x87_pop(state);
993
994         ia32_x87_attr_t *const attr = get_ia32_x87_attr(n);
995         attr->pop = do_pop;
996         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), get_st_reg(0)->name));
997
998         return insn;
999 }
1000
1001 static int sim_fprem(x87_state *const state, ir_node *const n)
1002 {
1003         (void)state;
1004         (void)n;
1005         panic("TODO implement");
1006         return NO_NODE_ADDED;
1007 }
1008
1009 /**
1010  * Simulate a virtual fisttp.
1011  *
1012  * @param state  the x87 state
1013  * @param n      the node that should be simulated (and patched)
1014  *
1015  * @return NO_NODE_ADDED
1016  */
1017 static int sim_fisttp(x87_state *state, ir_node *n)
1018 {
1019         ir_node               *val = get_irn_n(n, n_ia32_fst_val);
1020         const arch_register_t *op2 = x87_get_irn_register(val);
1021
1022         int const op2_idx = x87_on_stack(state, op2->index);
1023         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, op2->name));
1024         assert(op2_idx >= 0);
1025
1026         /* Note: although the value is still live here, it is destroyed because
1027            of the pop. The register allocator is aware of that and introduced a copy
1028            if the value must be alive. */
1029
1030         /* we can only store the tos to memory */
1031         if (op2_idx != 0)
1032                 x87_create_fxch(state, n, op2_idx);
1033
1034         x87_pop(state);
1035
1036         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), get_st_reg(0)->name));
1037
1038         return NO_NODE_ADDED;
1039 }
1040
1041 /**
1042  * Simulate a virtual FtstFnstsw.
1043  *
1044  * @param state  the x87 state
1045  * @param n      the node that should be simulated (and patched)
1046  *
1047  * @return NO_NODE_ADDED
1048  */
1049 static int sim_FtstFnstsw(x87_state *state, ir_node *n)
1050 {
1051         x87_simulator         *sim         = state->sim;
1052         ir_node               *op1_node    = get_irn_n(n, n_ia32_FtstFnstsw_left);
1053         const arch_register_t *reg1        = x87_get_irn_register(op1_node);
1054         int                    reg_index_1 = reg1->index;
1055         int                    op1_idx     = x87_on_stack(state, reg_index_1);
1056         unsigned               live        = fp_live_args_after(sim, n, 0);
1057
1058         DB((dbg, LEVEL_1, ">>> %+F %s\n", n, reg1->name));
1059         DEBUG_ONLY(fp_dump_live(live);)
1060         DB((dbg, LEVEL_1, "Stack before: "));
1061         DEBUG_ONLY(x87_dump_stack(state);)
1062         assert(op1_idx >= 0);
1063
1064         if (op1_idx != 0) {
1065                 /* bring the value to tos */
1066                 x87_create_fxch(state, n, op1_idx);
1067         }
1068
1069         if (!is_fp_live(reg_index_1, live))
1070                 x87_create_fpop(state, sched_next(n), 0);
1071
1072         return NO_NODE_ADDED;
1073 }
1074
1075 /**
1076  * Simulate a Fucom
1077  *
1078  * @param state  the x87 state
1079  * @param n      the node that should be simulated (and patched)
1080  *
1081  * @return NO_NODE_ADDED
1082  */
1083 static int sim_Fucom(x87_state *state, ir_node *n)
1084 {
1085         ia32_x87_attr_t       *attr        = get_ia32_x87_attr(n);
1086         x87_simulator         *sim         = state->sim;
1087         ir_node               *op1_node    = get_irn_n(n, n_ia32_FucomFnstsw_left);
1088         ir_node               *op2_node    = get_irn_n(n, n_ia32_FucomFnstsw_right);
1089         const arch_register_t *op1         = x87_get_irn_register(op1_node);
1090         const arch_register_t *op2         = x87_get_irn_register(op2_node);
1091         int                    reg_index_1 = op1->index;
1092         int                    reg_index_2 = op2->index;
1093         unsigned               live        = fp_live_args_after(sim, n, 0);
1094
1095         DB((dbg, LEVEL_1, ">>> %+F %s, %s\n", n, op1->name, op2->name));
1096         DEBUG_ONLY(fp_dump_live(live);)
1097         DB((dbg, LEVEL_1, "Stack before: "));
1098         DEBUG_ONLY(x87_dump_stack(state);)
1099
1100         int op1_idx = x87_on_stack(state, reg_index_1);
1101         assert(op1_idx >= 0);
1102
1103         int op2_idx;
1104         int pops = 0;
1105         /* BEWARE: check for comp a,a cases, they might happen */
1106         if (reg_index_2 != REG_FP_FP_NOREG) {
1107                 /* second operand is a fp register */
1108                 op2_idx = x87_on_stack(state, reg_index_2);
1109                 assert(op2_idx >= 0);
1110
1111                 if (is_fp_live(reg_index_2, live)) {
1112                         /* second operand is live */
1113
1114                         if (is_fp_live(reg_index_1, live)) {
1115                                 /* both operands are live */
1116                                 if (op1_idx != 0 && op2_idx != 0) {
1117                                         /* bring the first one to tos */
1118                                         x87_create_fxch(state, n, op1_idx);
1119                                         if (op1_idx == op2_idx)
1120                                                 op2_idx = 0;
1121                                         op1_idx = 0;
1122                                         /* res = tos X op */
1123                                 }
1124                         } else {
1125                                 /* second live, first operand is dead here, bring it to tos.
1126                                    This means further, op1_idx != op2_idx. */
1127                                 assert(op1_idx != op2_idx);
1128                                 if (op1_idx != 0) {
1129                                         x87_create_fxch(state, n, op1_idx);
1130                                         if (op2_idx == 0)
1131                                                 op2_idx = op1_idx;
1132                                         op1_idx = 0;
1133                                 }
1134                                 /* res = tos X op, pop */
1135                                 pops = 1;
1136                         }
1137                 } else {
1138                         /* second operand is dead */
1139                         if (is_fp_live(reg_index_1, live)) {
1140                                 /* first operand is live: bring second to tos.
1141                                    This means further, op1_idx != op2_idx. */
1142                                 assert(op1_idx != op2_idx);
1143                                 if (op2_idx != 0) {
1144                                         x87_create_fxch(state, n, op2_idx);
1145                                         if (op1_idx == 0)
1146                                                 op1_idx = op2_idx;
1147                                         op2_idx = 0;
1148                                 }
1149                                 /* res = op X tos, pop */
1150                                 pops = 1;
1151                         } else {
1152                                 /* both operands are dead here, check first for identity. */
1153                                 if (op1_idx == op2_idx) {
1154                                         /* identically, one pop needed */
1155                                         if (op1_idx != 0) {
1156                                                 x87_create_fxch(state, n, op1_idx);
1157                                                 op1_idx = 0;
1158                                                 op2_idx = 0;
1159                                         }
1160                                         /* res = tos X op, pop */
1161                                         pops    = 1;
1162                                 } else {
1163                                         if (op1_idx != 0 && op2_idx != 0) {
1164                                                 /* Both not at tos: Move one operand to tos. Move the one not at
1165                                                  * pos 1, so we get a chance to use fucompp. */
1166                                                 if (op1_idx != 1) {
1167                                                         x87_create_fxch(state, n, op1_idx);
1168                                                         op1_idx = 0;
1169                                                 } else {
1170                                                         x87_create_fxch(state, n, op2_idx);
1171                                                         op2_idx = 0;
1172                                                 }
1173                                         }
1174                                         pops = 2;
1175                                 }
1176                         }
1177                 }
1178         } else {
1179                 /* second operand is an address mode */
1180                 if (op1_idx != 0)
1181                         x87_create_fxch(state, n, op1_idx);
1182                 /* Pop first operand, if it is dead. */
1183                 if (!is_fp_live(reg_index_1, live))
1184                         pops = 1;
1185
1186                 op1_idx = attr->attr.data.ins_permuted ? -1 :  0;
1187                 op2_idx = attr->attr.data.ins_permuted ?  0 : -1;
1188         }
1189         assert(op1_idx == 0 || op2_idx == 0);
1190
1191         /* patch the operation */
1192         if (is_ia32_FucomFnstsw(n) && pops == 2
1193             && (op1_idx == 1 || op2_idx == 1)) {
1194                 set_irn_op(n, op_ia32_FucomppFnstsw);
1195                 x87_pop(state);
1196                 x87_pop(state);
1197         } else {
1198                 if (pops != 0)
1199                         x87_pop(state);
1200                 if (pops == 2) {
1201                         int const idx = (op1_idx != 0 ? op1_idx : op2_idx) - 1 /* Due to prior pop. */;
1202                         x87_create_fpop(state, sched_next(n), idx);
1203                 }
1204         }
1205
1206         int const reg_idx = op1_idx != 0 ? op1_idx : op2_idx;
1207         attr->reg                    = reg_idx >= 0 ? get_st_reg(reg_idx) : NULL;
1208         attr->attr.data.ins_permuted = op1_idx != 0;
1209         attr->pop                    = pops != 0;
1210
1211         DEBUG_ONLY(
1212                 char const *const l = op1_idx >= 0 ? get_st_reg(op1_idx)->name : "[AM]";
1213                 char const *const r = op2_idx >= 0 ? get_st_reg(op2_idx)->name : "[AM]";
1214                 DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(n), l, r));
1215         );
1216
1217         return NO_NODE_ADDED;
1218 }
1219
1220 /**
1221  * Simulate a Keep.
1222  *
1223  * @param state  the x87 state
1224  * @param n      the node that should be simulated (and patched)
1225  *
1226  * @return NO_NODE_ADDED
1227  */
1228 static int sim_Keep(x87_state *state, ir_node *node)
1229 {
1230         const ir_node         *op;
1231         const arch_register_t *op_reg;
1232         int                    reg_id;
1233         int                    op_stack_idx;
1234         unsigned               live;
1235         int                    i, arity;
1236
1237         DB((dbg, LEVEL_1, ">>> %+F\n", node));
1238
1239         arity = get_irn_arity(node);
1240         for (i = 0; i < arity; ++i) {
1241                 op      = get_irn_n(node, i);
1242                 op_reg  = arch_get_irn_register(op);
1243                 if (op_reg->reg_class != &ia32_reg_classes[CLASS_ia32_fp])
1244                         continue;
1245
1246                 reg_id = op_reg->index;
1247                 live   = fp_live_args_after(state->sim, node, 0);
1248
1249                 op_stack_idx = x87_on_stack(state, reg_id);
1250                 if (op_stack_idx >= 0 && !is_fp_live(reg_id, live))
1251                         x87_create_fpop(state, sched_next(node), 0);
1252         }
1253
1254         DB((dbg, LEVEL_1, "Stack after: "));
1255         DEBUG_ONLY(x87_dump_stack(state);)
1256
1257         return NO_NODE_ADDED;
1258 }
1259
1260 /**
1261  * Keep the given node alive by adding a be_Keep.
1262  *
1263  * @param node  the node to kept alive
1264  */
1265 static void keep_float_node_alive(ir_node *node)
1266 {
1267         ir_node *block = get_nodes_block(node);
1268         ir_node *keep  = be_new_Keep(block, 1, &node);
1269         sched_add_after(node, keep);
1270 }
1271
1272 /**
1273  * Create a copy of a node. Recreate the node if it's a constant.
1274  *
1275  * @param state  the x87 state
1276  * @param n      the node to be copied
1277  *
1278  * @return the copy of n
1279  */
1280 static ir_node *create_Copy(x87_state *state, ir_node *n)
1281 {
1282         dbg_info *n_dbg = get_irn_dbg_info(n);
1283         ir_mode *mode = get_irn_mode(n);
1284         ir_node *block = get_nodes_block(n);
1285         ir_node *pred = get_irn_n(n, 0);
1286         ir_node *(*cnstr)(dbg_info *, ir_node *) = NULL;
1287         ir_node *res;
1288         const arch_register_t *out;
1289         const arch_register_t *op1;
1290
1291         /* Do not copy constants, recreate them. */
1292         switch (get_ia32_irn_opcode(pred)) {
1293         case iro_ia32_fldz:
1294                 cnstr = new_bd_ia32_fldz;
1295                 break;
1296         case iro_ia32_fld1:
1297                 cnstr = new_bd_ia32_fld1;
1298                 break;
1299         case iro_ia32_fldpi:
1300                 cnstr = new_bd_ia32_fldpi;
1301                 break;
1302         case iro_ia32_fldl2e:
1303                 cnstr = new_bd_ia32_fldl2e;
1304                 break;
1305         case iro_ia32_fldl2t:
1306                 cnstr = new_bd_ia32_fldl2t;
1307                 break;
1308         case iro_ia32_fldlg2:
1309                 cnstr = new_bd_ia32_fldlg2;
1310                 break;
1311         case iro_ia32_fldln2:
1312                 cnstr = new_bd_ia32_fldln2;
1313                 break;
1314         default:
1315                 break;
1316         }
1317
1318         out = x87_get_irn_register(n);
1319         op1 = x87_get_irn_register(pred);
1320
1321         if (cnstr != NULL) {
1322                 /* copy a constant */
1323                 res = (*cnstr)(n_dbg, block);
1324
1325                 x87_push(state, out->index, res);
1326         } else {
1327                 int op1_idx = x87_on_stack(state, op1->index);
1328
1329                 res = new_bd_ia32_fpushCopy(n_dbg, block, pred, mode);
1330
1331                 x87_push(state, out->index, res);
1332
1333                 ia32_x87_attr_t *const attr = get_ia32_x87_attr(res);
1334                 attr->reg = get_st_reg(op1_idx);
1335         }
1336         arch_set_irn_register(res, out);
1337
1338         return res;
1339 }
1340
1341 /**
1342  * Simulate a be_Copy.
1343  *
1344  * @param state  the x87 state
1345  * @param n      the node that should be simulated (and patched)
1346  *
1347  * @return NO_NODE_ADDED
1348  */
1349 static int sim_Copy(x87_state *state, ir_node *n)
1350 {
1351         arch_register_class_t const *const cls = arch_get_irn_reg_class(n);
1352         if (cls != &ia32_reg_classes[CLASS_ia32_fp])
1353                 return NO_NODE_ADDED;
1354
1355         ir_node               *const pred = be_get_Copy_op(n);
1356         arch_register_t const *const op1  = x87_get_irn_register(pred);
1357         arch_register_t const *const out  = x87_get_irn_register(n);
1358         unsigned               const live = fp_live_args_after(state->sim, n, REGMASK(out));
1359
1360         DB((dbg, LEVEL_1, ">>> %+F %s -> %s\n", n, op1->name, out->name));
1361         DEBUG_ONLY(fp_dump_live(live);)
1362
1363         if (is_fp_live(op1->index, live)) {
1364                 /* Operand is still live, a real copy. We need here an fpush that can
1365                    hold a a register, so use the fpushCopy or recreate constants */
1366                 ir_node *const node = create_Copy(state, n);
1367
1368                 /* We have to make sure the old value doesn't go dead (which can happen
1369                  * when we recreate constants). As the simulator expected that value in
1370                  * the pred blocks. This is unfortunate as removing it would save us 1
1371                  * instruction, but we would have to rerun all the simulation to get
1372                  * this correct...
1373                  */
1374                 ir_node *const next = sched_next(n);
1375                 sched_remove(n);
1376                 exchange(n, node);
1377                 sched_add_before(next, node);
1378
1379                 if (get_irn_n_edges(pred) == 0) {
1380                         keep_float_node_alive(pred);
1381                 }
1382
1383                 DB((dbg, LEVEL_1, "<<< %+F %s -> ?\n", node, op1->name));
1384         } else {
1385                 /* Just a virtual copy. */
1386                 int const op1_idx = x87_on_stack(state, op1->index);
1387                 x87_set_st(state, out->index, n, op1_idx);
1388         }
1389         return NO_NODE_ADDED;
1390 }
1391
1392 /**
1393  * Returns the vf0 result Proj of a Call.
1394  *
1395  * @para call  the Call node
1396  */
1397 static ir_node *get_call_result_proj(ir_node *call)
1398 {
1399         /* search the result proj */
1400         foreach_out_edge(call, edge) {
1401                 ir_node *proj = get_edge_src_irn(edge);
1402                 long pn = get_Proj_proj(proj);
1403
1404                 if (pn == pn_ia32_Call_st0)
1405                         return proj;
1406         }
1407
1408         panic("result Proj missing");
1409 }
1410
1411 static int sim_Asm(x87_state *const state, ir_node *const n)
1412 {
1413         (void)state;
1414
1415         for (size_t i = get_irn_arity(n); i-- != 0;) {
1416                 arch_register_req_t const *const req = arch_get_irn_register_req_in(n, i);
1417                 if (req->cls == &ia32_reg_classes[CLASS_ia32_fp])
1418                         panic("cannot handle %+F with x87 constraints", n);
1419         }
1420
1421         be_foreach_out(n, i) {
1422                 arch_register_req_t const *const req = arch_get_irn_register_req_out(n, i);
1423                 if (req->cls == &ia32_reg_classes[CLASS_ia32_fp])
1424                         panic("cannot handle %+F with x87 constraints", n);
1425         }
1426
1427         return NO_NODE_ADDED;
1428 }
1429
1430 /**
1431  * Simulate a ia32_Call.
1432  *
1433  * @param state      the x87 state
1434  * @param n          the node that should be simulated (and patched)
1435  *
1436  * @return NO_NODE_ADDED
1437  */
1438 static int sim_Call(x87_state *state, ir_node *n)
1439 {
1440         DB((dbg, LEVEL_1, ">>> %+F\n", n));
1441
1442         /* at the begin of a call the x87 state should be empty */
1443         assert(state->depth == 0 && "stack not empty before call");
1444
1445         ir_type *const call_tp = get_ia32_call_attr_const(n)->call_tp;
1446         if (get_method_n_ress(call_tp) != 0) {
1447                 /* If the called function returns a float, it is returned in st(0).
1448                  * This even happens if the return value is NOT used.
1449                  * Moreover, only one return result is supported. */
1450                 ir_type *const res_type = get_method_res_type(call_tp, 0);
1451                 ir_mode *const mode     = get_type_mode(res_type);
1452                 if (mode && mode_is_float(mode)) {
1453                         ir_node               *const resproj = get_call_result_proj(n);
1454                         arch_register_t const *const reg     = x87_get_irn_register(resproj);
1455                         x87_push(state, reg->index, resproj);
1456                 }
1457         }
1458         DB((dbg, LEVEL_1, "Stack after: "));
1459         DEBUG_ONLY(x87_dump_stack(state);)
1460
1461         return NO_NODE_ADDED;
1462 }
1463
1464 /**
1465  * Simulate a be_Return.
1466  *
1467  * @param state  the x87 state
1468  * @param n      the node that should be simulated (and patched)
1469  *
1470  * @return NO_NODE_ADDED
1471  */
1472 static int sim_Return(x87_state *state, ir_node *n)
1473 {
1474 #ifdef DEBUG_libfirm
1475         /* only floating point return values must reside on stack */
1476         int       n_float_res = 0;
1477         int const n_res       = be_Return_get_n_rets(n);
1478         for (int i = 0; i < n_res; ++i) {
1479                 ir_node *const res = get_irn_n(n, n_be_Return_val + i);
1480                 if (mode_is_float(get_irn_mode(res)))
1481                         ++n_float_res;
1482         }
1483         assert(x87_get_depth(state) == n_float_res);
1484 #endif
1485
1486         /* pop them virtually */
1487         x87_emms(state);
1488         return NO_NODE_ADDED;
1489 }
1490
1491 /**
1492  * Simulate a be_Perm.
1493  *
1494  * @param state  the x87 state
1495  * @param irn    the node that should be simulated (and patched)
1496  *
1497  * @return NO_NODE_ADDED
1498  */
1499 static int sim_Perm(x87_state *state, ir_node *irn)
1500 {
1501         int      i, n;
1502         ir_node *pred = get_irn_n(irn, 0);
1503         int     *stack_pos;
1504
1505         /* handle only floating point Perms */
1506         if (! mode_is_float(get_irn_mode(pred)))
1507                 return NO_NODE_ADDED;
1508
1509         DB((dbg, LEVEL_1, ">>> %+F\n", irn));
1510
1511         /* Perm is a pure virtual instruction on x87.
1512            All inputs must be on the FPU stack and are pairwise
1513            different from each other.
1514            So, all we need to do is to permutate the stack state. */
1515         n = get_irn_arity(irn);
1516         NEW_ARR_A(int, stack_pos, n);
1517
1518         /* collect old stack positions */
1519         for (i = 0; i < n; ++i) {
1520                 const arch_register_t *inreg = x87_get_irn_register(get_irn_n(irn, i));
1521                 int idx = x87_on_stack(state, inreg->index);
1522
1523                 assert(idx >= 0 && "Perm argument not on x87 stack");
1524
1525                 stack_pos[i] = idx;
1526         }
1527         /* now do the permutation */
1528         foreach_out_edge(irn, edge) {
1529                 ir_node               *proj = get_edge_src_irn(edge);
1530                 const arch_register_t *out  = x87_get_irn_register(proj);
1531                 long                  num   = get_Proj_proj(proj);
1532
1533                 assert(0 <= num && num < n && "More Proj's than Perm inputs");
1534                 x87_set_st(state, out->index, proj, stack_pos[(unsigned)num]);
1535         }
1536         DB((dbg, LEVEL_1, "<<< %+F\n", irn));
1537
1538         return NO_NODE_ADDED;
1539 }
1540
1541 /**
1542  * Kill any dead registers at block start by popping them from the stack.
1543  *
1544  * @param sim    the simulator handle
1545  * @param block  the current block
1546  * @param state  the x87 state at the begin of the block
1547  */
1548 static void x87_kill_deads(x87_simulator *const sim, ir_node *const block, x87_state *const state)
1549 {
1550         ir_node *first_insn = sched_first(block);
1551         ir_node *keep = NULL;
1552         unsigned live = fp_live_args_after(sim, block, 0);
1553         unsigned kill_mask;
1554         int i, depth;
1555
1556         kill_mask = 0;
1557         depth = x87_get_depth(state);
1558         for (i = depth - 1; i >= 0; --i) {
1559                 int reg = x87_get_st_reg(state, i);
1560
1561                 if (! is_fp_live(reg, live))
1562                         kill_mask |= (1 << i);
1563         }
1564
1565         if (kill_mask) {
1566                 DB((dbg, LEVEL_1, "Killing deads:\n"));
1567                 DEBUG_ONLY(fp_dump_live(live);)
1568                 DEBUG_ONLY(x87_dump_stack(state);)
1569
1570                 if (kill_mask != 0 && live == 0) {
1571                         /* special case: kill all registers */
1572                         if (ia32_cg_config.use_femms || ia32_cg_config.use_emms) {
1573                                 if (ia32_cg_config.use_femms) {
1574                                         /* use FEMMS on AMD processors to clear all */
1575                                         keep = new_bd_ia32_femms(NULL, block);
1576                                 } else {
1577                                         /* use EMMS to clear all */
1578                                         keep = new_bd_ia32_emms(NULL, block);
1579                                 }
1580                                 sched_add_before(first_insn, keep);
1581                                 keep_alive(keep);
1582                                 x87_emms(state);
1583                                 return;
1584                         }
1585                 }
1586                 /* now kill registers */
1587                 while (kill_mask) {
1588                         /* we can only kill from TOS, so bring them up */
1589                         if (! (kill_mask & 1)) {
1590                                 /* search from behind, because we can to a double-pop */
1591                                 for (i = depth - 1; i >= 0; --i) {
1592                                         if (kill_mask & (1 << i)) {
1593                                                 kill_mask &= ~(1 << i);
1594                                                 kill_mask |= 1;
1595                                                 break;
1596                                         }
1597                                 }
1598
1599                                 if (keep)
1600                                         x87_set_st(state, -1, keep, i);
1601                                 x87_create_fxch(state, first_insn, i);
1602                         }
1603
1604                         depth      -= 1;
1605                         kill_mask >>= 1;
1606                         keep        = x87_create_fpop(state, first_insn, 0);
1607                 }
1608                 keep_alive(keep);
1609         }
1610 }
1611
1612 /**
1613  * Run a simulation and fix all virtual instructions for a block.
1614  *
1615  * @param sim          the simulator handle
1616  * @param block        the current block
1617  */
1618 static void x87_simulate_block(x87_simulator *sim, ir_node *block)
1619 {
1620         ir_node *n, *next;
1621         blk_state *bl_state = x87_get_bl_state(sim, block);
1622         x87_state *state = bl_state->begin;
1623         ir_node *start_block;
1624
1625         assert(state != NULL);
1626         /* already processed? */
1627         if (bl_state->end != NULL)
1628                 return;
1629
1630         DB((dbg, LEVEL_1, "Simulate %+F\n", block));
1631         DB((dbg, LEVEL_2, "State at Block begin:\n "));
1632         DEBUG_ONLY(x87_dump_stack(state);)
1633
1634         /* create a new state, will be changed */
1635         state = x87_clone_state(sim, state);
1636         /* at block begin, kill all dead registers */
1637         x87_kill_deads(sim, block, state);
1638
1639         /* beware, n might change */
1640         for (n = sched_first(block); !sched_is_end(n); n = next) {
1641                 int node_inserted;
1642                 sim_func func;
1643                 ir_op *op = get_irn_op(n);
1644
1645                 /*
1646                  * get the next node to be simulated here.
1647                  * n might be completely removed from the schedule-
1648                  */
1649                 next = sched_next(n);
1650                 if (op->ops.generic != NULL) {
1651                         func = (sim_func)op->ops.generic;
1652
1653                         /* simulate it */
1654                         node_inserted = (*func)(state, n);
1655
1656                         /*
1657                          * sim_func might have added an additional node after n,
1658                          * so update next node
1659                          * beware: n must not be changed by sim_func
1660                          * (i.e. removed from schedule) in this case
1661                          */
1662                         if (node_inserted != NO_NODE_ADDED)
1663                                 next = sched_next(n);
1664                 }
1665         }
1666
1667         start_block = get_irg_start_block(get_irn_irg(block));
1668
1669         DB((dbg, LEVEL_2, "State at Block end:\n ")); DEBUG_ONLY(x87_dump_stack(state);)
1670
1671         /* check if the state must be shuffled */
1672         foreach_block_succ(block, edge) {
1673                 ir_node *succ = get_edge_src_irn(edge);
1674                 blk_state *succ_state;
1675
1676                 if (succ == start_block)
1677                         continue;
1678
1679                 succ_state = x87_get_bl_state(sim, succ);
1680
1681                 if (succ_state->begin == NULL) {
1682                         DB((dbg, LEVEL_2, "Set begin state for succ %+F:\n", succ));
1683                         DEBUG_ONLY(x87_dump_stack(state);)
1684                         succ_state->begin = state;
1685
1686                         waitq_put(sim->worklist, succ);
1687                 } else {
1688                         DB((dbg, LEVEL_2, "succ %+F already has a state, shuffling\n", succ));
1689                         /* There is already a begin state for the successor, bad.
1690                            Do the necessary permutations.
1691                            Note that critical edges are removed, so this is always possible:
1692                            If the successor has more than one possible input, then it must
1693                            be the only one.
1694                          */
1695                         x87_shuffle(block, state, succ_state->begin);
1696                 }
1697         }
1698         bl_state->end = state;
1699 }
1700
1701 /**
1702  * Register a simulator function.
1703  *
1704  * @param op    the opcode to simulate
1705  * @param func  the simulator function for the opcode
1706  */
1707 static void register_sim(ir_op *op, sim_func func)
1708 {
1709         assert(op->ops.generic == NULL);
1710         op->ops.generic = (op_func) func;
1711 }
1712
1713 /**
1714  * Create a new x87 simulator.
1715  *
1716  * @param sim       a simulator handle, will be initialized
1717  * @param irg       the current graph
1718  */
1719 static void x87_init_simulator(x87_simulator *sim, ir_graph *irg)
1720 {
1721         obstack_init(&sim->obst);
1722         sim->blk_states = pmap_create();
1723         sim->n_idx      = get_irg_last_idx(irg);
1724         sim->live       = OALLOCN(&sim->obst, fp_liveness, sim->n_idx);
1725
1726         DB((dbg, LEVEL_1, "--------------------------------\n"
1727                 "x87 Simulator started for %+F\n", irg));
1728
1729         /* set the generic function pointer of instruction we must simulate */
1730         ir_clear_opcodes_generic_func();
1731
1732         register_sim(op_ia32_Asm,          sim_Asm);
1733         register_sim(op_ia32_Call,         sim_Call);
1734         register_sim(op_ia32_fld,          sim_load);
1735         register_sim(op_ia32_fild,         sim_load);
1736         register_sim(op_ia32_fld1,         sim_load);
1737         register_sim(op_ia32_fldz,         sim_load);
1738         register_sim(op_ia32_fadd,         sim_binop);
1739         register_sim(op_ia32_fsub,         sim_binop);
1740         register_sim(op_ia32_fmul,         sim_binop);
1741         register_sim(op_ia32_fdiv,         sim_binop);
1742         register_sim(op_ia32_fprem,        sim_fprem);
1743         register_sim(op_ia32_fabs,         sim_unop);
1744         register_sim(op_ia32_fchs,         sim_unop);
1745         register_sim(op_ia32_fist,         sim_store);
1746         register_sim(op_ia32_fisttp,       sim_fisttp);
1747         register_sim(op_ia32_fst,          sim_store);
1748         register_sim(op_ia32_FtstFnstsw,   sim_FtstFnstsw);
1749         register_sim(op_ia32_FucomFnstsw,  sim_Fucom);
1750         register_sim(op_ia32_Fucomi,       sim_Fucom);
1751         register_sim(op_be_Copy,           sim_Copy);
1752         register_sim(op_be_Return,         sim_Return);
1753         register_sim(op_be_Perm,           sim_Perm);
1754         register_sim(op_be_Keep,           sim_Keep);
1755 }
1756
1757 /**
1758  * Destroy a x87 simulator.
1759  *
1760  * @param sim  the simulator handle
1761  */
1762 static void x87_destroy_simulator(x87_simulator *sim)
1763 {
1764         pmap_destroy(sim->blk_states);
1765         obstack_free(&sim->obst, NULL);
1766         DB((dbg, LEVEL_1, "x87 Simulator stopped\n\n"));
1767 }
1768
1769 /**
1770  * Pre-block walker: calculate the liveness information for the block
1771  * and store it into the sim->live cache.
1772  */
1773 static void update_liveness_walker(ir_node *block, void *data)
1774 {
1775         x87_simulator *sim = (x87_simulator*)data;
1776         update_liveness(sim, block);
1777 }
1778
1779 /*
1780  * Run a simulation and fix all virtual instructions for a graph.
1781  * Replaces all virtual floating point instructions and registers
1782  * by real ones.
1783  */
1784 void ia32_x87_simulate_graph(ir_graph *irg)
1785 {
1786         /* TODO improve code quality (less executed fxch) by using execfreqs */
1787
1788         ir_node       *block, *start_block;
1789         blk_state     *bl_state;
1790         x87_simulator sim;
1791
1792         /* create the simulator */
1793         x87_init_simulator(&sim, irg);
1794
1795         start_block = get_irg_start_block(irg);
1796         bl_state    = x87_get_bl_state(&sim, start_block);
1797
1798         /* start with the empty state */
1799         empty.sim       = &sim;
1800         bl_state->begin = &empty;
1801
1802         sim.worklist = new_waitq();
1803         waitq_put(sim.worklist, start_block);
1804
1805         be_assure_live_sets(irg);
1806         sim.lv = be_get_irg_liveness(irg);
1807
1808         /* Calculate the liveness for all nodes. We must precalculate this info,
1809          * because the simulator adds new nodes (possible before Phi nodes) which
1810          * would let a lazy calculation fail.
1811          * On the other hand we reduce the computation amount due to
1812          * precaching from O(n^2) to O(n) at the expense of O(n) cache memory.
1813          */
1814         irg_block_walk_graph(irg, update_liveness_walker, NULL, &sim);
1815
1816         /* iterate */
1817         do {
1818                 block = (ir_node*)waitq_get(sim.worklist);
1819                 x87_simulate_block(&sim, block);
1820         } while (! waitq_empty(sim.worklist));
1821
1822         /* kill it */
1823         del_waitq(sim.worklist);
1824         x87_destroy_simulator(&sim);
1825 }
1826
1827 /* Initializes the x87 simulator. */
1828 void ia32_init_x87(void)
1829 {
1830         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.x87");
1831 }