SSE3 fisttp instruction added (currently unused due to RA problems)
[libfirm] / ir / be / ia32 / ia32_x87.c
1 /*
2  * Copyright (C) 1995-2008 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  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <assert.h>
32
33 #include "irnode_t.h"
34 #include "irop_t.h"
35 #include "irprog.h"
36 #include "iredges_t.h"
37 #include "irgmod.h"
38 #include "ircons.h"
39 #include "irgwalk.h"
40 #include "obst.h"
41 #include "pmap.h"
42 #include "pdeq.h"
43 #include "irprintf.h"
44 #include "debug.h"
45 #include "error.h"
46
47 #include "../belive_t.h"
48 #include "../besched_t.h"
49 #include "../benode_t.h"
50 #include "bearch_ia32_t.h"
51 #include "ia32_new_nodes.h"
52 #include "gen_ia32_new_nodes.h"
53 #include "gen_ia32_regalloc_if.h"
54 #include "ia32_x87.h"
55 #include "ia32_architecture.h"
56
57 #define N_x87_REGS 8
58
59 /* the unop index */
60 #define UNOP_IDX 0
61
62 #define MASK_TOS(x)             ((x) & (N_x87_REGS - 1))
63
64 /** the debug handle */
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 /* Forward declaration. */
68 typedef struct _x87_simulator x87_simulator;
69
70 /**
71  * An exchange template.
72  * Note that our virtual functions have the same inputs
73  * and attributes as the real ones, so we can simple exchange
74  * their opcodes!
75  * Further, x87 supports inverse instructions, so we can handle them.
76  */
77 typedef struct _exchange_tmpl {
78         ir_op *normal_op;       /**< the normal one */
79         ir_op *reverse_op;      /**< the reverse one if exists */
80         ir_op *normal_pop_op;   /**< the normal one with tos pop */
81         ir_op *reverse_pop_op;  /**< the reverse one with tos pop */
82 } exchange_tmpl;
83
84 /**
85  * An entry on the simulated x87 stack.
86  */
87 typedef struct _st_entry {
88         int     reg_idx;        /**< the virtual register index of this stack value */
89         ir_node *node;          /**< the node that produced this value */
90 } st_entry;
91
92 /**
93  * The x87 state.
94  */
95 typedef struct _x87_state {
96         st_entry st[N_x87_REGS];  /**< the register stack */
97         int depth;                /**< the current stack depth */
98         int tos;                  /**< position of the tos */
99         x87_simulator *sim;       /**< The simulator. */
100 } x87_state;
101
102 /** An empty state, used for blocks without fp instructions. */
103 static x87_state _empty = { { {0, NULL}, }, 0, 0, NULL };
104 static x87_state *empty = (x87_state *)&_empty;
105
106 enum {
107         NO_NODE_ADDED = 0,  /**< No node was added. */
108         NODE_ADDED = 1      /**< A node was added by the simulator in the schedule. */
109 };
110
111 /**
112  * The type of an instruction simulator function.
113  *
114  * @param state  the x87 state
115  * @param n      the node to be simulated
116  *
117  * @return NODE_ADDED if a node was added AFTER n in schedule,
118  *         NO_NODE_ADDED else
119  */
120 typedef int (*sim_func)(x87_state *state, ir_node *n);
121
122 /**
123  * A block state: Every block has a x87 state at the beginning and at the end.
124  */
125 typedef struct _blk_state {
126         x87_state *begin;   /**< state at the begin or NULL if not assigned */
127         x87_state *end;     /**< state at the end or NULL if not assigned */
128 } blk_state;
129
130 #define PTR_TO_BLKSTATE(p)      ((blk_state *)(p))
131
132 /** liveness bitset for vfp registers. */
133 typedef unsigned char vfp_liveness;
134
135 /**
136  * The x87 simulator.
137  */
138 struct _x87_simulator {
139         struct obstack obst;        /**< An obstack for fast allocating. */
140         pmap *blk_states;           /**< Map blocks to states. */
141         const arch_env_t *arch_env; /**< The architecture environment. */
142         be_lv_t *lv;                /**< intrablock liveness. */
143         vfp_liveness *live;         /**< Liveness information. */
144         unsigned n_idx;             /**< The cached get_irg_last_idx() result. */
145         waitq *worklist;            /**< Worklist of blocks that must be processed. */
146         ia32_isa_t *isa;            /**< the ISA object */
147 };
148
149 /**
150  * Returns the current stack depth.
151  *
152  * @param state  the x87 state
153  *
154  * @return the x87 stack depth
155  */
156 static int x87_get_depth(const x87_state *state) {
157         return state->depth;
158 }  /* x87_get_depth */
159
160 /**
161  * Return the virtual register index at st(pos).
162  *
163  * @param state  the x87 state
164  * @param pos    a stack position
165  *
166  * @return the vfp register index that produced the value at st(pos)
167  */
168 static int x87_get_st_reg(const x87_state *state, int pos) {
169         assert(pos < state->depth);
170         return state->st[MASK_TOS(state->tos + pos)].reg_idx;
171 }  /* x87_get_st_reg */
172
173 #ifdef DEBUG_libfirm
174 /**
175  * Return the node at st(pos).
176  *
177  * @param state  the x87 state
178  * @param pos    a stack position
179  *
180  * @return the IR node that produced the value at st(pos)
181  */
182 static ir_node *x87_get_st_node(const x87_state *state, int pos) {
183         assert(pos < state->depth);
184         return state->st[MASK_TOS(state->tos + pos)].node;
185 }  /* x87_get_st_node */
186
187 /**
188  * Dump the stack for debugging.
189  *
190  * @param state  the x87 state
191  */
192 static void x87_dump_stack(const x87_state *state) {
193         int i;
194
195         for (i = state->depth - 1; i >= 0; --i) {
196                 DB((dbg, LEVEL_2, "vf%d(%+F) ", x87_get_st_reg(state, i),
197                     x87_get_st_node(state, i)));
198         }
199         DB((dbg, LEVEL_2, "<-- TOS\n"));
200 }  /* x87_dump_stack */
201 #endif /* DEBUG_libfirm */
202
203 /**
204  * Set a virtual register to st(pos).
205  *
206  * @param state    the x87 state
207  * @param reg_idx  the vfp register index that should be set
208  * @param node     the IR node that produces the value of the vfp register
209  * @param pos      the stack position where the new value should be entered
210  */
211 static void x87_set_st(x87_state *state, int reg_idx, ir_node *node, int pos) {
212         assert(0 < state->depth);
213         state->st[MASK_TOS(state->tos + pos)].reg_idx = reg_idx;
214         state->st[MASK_TOS(state->tos + pos)].node    = node;
215
216         DB((dbg, LEVEL_2, "After SET_REG: "));
217         DEBUG_ONLY(x87_dump_stack(state));
218 }  /* x87_set_st */
219
220 /**
221  * Set the tos virtual register.
222  *
223  * @param state    the x87 state
224  * @param reg_idx  the vfp register index that should be set
225  * @param node     the IR node that produces the value of the vfp register
226  */
227 static void x87_set_tos(x87_state *state, int reg_idx, ir_node *node) {
228         x87_set_st(state, reg_idx, node, 0);
229 }  /* x87_set_tos */
230
231 /**
232  * Swap st(0) with st(pos).
233  *
234  * @param state    the x87 state
235  * @param pos      the stack position to change the tos with
236  */
237 static void x87_fxch(x87_state *state, int pos) {
238         st_entry entry;
239         assert(pos < state->depth);
240
241         entry = state->st[MASK_TOS(state->tos + pos)];
242         state->st[MASK_TOS(state->tos + pos)] = state->st[MASK_TOS(state->tos)];
243         state->st[MASK_TOS(state->tos)] = entry;
244
245         DB((dbg, LEVEL_2, "After FXCH: ")); DEBUG_ONLY(x87_dump_stack(state));
246 }  /* x87_fxch */
247
248 /**
249  * Convert a virtual register to the stack index.
250  *
251  * @param state    the x87 state
252  * @param reg_idx  the register vfp index
253  *
254  * @return the stack position where the register is stacked
255  *         or -1 if the virtual register was not found
256  */
257 static int x87_on_stack(const x87_state *state, int reg_idx) {
258         int i, tos = state->tos;
259
260         for (i = 0; i < state->depth; ++i)
261                 if (state->st[MASK_TOS(tos + i)].reg_idx == reg_idx)
262                         return i;
263         return -1;
264 }  /* x87_on_stack */
265
266 /**
267  * Push a virtual Register onto the stack, double pushed allowed.
268  *
269  * @param state     the x87 state
270  * @param reg_idx   the register vfp index
271  * @param node      the node that produces the value of the vfp register
272  */
273 static void x87_push_dbl(x87_state *state, int reg_idx, ir_node *node) {
274         assert(state->depth < N_x87_REGS && "stack overrun");
275
276         ++state->depth;
277         state->tos = MASK_TOS(state->tos - 1);
278         state->st[state->tos].reg_idx = reg_idx;
279         state->st[state->tos].node    = node;
280
281         DB((dbg, LEVEL_2, "After PUSH: ")); DEBUG_ONLY(x87_dump_stack(state));
282 }  /* x87_push_dbl */
283
284 /**
285  * Push a virtual Register onto the stack, double pushes are NOT allowed.
286  *
287  * @param state     the x87 state
288  * @param reg_idx   the register vfp index
289  * @param node      the node that produces the value of the vfp register
290  * @param dbl_push  if != 0 double pushes are allowed
291  */
292 static void x87_push(x87_state *state, int reg_idx, ir_node *node) {
293         assert(x87_on_stack(state, reg_idx) == -1 && "double push");
294
295         x87_push_dbl(state, reg_idx, node);
296 }  /* x87_push */
297
298 /**
299  * Pop a virtual Register from the stack.
300  *
301  * @param state     the x87 state
302  */
303 static void x87_pop(x87_state *state) {
304         assert(state->depth > 0 && "stack underrun");
305
306         --state->depth;
307         state->tos = MASK_TOS(state->tos + 1);
308
309         DB((dbg, LEVEL_2, "After POP: ")); DEBUG_ONLY(x87_dump_stack(state));
310 }  /* x87_pop */
311
312 /**
313  * Empty the fpu stack
314  *
315  * @param state     the x87 state
316  */
317 static void x87_emms(x87_state *state) {
318         state->depth = 0;
319         state->tos   = 0;
320 }
321
322 /**
323  * Returns the block state of a block.
324  *
325  * @param sim    the x87 simulator handle
326  * @param block  the current block
327  *
328  * @return the block state
329  */
330 static blk_state *x87_get_bl_state(x87_simulator *sim, ir_node *block) {
331         pmap_entry *entry = pmap_find(sim->blk_states, block);
332
333         if (! entry) {
334                 blk_state *bl_state = obstack_alloc(&sim->obst, sizeof(*bl_state));
335                 bl_state->begin = NULL;
336                 bl_state->end   = NULL;
337
338                 pmap_insert(sim->blk_states, block, bl_state);
339                 return bl_state;
340         }
341
342         return PTR_TO_BLKSTATE(entry->value);
343 }  /* x87_get_bl_state */
344
345 /**
346  * Creates a new x87 state.
347  *
348  * @param sim    the x87 simulator handle
349  *
350  * @return a new x87 state
351  */
352 static x87_state *x87_alloc_state(x87_simulator *sim) {
353         x87_state *res = obstack_alloc(&sim->obst, sizeof(*res));
354
355         res->sim = sim;
356         return res;
357 }  /* x87_alloc_state */
358
359 /**
360  * Clone a x87 state.
361  *
362  * @param sim    the x87 simulator handle
363  * @param src    the x87 state that will be cloned
364  *
365  * @return a cloned copy of the src state
366  */
367 static x87_state *x87_clone_state(x87_simulator *sim, const x87_state *src) {
368         x87_state *res = x87_alloc_state(sim);
369
370         memcpy(res, src, sizeof(*res));
371         return res;
372 }  /* x87_clone_state */
373
374 /**
375  * Patch a virtual instruction into a x87 one and return
376  * the node representing the result value.
377  *
378  * @param n   the IR node to patch
379  * @param op  the x87 opcode to patch in
380  */
381 static ir_node *x87_patch_insn(ir_node *n, ir_op *op) {
382         ir_mode *mode = get_irn_mode(n);
383         ir_node *res = n;
384
385         set_irn_op(n, op);
386
387         if (mode == mode_T) {
388                 /* patch all Proj's */
389                 const ir_edge_t *edge;
390
391                 foreach_out_edge(n, edge) {
392                         ir_node *proj = get_edge_src_irn(edge);
393                         if (is_Proj(proj)) {
394                                 mode = get_irn_mode(proj);
395                                 if (mode_is_float(mode)) {
396                                         res = proj;
397                                         set_irn_mode(proj, mode_E);
398                                 }
399                         }
400                 }
401         } else if (mode_is_float(mode))
402                 set_irn_mode(n, mode_E);
403         return res;
404 }  /* x87_patch_insn */
405
406 /**
407  * Returns the first Proj of a mode_T node having a given mode.
408  *
409  * @param n  the mode_T node
410  * @param m  the desired mode of the Proj
411  * @return The first Proj of mode @p m found or NULL.
412  */
413 static ir_node *get_irn_Proj_for_mode(ir_node *n, ir_mode *m) {
414         const ir_edge_t *edge;
415
416         assert(get_irn_mode(n) == mode_T && "Need mode_T node");
417
418         foreach_out_edge(n, edge) {
419                 ir_node *proj = get_edge_src_irn(edge);
420                 if (get_irn_mode(proj) == m)
421                         return proj;
422         }
423
424         return NULL;
425 }  /* get_irn_Proj_for_mode */
426
427 /**
428  * Wrap the arch_* function here so we can check for errors.
429  */
430 static INLINE const arch_register_t *x87_get_irn_register(x87_simulator *sim, const ir_node *irn) {
431         const arch_register_t *res;
432
433         res = arch_get_irn_register(sim->arch_env, irn);
434         assert(res->reg_class->regs == ia32_vfp_regs);
435         return res;
436 }  /* x87_get_irn_register */
437
438 /* -------------- x87 perm --------------- */
439
440 /**
441  * Creates a fxch for shuffle.
442  *
443  * @param state     the x87 state
444  * @param pos       parameter for fxch
445  * @param block     the block were fxch is inserted
446  *
447  * Creates a new fxch node and reroute the user of the old node
448  * to the fxch.
449  *
450  * @return the fxch node
451  */
452 static ir_node *x87_fxch_shuffle(x87_state *state, int pos, ir_node *block) {
453         ir_node         *fxch;
454         ia32_x87_attr_t *attr;
455
456         fxch = new_rd_ia32_fxch(NULL, get_irn_irg(block), block);
457         attr = get_ia32_x87_attr(fxch);
458         attr->x87[0] = &ia32_st_regs[pos];
459         attr->x87[2] = &ia32_st_regs[0];
460
461         keep_alive(fxch);
462
463         x87_fxch(state, pos);
464         return fxch;
465 }  /* x87_fxch_shuffle */
466
467 /**
468  * Calculate the necessary permutations to reach dst_state.
469  *
470  * These permutations are done with fxch instructions and placed
471  * at the end of the block.
472  *
473  * Note that critical edges are removed here, so we need only
474  * a shuffle if the current block has only one successor.
475  *
476  * @param sim        the simulator handle
477  * @param block      the current block
478  * @param state      the current x87 stack state, might be modified
479  * @param dst_block  the destination block
480  * @param dst_state  destination state
481  *
482  * @return state
483  */
484 static x87_state *x87_shuffle(x87_simulator *sim, ir_node *block,
485                               x87_state *state, ir_node *dst_block,
486                               const x87_state *dst_state)
487 {
488         int      i, n_cycles, k, ri;
489         unsigned cycles[4], all_mask;
490         char     cycle_idx[4][8];
491         ir_node  *fxch, *before, *after;
492         (void) sim;
493         (void) dst_block;
494
495         assert(state->depth == dst_state->depth);
496
497         /* Some mathematics here:
498            If we have a cycle of length n that includes the tos,
499            we need n-1 exchange operations.
500            We can always add the tos and restore it, so we need
501            n+1 exchange operations for a cycle not containing the tos.
502            So, the maximum of needed operations is for a cycle of 7
503            not including the tos == 8.
504            This is the same number of ops we would need for using stores,
505            so exchange is cheaper (we save the loads).
506            On the other hand, we might need an additional exchange
507            in the next block to bring one operand on top, so the
508            number of ops in the first case is identical.
509            Further, no more than 4 cycles can exists (4 x 2).
510         */
511         all_mask = (1 << (state->depth)) - 1;
512
513         for (n_cycles = 0; all_mask; ++n_cycles) {
514                 int src_idx, dst_idx;
515
516                 /* find the first free slot */
517                 for (i = 0; i < state->depth; ++i) {
518                         if (all_mask & (1 << i)) {
519                                 all_mask &= ~(1 << i);
520
521                                 /* check if there are differences here */
522                                 if (x87_get_st_reg(state, i) != x87_get_st_reg(dst_state, i))
523                                         break;
524                         }
525                 }
526
527                 if (! all_mask) {
528                         /* no more cycles found */
529                         break;
530                 }
531
532                 k = 0;
533                 cycles[n_cycles] = (1 << i);
534                 cycle_idx[n_cycles][k++] = i;
535                 for (src_idx = i; ; src_idx = dst_idx) {
536                         dst_idx = x87_on_stack(dst_state, x87_get_st_reg(state, src_idx));
537
538                         if ((all_mask & (1 << dst_idx)) == 0)
539                                 break;
540
541                         cycle_idx[n_cycles][k++] = dst_idx;
542                         cycles[n_cycles] |=  (1 << dst_idx);
543                         all_mask       &= ~(1 << dst_idx);
544                 }
545                 cycle_idx[n_cycles][k] = -1;
546         }
547
548         if (n_cycles <= 0) {
549                 /* no permutation needed */
550                 return state;
551         }
552
553         /* Hmm: permutation needed */
554         DB((dbg, LEVEL_2, "\n%+F needs permutation: from\n", block));
555         DEBUG_ONLY(x87_dump_stack(state));
556         DB((dbg, LEVEL_2, "                  to\n"));
557         DEBUG_ONLY(x87_dump_stack(dst_state));
558
559
560 #ifdef DEBUG_libfirm
561         DB((dbg, LEVEL_2, "Need %d cycles\n", n_cycles));
562         for (ri = 0; ri < n_cycles; ++ri) {
563                 DB((dbg, LEVEL_2, " Ring %d:\n ", ri));
564                 for (k = 0; cycle_idx[ri][k] != -1; ++k)
565                         DB((dbg, LEVEL_2, " st%d ->", cycle_idx[ri][k]));
566                 DB((dbg, LEVEL_2, "\n"));
567         }
568 #endif
569
570         after = NULL;
571
572         /*
573          * Find the place node must be insert.
574          * We have only one successor block, so the last instruction should
575          * be a jump.
576          */
577         before = sched_last(block);
578         assert(is_cfop(before));
579
580         /* now do the permutations */
581         for (ri = 0; ri < n_cycles; ++ri) {
582                 if ((cycles[ri] & 1) == 0) {
583                         /* this cycle does not include the tos */
584                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
585                         if (after)
586                                 sched_add_after(after, fxch);
587                         else
588                                 sched_add_before(before, fxch);
589                         after = fxch;
590                 }
591                 for (k = 1; cycle_idx[ri][k] != -1; ++k) {
592                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][k], block);
593                         if (after)
594                                 sched_add_after(after, fxch);
595                         else
596                                 sched_add_before(before, fxch);
597                         after = fxch;
598                 }
599                 if ((cycles[ri] & 1) == 0) {
600                         /* this cycle does not include the tos */
601                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
602                         sched_add_after(after, fxch);
603                 }
604         }
605         return state;
606 }  /* x87_shuffle */
607
608 /**
609  * Create a fxch node before another node.
610  *
611  * @param state   the x87 state
612  * @param n       the node after the fxch
613  * @param pos     exchange st(pos) with st(0)
614  *
615  * @return the fxch
616  */
617 static ir_node *x87_create_fxch(x87_state *state, ir_node *n, int pos)
618 {
619         ir_node         *fxch;
620         ia32_x87_attr_t *attr;
621         ir_graph        *irg = get_irn_irg(n);
622         ir_node         *block = get_nodes_block(n);
623
624         x87_fxch(state, pos);
625
626         fxch = new_rd_ia32_fxch(NULL, irg, block);
627         attr = get_ia32_x87_attr(fxch);
628         attr->x87[0] = &ia32_st_regs[pos];
629         attr->x87[2] = &ia32_st_regs[0];
630
631         keep_alive(fxch);
632
633         sched_add_before(n, fxch);
634         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fxch), attr->x87[0]->name, attr->x87[2]->name));
635         return fxch;
636 }  /* x87_create_fxch */
637
638 /**
639  * Create a fpush before node n.
640  *
641  * @param state     the x87 state
642  * @param n         the node after the fpush
643  * @param pos       push st(pos) on stack
644  * @param op_idx    replace input op_idx of n with the fpush result
645  */
646 static void x87_create_fpush(x87_state *state, ir_node *n, int pos, int op_idx) {
647         ir_node               *fpush, *pred = get_irn_n(n, op_idx);
648         ia32_x87_attr_t       *attr;
649         const arch_register_t *out = x87_get_irn_register(state->sim, pred);
650
651         x87_push_dbl(state, arch_register_get_index(out), pred);
652
653         fpush = new_rd_ia32_fpush(NULL, get_irn_irg(n), get_nodes_block(n));
654         attr  = get_ia32_x87_attr(fpush);
655         attr->x87[0] = &ia32_st_regs[pos];
656         attr->x87[2] = &ia32_st_regs[0];
657
658         keep_alive(fpush);
659         sched_add_before(n, fpush);
660
661         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fpush), attr->x87[0]->name, attr->x87[2]->name));
662 }  /* x87_create_fpush */
663
664 /**
665  * Create a fpop before node n.
666  *
667  * @param state   the x87 state
668  * @param n       the node after the fpop
669  * @param num     pop 1 or 2 values
670  *
671  * @return the fpop node
672  */
673 static ir_node *x87_create_fpop(x87_state *state, ir_node *n, int num)
674 {
675         ir_node         *fpop = NULL;
676         ia32_x87_attr_t *attr;
677
678         assert(num > 0);
679         while (num > 0) {
680                 x87_pop(state);
681                 if (ia32_cg_config.use_ffreep)
682                         fpop = new_rd_ia32_ffreep(NULL, get_irn_irg(n), get_nodes_block(n));
683                 else
684                         fpop = new_rd_ia32_fpop(NULL, get_irn_irg(n), get_nodes_block(n));
685                 attr = get_ia32_x87_attr(fpop);
686                 attr->x87[0] = &ia32_st_regs[0];
687                 attr->x87[1] = &ia32_st_regs[0];
688                 attr->x87[2] = &ia32_st_regs[0];
689
690                 keep_alive(fpop);
691                 sched_add_before(n, fpop);
692                 DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fpop), attr->x87[0]->name));
693
694                 --num;
695         }
696         return fpop;
697 }  /* x87_create_fpop */
698
699 /**
700  * Creates an fldz before node n
701  *
702  * @param state   the x87 state
703  * @param n       the node after the fldz
704  *
705  * @return the fldz node
706  */
707 static ir_node *x87_create_fldz(x87_state *state, ir_node *n, int regidx) {
708         ir_graph *irg = get_irn_irg(n);
709         ir_node *block = get_nodes_block(n);
710         ir_node *fldz;
711
712         fldz = new_rd_ia32_fldz(NULL, irg, block, mode_E);
713
714         sched_add_before(n, fldz);
715         DB((dbg, LEVEL_1, "<<< %s\n", get_irn_opname(fldz)));
716         keep_alive(fldz);
717
718         x87_push(state, regidx, fldz);
719
720         return fldz;
721 }
722
723 /* --------------------------------- liveness ------------------------------------------ */
724
725 /**
726  * The liveness transfer function.
727  * Updates a live set over a single step from a given node to its predecessor.
728  * Everything defined at the node is removed from the set, the uses of the node get inserted.
729  *
730  * @param sim      The simulator handle.
731  * @param irn      The node at which liveness should be computed.
732  * @param live     The bitset of registers live before @p irn. This set gets modified by updating it to
733  *                 the registers live after irn.
734  *
735  * @return The live bitset.
736  */
737 static vfp_liveness vfp_liveness_transfer(x87_simulator *sim, ir_node *irn, vfp_liveness live)
738 {
739         int i, n;
740         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
741         const arch_env_t *arch_env = sim->arch_env;
742
743         if (get_irn_mode(irn) == mode_T) {
744                 const ir_edge_t *edge;
745
746                 foreach_out_edge(irn, edge) {
747                         ir_node *proj = get_edge_src_irn(edge);
748
749                         if (arch_irn_consider_in_reg_alloc(arch_env, cls, proj)) {
750                                 const arch_register_t *reg = x87_get_irn_register(sim, proj);
751                                 live &= ~(1 << arch_register_get_index(reg));
752                         }
753                 }
754         }
755
756         if (arch_irn_consider_in_reg_alloc(arch_env, cls, irn)) {
757                 const arch_register_t *reg = x87_get_irn_register(sim, irn);
758                 live &= ~(1 << arch_register_get_index(reg));
759         }
760
761         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
762                 ir_node *op = get_irn_n(irn, i);
763
764                 if (mode_is_float(get_irn_mode(op)) && arch_irn_consider_in_reg_alloc(arch_env, cls, op)) {
765                         const arch_register_t *reg = x87_get_irn_register(sim, op);
766                         live |= 1 << arch_register_get_index(reg);
767                 }
768         }
769         return live;
770 }  /* vfp_liveness_transfer */
771
772 /**
773  * Put all live virtual registers at the end of a block into a bitset.
774  *
775  * @param sim      the simulator handle
776  * @param lv       the liveness information
777  * @param bl       the block
778  *
779  * @return The live bitset at the end of this block
780  */
781 static vfp_liveness vfp_liveness_end_of_block(x87_simulator *sim, const ir_node *block)
782 {
783         int i;
784         vfp_liveness live = 0;
785         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
786         const arch_env_t *arch_env = sim->arch_env;
787         const be_lv_t *lv = sim->lv;
788
789         be_lv_foreach(lv, block, be_lv_state_end, i) {
790                 const arch_register_t *reg;
791                 const ir_node *node = be_lv_get_irn(lv, block, i);
792                 if (!arch_irn_consider_in_reg_alloc(arch_env, cls, node))
793                         continue;
794
795                 reg = x87_get_irn_register(sim, node);
796                 live |= 1 << arch_register_get_index(reg);
797         }
798
799         return live;
800 }  /* vfp_liveness_end_of_block */
801
802 /** get the register mask from an arch_register */
803 #define REGMASK(reg)    (1 << (arch_register_get_index(reg)))
804
805 /**
806  * Return a bitset of argument registers which are live at the end of a node.
807  *
808  * @param sim    the simulator handle
809  * @param pos    the node
810  * @param kill   kill mask for the output registers
811  *
812  * @return The live bitset.
813  */
814 static unsigned vfp_live_args_after(x87_simulator *sim, const ir_node *pos, unsigned kill)
815 {
816         unsigned idx = get_irn_idx(pos);
817
818         assert(idx < sim->n_idx);
819         return sim->live[idx] & ~kill;
820 }  /* vfp_live_args_after */
821
822 /**
823  * Calculate the liveness for a whole block and cache it.
824  *
825  * @param sim   the simulator handle
826  * @param lv    the liveness handle
827  * @param block the block
828  */
829 static void update_liveness(x87_simulator *sim, ir_node *block) {
830         vfp_liveness live = vfp_liveness_end_of_block(sim, block);
831         unsigned idx;
832         ir_node *irn;
833
834         /* now iterate through the block backward and cache the results */
835         sched_foreach_reverse(block, irn) {
836                 /* stop at the first Phi: this produces the live-in */
837                 if (is_Phi(irn))
838                         break;
839
840                 idx = get_irn_idx(irn);
841                 sim->live[idx] = live;
842
843                 live = vfp_liveness_transfer(sim, irn, live);
844         }
845         idx = get_irn_idx(block);
846         sim->live[idx] = live;
847 }  /* update_liveness */
848
849 /**
850  * Returns true if a register is live in a set.
851  *
852  * @param reg_idx  the vfp register index
853  * @param live     a live bitset
854  */
855 #define is_vfp_live(reg_idx, live) ((live) & (1 << (reg_idx)))
856
857 #ifdef DEBUG_libfirm
858 /**
859  * Dump liveness info.
860  *
861  * @param live  the live bitset
862  */
863 static void vfp_dump_live(vfp_liveness live) {
864         int i;
865
866         DB((dbg, LEVEL_2, "Live after: "));
867         for (i = 0; i < 8; ++i) {
868                 if (live & (1 << i)) {
869                         DB((dbg, LEVEL_2, "vf%d ", i));
870                 }
871         }
872         DB((dbg, LEVEL_2, "\n"));
873 }  /* vfp_dump_live */
874 #endif /* DEBUG_libfirm */
875
876 /* --------------------------------- simulators ---------------------------------------- */
877
878 #define XCHG(a, b) do { int t = (a); (a) = (b); (b) = t; } while (0)
879
880 /* Pseudocode:
881
882
883
884
885
886
887 */
888
889 /**
890  * Simulate a virtual binop.
891  *
892  * @param state  the x87 state
893  * @param n      the node that should be simulated (and patched)
894  * @param tmpl   the template containing the 4 possible x87 opcodes
895  *
896  * @return NO_NODE_ADDED
897  */
898 static int sim_binop(x87_state *state, ir_node *n, const exchange_tmpl *tmpl) {
899         int op2_idx = 0, op1_idx;
900         int out_idx, do_pop = 0;
901         ia32_x87_attr_t *attr;
902         ir_node *patched_insn;
903         ir_op *dst;
904         x87_simulator         *sim     = state->sim;
905         ir_node               *op1     = get_irn_n(n, n_ia32_binary_left);
906         ir_node               *op2     = get_irn_n(n, n_ia32_binary_right);
907         const arch_register_t *op1_reg = x87_get_irn_register(sim, op1);
908         const arch_register_t *op2_reg = x87_get_irn_register(sim, op2);
909         const arch_register_t *out     = x87_get_irn_register(sim, n);
910         int reg_index_1                = arch_register_get_index(op1_reg);
911         int reg_index_2                = arch_register_get_index(op2_reg);
912         vfp_liveness           live    = vfp_live_args_after(sim, n, REGMASK(out));
913         int                    op1_live_after;
914         int                    op2_live_after;
915
916         DB((dbg, LEVEL_1, ">>> %+F %s, %s -> %s\n", n,
917                 arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
918                 arch_register_get_name(out)));
919         DEBUG_ONLY(vfp_dump_live(live));
920         DB((dbg, LEVEL_1, "Stack before: "));
921         DEBUG_ONLY(x87_dump_stack(state));
922
923         if(reg_index_1 == REG_VFP_UKNWN) {
924                 op1_idx        = 0;
925                 op1_live_after = 1;
926         } else {
927                 op1_idx = x87_on_stack(state, reg_index_1);
928                 assert(op1_idx >= 0);
929                 op1_live_after = is_vfp_live(arch_register_get_index(op1_reg), live);
930         }
931
932         if (reg_index_2 != REG_VFP_NOREG) {
933                 if(reg_index_2 == REG_VFP_UKNWN) {
934                         op2_idx        = 0;
935                         op2_live_after = 1;
936                 } else {
937                         /* second operand is a vfp register */
938                         op2_idx = x87_on_stack(state, reg_index_2);
939                         assert(op2_idx >= 0);
940                         op2_live_after
941                                 = is_vfp_live(arch_register_get_index(op2_reg), live);
942                 }
943
944                 if (op2_live_after) {
945                         /* Second operand is live. */
946
947                         if (op1_live_after) {
948                                 /* Both operands are live: push the first one.
949                                    This works even for op1 == op2. */
950                                 x87_create_fpush(state, n, op1_idx, n_ia32_binary_right);
951                                 /* now do fxxx (tos=tos X op) */
952                                 op1_idx = 0;
953                                 op2_idx += 1;
954                                 out_idx = 0;
955                                 dst = tmpl->normal_op;
956                         } else {
957                                 /* Second live, first operand is dead here, bring it to tos. */
958                                 if (op1_idx != 0) {
959                                         x87_create_fxch(state, n, op1_idx);
960                                         if (op2_idx == 0)
961                                                 op2_idx = op1_idx;
962                                         op1_idx = 0;
963                                 }
964                                 /* now do fxxx (tos=tos X op) */
965                                 out_idx = 0;
966                                 dst = tmpl->normal_op;
967                         }
968                 } else {
969                         /* Second operand is dead. */
970                         if (op1_live_after) {
971                                 /* First operand is live: bring second to tos. */
972                                 if (op2_idx != 0) {
973                                         x87_create_fxch(state, n, op2_idx);
974                                         if (op1_idx == 0)
975                                                 op1_idx = op2_idx;
976                                         op2_idx = 0;
977                                 }
978                                 /* now do fxxxr (tos = op X tos) */
979                                 out_idx = 0;
980                                 dst = tmpl->reverse_op;
981                         } else {
982                                 /* Both operands are dead here, pop them from the stack. */
983                                 if (op2_idx == 0) {
984                                         if (op1_idx == 0) {
985                                                 /* Both are identically and on tos, no pop needed. */
986                                                 /* here fxxx (tos = tos X tos) */
987                                                 dst = tmpl->normal_op;
988                                                 out_idx = 0;
989                                         } else {
990                                                 /* now do fxxxp (op = op X tos, pop) */
991                                                 dst = tmpl->normal_pop_op;
992                                                 do_pop = 1;
993                                                 out_idx = op1_idx;
994                                         }
995                                 } else if (op1_idx == 0) {
996                                         assert(op1_idx != op2_idx);
997                                         /* now do fxxxrp (op = tos X op, pop) */
998                                         dst = tmpl->reverse_pop_op;
999                                         do_pop = 1;
1000                                         out_idx = op2_idx;
1001                                 } else {
1002                                         /* Bring the second on top. */
1003                                         x87_create_fxch(state, n, op2_idx);
1004                                         if (op1_idx == op2_idx) {
1005                                                 /* Both are identically and on tos now, no pop needed. */
1006                                                 op1_idx = 0;
1007                                                 op2_idx = 0;
1008                                                 /* use fxxx (tos = tos X tos) */
1009                                                 dst = tmpl->normal_op;
1010                                                 out_idx = 0;
1011                                         } else {
1012                                                 /* op2 is on tos now */
1013                                                 op2_idx = 0;
1014                                                 /* use fxxxp (op = op X tos, pop) */
1015                                                 dst = tmpl->normal_pop_op;
1016                                                 out_idx = op1_idx;
1017                                                 do_pop = 1;
1018                                         }
1019                                 }
1020                         }
1021                 }
1022         } else {
1023                 /* second operand is an address mode */
1024                 if (op1_live_after) {
1025                         /* first operand is live: push it here */
1026                         x87_create_fpush(state, n, op1_idx, n_ia32_binary_left);
1027                         op1_idx = 0;
1028                         /* use fxxx (tos = tos X mem) */
1029                         dst = tmpl->normal_op;
1030                         out_idx = 0;
1031                 } else {
1032                         /* first operand is dead: bring it to tos */
1033                         if (op1_idx != 0) {
1034                                 x87_create_fxch(state, n, op1_idx);
1035                                 op1_idx = 0;
1036                         }
1037
1038                         /* use fxxxp (tos = tos X mem) */
1039                         dst = tmpl->normal_op;
1040                         out_idx = 0;
1041                 }
1042         }
1043
1044         patched_insn = x87_patch_insn(n, dst);
1045         x87_set_st(state, arch_register_get_index(out), patched_insn, out_idx);
1046         if (do_pop) {
1047                 x87_pop(state);
1048         }
1049
1050         /* patch the operation */
1051         attr = get_ia32_x87_attr(n);
1052         attr->x87[0] = op1_reg = &ia32_st_regs[op1_idx];
1053         if (reg_index_2 != REG_VFP_NOREG) {
1054                 attr->x87[1] = op2_reg = &ia32_st_regs[op2_idx];
1055         }
1056         attr->x87[2] = out = &ia32_st_regs[out_idx];
1057
1058         if (reg_index_2 != REG_VFP_NOREG) {
1059                 DB((dbg, LEVEL_1, "<<< %s %s, %s -> %s\n", get_irn_opname(n),
1060                         arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
1061                         arch_register_get_name(out)));
1062         } else {
1063                 DB((dbg, LEVEL_1, "<<< %s %s, [AM] -> %s\n", get_irn_opname(n),
1064                         arch_register_get_name(op1_reg),
1065                         arch_register_get_name(out)));
1066         }
1067
1068         return NO_NODE_ADDED;
1069 }  /* sim_binop */
1070
1071 /**
1072  * Simulate a virtual Unop.
1073  *
1074  * @param state  the x87 state
1075  * @param n      the node that should be simulated (and patched)
1076  * @param op     the x87 opcode that will replace n's opcode
1077  *
1078  * @return NO_NODE_ADDED
1079  */
1080 static int sim_unop(x87_state *state, ir_node *n, ir_op *op) {
1081         int op1_idx, out_idx;
1082         x87_simulator         *sim = state->sim;
1083         const arch_register_t *op1 = x87_get_irn_register(sim, get_irn_n(n, UNOP_IDX));
1084         const arch_register_t *out = x87_get_irn_register(sim, n);
1085         ia32_x87_attr_t *attr;
1086         unsigned live = vfp_live_args_after(sim, n, REGMASK(out));
1087
1088         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, out->name));
1089         DEBUG_ONLY(vfp_dump_live(live));
1090
1091         op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1092
1093         if (is_vfp_live(arch_register_get_index(op1), live)) {
1094                 /* push the operand here */
1095                 x87_create_fpush(state, n, op1_idx, UNOP_IDX);
1096                 op1_idx = 0;
1097         }
1098         else {
1099                 /* operand is dead, bring it to tos */
1100                 if (op1_idx != 0) {
1101                         x87_create_fxch(state, n, op1_idx);
1102                         op1_idx = 0;
1103                 }
1104         }
1105
1106         x87_set_tos(state, arch_register_get_index(out), x87_patch_insn(n, op));
1107         out_idx = 0;
1108         attr = get_ia32_x87_attr(n);
1109         attr->x87[0] = op1 = &ia32_st_regs[0];
1110         attr->x87[2] = out = &ia32_st_regs[0];
1111         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), out->name));
1112
1113         return NO_NODE_ADDED;
1114 }  /* sim_unop */
1115
1116 /**
1117  * Simulate a virtual Load instruction.
1118  *
1119  * @param state  the x87 state
1120  * @param n      the node that should be simulated (and patched)
1121  * @param op     the x87 opcode that will replace n's opcode
1122  *
1123  * @return NO_NODE_ADDED
1124  */
1125 static int sim_load(x87_state *state, ir_node *n, ir_op *op) {
1126         const arch_register_t *out = x87_get_irn_register(state->sim, n);
1127         ia32_x87_attr_t *attr;
1128
1129         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, arch_register_get_name(out)));
1130         x87_push(state, arch_register_get_index(out), x87_patch_insn(n, op));
1131         assert(out == x87_get_irn_register(state->sim, n));
1132         attr = get_ia32_x87_attr(n);
1133         attr->x87[2] = out = &ia32_st_regs[0];
1134         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), arch_register_get_name(out)));
1135
1136         return NO_NODE_ADDED;
1137 }  /* sim_load */
1138
1139 /**
1140  * Rewire all users of @p old_val to @new_val iff they are scheduled after @p store.
1141  *
1142  * @param store   The store
1143  * @param old_val The former value
1144  * @param new_val The new value
1145  */
1146 static void collect_and_rewire_users(ir_node *store, ir_node *old_val, ir_node *new_val) {
1147         const ir_edge_t *edge, *ne;
1148
1149         foreach_out_edge_safe(old_val, edge, ne) {
1150                 ir_node *user = get_edge_src_irn(edge);
1151
1152                 if (! user || user == store)
1153                         continue;
1154
1155                 /* if the user is scheduled after the store: rewire */
1156                 if (sched_is_scheduled(user) && sched_comes_after(store, user)) {
1157                         int i;
1158                         /* find the input of the user pointing to the old value */
1159                         for (i = get_irn_arity(user) - 1; i >= 0; i--) {
1160                                 if (get_irn_n(user, i) == old_val)
1161                                         set_irn_n(user, i, new_val);
1162                         }
1163                 }
1164         }
1165 }  /* collect_and_rewire_users */
1166
1167 /**
1168  * Simulate a virtual Store.
1169  *
1170  * @param state  the x87 state
1171  * @param n      the node that should be simulated (and patched)
1172  * @param op     the x87 store opcode
1173  * @param op_p   the x87 store and pop opcode
1174  */
1175 static int sim_store(x87_state *state, ir_node *n, ir_op *op, ir_op *op_p) {
1176         x87_simulator         *sim = state->sim;
1177         ir_node               *val = get_irn_n(n, n_ia32_vfst_val);
1178         const arch_register_t *op2 = x87_get_irn_register(sim, val);
1179         unsigned              live = vfp_live_args_after(sim, n, 0);
1180         int                   insn = NO_NODE_ADDED;
1181         ia32_x87_attr_t *attr;
1182         int op2_reg_idx, op2_idx, depth;
1183         int live_after_node;
1184         ir_mode *mode;
1185
1186         op2_reg_idx = arch_register_get_index(op2);
1187         if (op2_reg_idx == REG_VFP_UKNWN) {
1188                 /* just take any value from stack */
1189                 if(state->depth > 0) {
1190                         op2_idx = 0;
1191                         DEBUG_ONLY(op2 = NULL);
1192                         live_after_node = 1;
1193                 } else {
1194                         /* produce a new value which we will consume immediately */
1195                         x87_create_fldz(state, n, op2_reg_idx);
1196                         live_after_node = 0;
1197                         op2_idx = x87_on_stack(state, op2_reg_idx);
1198                         assert(op2_idx >= 0);
1199                 }
1200         } else {
1201                 op2_idx = x87_on_stack(state, op2_reg_idx);
1202                 live_after_node = is_vfp_live(arch_register_get_index(op2), live);
1203                 DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1204                 assert(op2_idx >= 0);
1205         }
1206
1207         mode  = get_ia32_ls_mode(n);
1208         depth = x87_get_depth(state);
1209
1210         if (live_after_node) {
1211                 /*
1212                         Problem: fst doesn't support mode_E (spills), only fstp does
1213                         Solution:
1214                                 - stack not full: push value and fstp
1215                                 - stack full: fstp value and load again
1216                         Note that we cannot test on mode_E, because floats might be 96bit ...
1217                 */
1218                 if (get_mode_size_bits(mode) > 64 || mode == mode_Ls) {
1219                         if (depth < N_x87_REGS) {
1220                                 /* ok, we have a free register: push + fstp */
1221                                 x87_create_fpush(state, n, op2_idx, n_ia32_vfst_val);
1222                                 x87_pop(state);
1223                                 x87_patch_insn(n, op_p);
1224                         } else {
1225                                 ir_node  *vfld, *mem, *block, *rproj, *mproj;
1226                                 ir_graph *irg;
1227
1228                                 /* stack full here: need fstp + load */
1229                                 x87_pop(state);
1230                                 x87_patch_insn(n, op_p);
1231
1232                                 block = get_nodes_block(n);
1233                                 irg   = get_irn_irg(n);
1234                                 vfld  = new_rd_ia32_vfld(NULL, irg, block, get_irn_n(n, 0), get_irn_n(n, 1), new_rd_NoMem(irg), get_ia32_ls_mode(n));
1235
1236                                 /* copy all attributes */
1237                                 set_ia32_frame_ent(vfld, get_ia32_frame_ent(n));
1238                                 if (is_ia32_use_frame(n))
1239                                         set_ia32_use_frame(vfld);
1240                                 set_ia32_op_type(vfld, ia32_am_Source);
1241                                 add_ia32_am_offs_int(vfld, get_ia32_am_offs_int(n));
1242                                 set_ia32_am_sc(vfld, get_ia32_am_sc(n));
1243                                 set_ia32_ls_mode(vfld, get_ia32_ls_mode(n));
1244
1245                                 rproj = new_r_Proj(irg, block, vfld, get_ia32_ls_mode(vfld), pn_ia32_vfld_res);
1246                                 mproj = new_r_Proj(irg, block, vfld, mode_M, pn_ia32_vfld_M);
1247                                 mem   = get_irn_Proj_for_mode(n, mode_M);
1248
1249                                 assert(mem && "Store memory not found");
1250
1251                                 arch_set_irn_register(sim->arch_env, rproj, op2);
1252
1253                                 /* reroute all former users of the store memory to the load memory */
1254                                 edges_reroute(mem, mproj, irg);
1255                                 /* set the memory input of the load to the store memory */
1256                                 set_irn_n(vfld, n_ia32_vfld_mem, mem);
1257
1258                                 sched_add_after(n, vfld);
1259                                 sched_add_after(vfld, rproj);
1260
1261                                 /* rewire all users, scheduled after the store, to the loaded value */
1262                                 collect_and_rewire_users(n, val, rproj);
1263
1264                                 insn = NODE_ADDED;
1265                         }
1266                 } else {
1267                         /* we can only store the tos to memory */
1268                         if (op2_idx != 0)
1269                                 x87_create_fxch(state, n, op2_idx);
1270
1271                         /* mode != mode_E -> use normal fst */
1272                         x87_patch_insn(n, op);
1273                 }
1274         } else {
1275                 /* we can only store the tos to memory */
1276                 if (op2_idx != 0)
1277                         x87_create_fxch(state, n, op2_idx);
1278
1279                 x87_pop(state);
1280                 x87_patch_insn(n, op_p);
1281         }
1282
1283         attr = get_ia32_x87_attr(n);
1284         attr->x87[1] = op2 = &ia32_st_regs[0];
1285         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(op2)));
1286
1287         return insn;
1288 }  /* sim_store */
1289
1290 #define _GEN_BINOP(op, rev) \
1291 static int sim_##op(x87_state *state, ir_node *n) { \
1292         exchange_tmpl tmpl = { op_ia32_##op, op_ia32_##rev, op_ia32_##op##p, op_ia32_##rev##p }; \
1293         return sim_binop(state, n, &tmpl); \
1294 }
1295
1296 #define GEN_BINOP(op)   _GEN_BINOP(op, op)
1297 #define GEN_BINOPR(op)  _GEN_BINOP(op, op##r)
1298
1299 #define GEN_LOAD2(op, nop) \
1300 static int sim_##op(x87_state *state, ir_node *n) { \
1301         return sim_load(state, n, op_ia32_##nop); \
1302 }
1303
1304 #define GEN_LOAD(op)    GEN_LOAD2(op, op)
1305
1306 #define GEN_UNOP(op) \
1307 static int sim_##op(x87_state *state, ir_node *n) { \
1308         return sim_unop(state, n, op_ia32_##op); \
1309 }
1310
1311 #define GEN_STORE(op) \
1312 static int sim_##op(x87_state *state, ir_node *n) { \
1313         return sim_store(state, n, op_ia32_##op, op_ia32_##op##p); \
1314 }
1315
1316 /* all stubs */
1317 GEN_BINOP(fadd)
1318 GEN_BINOPR(fsub)
1319 GEN_BINOP(fmul)
1320 GEN_BINOPR(fdiv)
1321 GEN_BINOP(fprem)
1322
1323 GEN_UNOP(fabs)
1324 GEN_UNOP(fchs)
1325
1326 GEN_LOAD(fld)
1327 GEN_LOAD(fild)
1328 GEN_LOAD(fldz)
1329 GEN_LOAD(fld1)
1330
1331 GEN_STORE(fst)
1332 GEN_STORE(fist)
1333
1334 /**
1335 * Simulate a virtual fisttp.
1336 *
1337 * @param state  the x87 state
1338 * @param n      the node that should be simulated (and patched)
1339 */
1340 static int sim_fisttp(x87_state *state, ir_node *n) {
1341         x87_simulator         *sim = state->sim;
1342         ir_node               *val = get_irn_n(n, n_ia32_vfst_val);
1343         const arch_register_t *op2 = x87_get_irn_register(sim, val);
1344         unsigned              live = vfp_live_args_after(sim, n, 0);
1345         int                   insn = NO_NODE_ADDED;
1346         ia32_x87_attr_t *attr;
1347         int op2_reg_idx, op2_idx, depth;
1348         int live_after_node;
1349         ir_mode *mode;
1350
1351         op2_reg_idx = arch_register_get_index(op2);
1352         if (op2_reg_idx == REG_VFP_UKNWN) {
1353                 /* just take any value from stack */
1354                 if (state->depth > 0) {
1355                         op2_idx = 0;
1356                         DEBUG_ONLY(op2 = NULL);
1357                         live_after_node = 1;
1358                 } else {
1359                         /* produce a new value which we will consume immediately */
1360                         x87_create_fldz(state, n, op2_reg_idx);
1361                         live_after_node = 0;
1362                         op2_idx = x87_on_stack(state, op2_reg_idx);
1363                         assert(op2_idx >= 0);
1364                 }
1365         } else {
1366                 op2_idx = x87_on_stack(state, op2_reg_idx);
1367                 live_after_node = is_vfp_live(arch_register_get_index(op2), live);
1368                 DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1369                 assert(op2_idx >= 0);
1370         }
1371
1372         mode  = get_ia32_ls_mode(n);
1373         depth = x87_get_depth(state);
1374
1375         if (live_after_node) {
1376                 /* ffistp always pop the stack */
1377                 panic("vfisttp with live input detected, RA failed");
1378         } else {
1379                 /* we can only store the tos to memory */
1380                 if (op2_idx != 0)
1381                         x87_create_fxch(state, n, op2_idx);
1382
1383                 x87_pop(state);
1384                 x87_patch_insn(n, op_ia32_fisttp);
1385         }
1386
1387         attr = get_ia32_x87_attr(n);
1388         attr->x87[1] = op2 = &ia32_st_regs[0];
1389         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(op2)));
1390
1391         return insn;
1392 }  /* sim_fisttp */
1393
1394 static int sim_FtstFnstsw(x87_state *state, ir_node *n) {
1395         x87_simulator         *sim         = state->sim;
1396         ia32_x87_attr_t       *attr        = get_ia32_x87_attr(n);
1397         ir_node               *op1_node    = get_irn_n(n, n_ia32_vFtstFnstsw_left);
1398         const arch_register_t *reg1        = x87_get_irn_register(sim, op1_node);
1399         int                    reg_index_1 = arch_register_get_index(reg1);
1400         int                    op1_idx     = x87_on_stack(state, reg_index_1);
1401         unsigned               live        = vfp_live_args_after(sim, n, 0);
1402
1403         DB((dbg, LEVEL_1, ">>> %+F %s\n", n, arch_register_get_name(reg1)));
1404         DEBUG_ONLY(vfp_dump_live(live));
1405         DB((dbg, LEVEL_1, "Stack before: "));
1406         DEBUG_ONLY(x87_dump_stack(state));
1407         assert(op1_idx >= 0);
1408
1409         if (op1_idx != 0) {
1410                 /* bring the value to tos */
1411                 x87_create_fxch(state, n, op1_idx);
1412                 op1_idx = 0;
1413         }
1414
1415         /* patch the operation */
1416         x87_patch_insn(n, op_ia32_FtstFnstsw);
1417         reg1 = &ia32_st_regs[op1_idx];
1418         attr->x87[0] = reg1;
1419         attr->x87[1] = NULL;
1420         attr->x87[2] = NULL;
1421
1422         if(!is_vfp_live(reg_index_1, live)) {
1423                 x87_create_fpop(state, sched_next(n), 1);
1424                 return NODE_ADDED;
1425         }
1426
1427         return NO_NODE_ADDED;
1428 }
1429
1430 /**
1431  * @param state  the x87 state
1432  * @param n      the node that should be simulated (and patched)
1433  */
1434 static int sim_Fucom(x87_state *state, ir_node *n) {
1435         int op1_idx;
1436         int op2_idx = -1;
1437         ia32_x87_attr_t *attr = get_ia32_x87_attr(n);
1438         ir_op *dst;
1439         x87_simulator         *sim = state->sim;
1440         ir_node               *op1_node = get_irn_n(n, n_ia32_vFucomFnstsw_left);
1441         ir_node               *op2_node = get_irn_n(n, n_ia32_vFucomFnstsw_right);
1442         const arch_register_t *op1      = x87_get_irn_register(sim, op1_node);
1443         const arch_register_t *op2      = x87_get_irn_register(sim, op2_node);
1444         int reg_index_1 = arch_register_get_index(op1);
1445         int reg_index_2 = arch_register_get_index(op2);
1446         unsigned live = vfp_live_args_after(sim, n, 0);
1447         int                    permuted = attr->attr.data.ins_permuted;
1448         int xchg = 0;
1449         int pops = 0;
1450         int node_added = NO_NODE_ADDED;
1451
1452         DB((dbg, LEVEL_1, ">>> %+F %s, %s\n", n,
1453                 arch_register_get_name(op1), arch_register_get_name(op2)));
1454         DEBUG_ONLY(vfp_dump_live(live));
1455         DB((dbg, LEVEL_1, "Stack before: "));
1456         DEBUG_ONLY(x87_dump_stack(state));
1457
1458         op1_idx = x87_on_stack(state, reg_index_1);
1459         assert(op1_idx >= 0);
1460
1461         /* BEWARE: check for comp a,a cases, they might happen */
1462         if (reg_index_2 != REG_VFP_NOREG) {
1463                 /* second operand is a vfp register */
1464                 op2_idx = x87_on_stack(state, reg_index_2);
1465                 assert(op2_idx >= 0);
1466
1467                 if (is_vfp_live(reg_index_2, live)) {
1468                         /* second operand is live */
1469
1470                         if (is_vfp_live(reg_index_1, live)) {
1471                                 /* both operands are live */
1472
1473                                 if (op1_idx == 0) {
1474                                         /* res = tos X op */
1475                                 } else if (op2_idx == 0) {
1476                                         /* res = op X tos */
1477                                         permuted = !permuted;
1478                                         xchg    = 1;
1479                                 } else {
1480                                         /* bring the first one to tos */
1481                                         x87_create_fxch(state, n, op1_idx);
1482                                         if (op2_idx == 0)
1483                                                 op2_idx = op1_idx;
1484                                         op1_idx = 0;
1485                                         /* res = tos X op */
1486                                 }
1487                         } else {
1488                                 /* second live, first operand is dead here, bring it to tos.
1489                                    This means further, op1_idx != op2_idx. */
1490                                 assert(op1_idx != op2_idx);
1491                                 if (op1_idx != 0) {
1492                                         x87_create_fxch(state, n, op1_idx);
1493                                         if (op2_idx == 0)
1494                                                 op2_idx = op1_idx;
1495                                         op1_idx = 0;
1496                                 }
1497                                 /* res = tos X op, pop */
1498                                 pops = 1;
1499                         }
1500                 } else {
1501                         /* second operand is dead */
1502                         if (is_vfp_live(reg_index_1, live)) {
1503                                 /* first operand is live: bring second to tos.
1504                                    This means further, op1_idx != op2_idx. */
1505                                 assert(op1_idx != op2_idx);
1506                                 if (op2_idx != 0) {
1507                                         x87_create_fxch(state, n, op2_idx);
1508                                         if (op1_idx == 0)
1509                                                 op1_idx = op2_idx;
1510                                         op2_idx = 0;
1511                                 }
1512                                 /* res = op X tos, pop */
1513                                 pops    = 1;
1514                                 permuted = !permuted;
1515                                 xchg    = 1;
1516                         } else {
1517                                 /* both operands are dead here, check first for identity. */
1518                                 if (op1_idx == op2_idx) {
1519                                         /* identically, one pop needed */
1520                                         if (op1_idx != 0) {
1521                                                 x87_create_fxch(state, n, op1_idx);
1522                                                 op1_idx = 0;
1523                                                 op2_idx = 0;
1524                                         }
1525                                         /* res = tos X op, pop */
1526                                         pops    = 1;
1527                                 }
1528                                 /* different, move them to st and st(1) and pop both.
1529                                    The tricky part is to get one into st(1).*/
1530                                 else if (op2_idx == 1) {
1531                                         /* good, second operand is already in the right place, move the first */
1532                                         if (op1_idx != 0) {
1533                                                 /* bring the first on top */
1534                                                 x87_create_fxch(state, n, op1_idx);
1535                                                 assert(op2_idx != 0);
1536                                                 op1_idx = 0;
1537                                         }
1538                                         /* res = tos X op, pop, pop */
1539                                         pops = 2;
1540                                 } else if (op1_idx == 1) {
1541                                         /* good, first operand is already in the right place, move the second */
1542                                         if (op2_idx != 0) {
1543                                                 /* bring the first on top */
1544                                                 x87_create_fxch(state, n, op2_idx);
1545                                                 assert(op1_idx != 0);
1546                                                 op2_idx = 0;
1547                                         }
1548                                         /* res = op X tos, pop, pop */
1549                                         permuted = !permuted;
1550                                         xchg    = 1;
1551                                         pops    = 2;
1552                                 } else {
1553                                         /* if one is already the TOS, we need two fxch */
1554                                         if (op1_idx == 0) {
1555                                                 /* first one is TOS, move to st(1) */
1556                                                 x87_create_fxch(state, n, 1);
1557                                                 assert(op2_idx != 1);
1558                                                 op1_idx = 1;
1559                                                 x87_create_fxch(state, n, op2_idx);
1560                                                 op2_idx = 0;
1561                                                 /* res = op X tos, pop, pop */
1562                                                 pops    = 2;
1563                                                 permuted = !permuted;
1564                                                 xchg    = 1;
1565                                         } else if (op2_idx == 0) {
1566                                                 /* second one is TOS, move to st(1) */
1567                                                 x87_create_fxch(state, n, 1);
1568                                                 assert(op1_idx != 1);
1569                                                 op2_idx = 1;
1570                                                 x87_create_fxch(state, n, op1_idx);
1571                                                 op1_idx = 0;
1572                                                 /* res = tos X op, pop, pop */
1573                                                 pops    = 2;
1574                                         } else {
1575                                                 /* none of them is either TOS or st(1), 3 fxch needed */
1576                                                 x87_create_fxch(state, n, op2_idx);
1577                                                 assert(op1_idx != 0);
1578                                                 x87_create_fxch(state, n, 1);
1579                                                 op2_idx = 1;
1580                                                 x87_create_fxch(state, n, op1_idx);
1581                                                 op1_idx = 0;
1582                                                 /* res = tos X op, pop, pop */
1583                                                 pops    = 2;
1584                                         }
1585                                 }
1586                         }
1587                 }
1588         } else {
1589                 /* second operand is an address mode */
1590                 if (is_vfp_live(reg_index_1, live)) {
1591                         /* first operand is live: bring it to TOS */
1592                         if (op1_idx != 0) {
1593                                 x87_create_fxch(state, n, op1_idx);
1594                                 op1_idx = 0;
1595                         }
1596                 } else {
1597                         /* first operand is dead: bring it to tos */
1598                         if (op1_idx != 0) {
1599                                 x87_create_fxch(state, n, op1_idx);
1600                                 op1_idx = 0;
1601                         }
1602                         pops = 1;
1603                 }
1604         }
1605
1606         /* patch the operation */
1607         if (is_ia32_vFucomFnstsw(n)) {
1608                 int i;
1609
1610                 switch(pops) {
1611                 case 0: dst = op_ia32_FucomFnstsw; break;
1612                 case 1: dst = op_ia32_FucompFnstsw; break;
1613                 case 2: dst = op_ia32_FucomppFnstsw; break;
1614                 default: panic("invalid popcount in sim_Fucom");
1615                 }
1616
1617                 for(i = 0; i < pops; ++i) {
1618                         x87_pop(state);
1619                 }
1620         } else if(is_ia32_vFucomi(n)) {
1621                 switch(pops) {
1622                 case 0: dst = op_ia32_Fucomi; break;
1623                 case 1: dst = op_ia32_Fucompi; x87_pop(state); break;
1624                 case 2:
1625                         dst = op_ia32_Fucompi;
1626                         x87_pop(state);
1627                         x87_create_fpop(state, sched_next(n), 1);
1628                         node_added = NODE_ADDED;
1629                         break;
1630                 default: panic("invalid popcount in sim_Fucom");
1631                 }
1632         } else {
1633                 panic("invalid operation %+F in sim_FucomFnstsw", n);
1634         }
1635
1636         x87_patch_insn(n, dst);
1637         if(xchg) {
1638                 int tmp = op1_idx;
1639                 op1_idx = op2_idx;
1640                 op2_idx = tmp;
1641         }
1642
1643         op1 = &ia32_st_regs[op1_idx];
1644         attr->x87[0] = op1;
1645         if (op2_idx >= 0) {
1646                 op2 = &ia32_st_regs[op2_idx];
1647                 attr->x87[1] = op2;
1648         }
1649         attr->x87[2] = NULL;
1650         attr->attr.data.ins_permuted = permuted;
1651
1652         if (op2_idx >= 0) {
1653                 DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(n),
1654                         arch_register_get_name(op1), arch_register_get_name(op2)));
1655         } else {
1656                 DB((dbg, LEVEL_1, "<<< %s %s, [AM]\n", get_irn_opname(n),
1657                         arch_register_get_name(op1)));
1658         }
1659
1660         return node_added;
1661 }
1662
1663 static int sim_Keep(x87_state *state, ir_node *node)
1664 {
1665         const ir_node         *op;
1666         const arch_register_t *op_reg;
1667         int                    reg_id;
1668         int                    op_stack_idx;
1669         unsigned               live;
1670         int                    i, arity;
1671         int                    node_added = NO_NODE_ADDED;
1672
1673         DB((dbg, LEVEL_1, ">>> %+F\n", node));
1674
1675         arity = get_irn_arity(node);
1676         for(i = 0; i < arity; ++i) {
1677                 op      = get_irn_n(node, i);
1678                 op_reg  = arch_get_irn_register(state->sim->arch_env, op);
1679                 if(arch_register_get_class(op_reg) != &ia32_reg_classes[CLASS_ia32_vfp])
1680                         continue;
1681
1682                 reg_id = arch_register_get_index(op_reg);
1683                 live   = vfp_live_args_after(state->sim, node, 0);
1684
1685                 op_stack_idx = x87_on_stack(state, reg_id);
1686                 if(op_stack_idx >= 0 && !is_vfp_live(reg_id, live)) {
1687                         x87_create_fpop(state, sched_next(node), 1);
1688                         node_added = NODE_ADDED;
1689                 }
1690         }
1691
1692         DB((dbg, LEVEL_1, "Stack after: "));
1693         DEBUG_ONLY(x87_dump_stack(state));
1694
1695         return node_added;
1696 }
1697
1698 static
1699 void keep_float_node_alive(x87_state *state, ir_node *node)
1700 {
1701         ir_graph                    *irg;
1702         ir_node                     *block;
1703         ir_node                     *in[1];
1704         ir_node                     *keep;
1705         const arch_register_class_t *cls;
1706
1707         irg    = get_irn_irg(node);
1708         block  = get_nodes_block(node);
1709         cls    = arch_get_irn_reg_class(state->sim->arch_env, node, -1);
1710         in[0]  = node;
1711         keep   = be_new_Keep(cls, irg, block, 1, in);
1712
1713         assert(sched_is_scheduled(node));
1714         sched_add_after(node, keep);
1715 }
1716
1717 /**
1718  * Create a copy of a node. Recreate the node if it's a constant.
1719  *
1720  * @param state  the x87 state
1721  * @param n      the node to be copied
1722  *
1723  * @return the copy of n
1724  */
1725 static ir_node *create_Copy(x87_state *state, ir_node *n) {
1726         x87_simulator *sim = state->sim;
1727         ir_graph *irg = get_irn_irg(n);
1728         dbg_info *n_dbg = get_irn_dbg_info(n);
1729         ir_mode *mode = get_irn_mode(n);
1730         ir_node *block = get_nodes_block(n);
1731         ir_node *pred = get_irn_n(n, 0);
1732         ir_node *(*cnstr)(dbg_info *, ir_graph *, ir_node *, ir_mode *) = NULL;
1733         ir_node *res;
1734         const arch_register_t *out;
1735         const arch_register_t *op1;
1736         ia32_x87_attr_t *attr;
1737
1738         /* Do not copy constants, recreate them. */
1739         switch (get_ia32_irn_opcode(pred)) {
1740         case iro_ia32_Unknown_VFP:
1741         case iro_ia32_fldz:
1742                 cnstr = new_rd_ia32_fldz;
1743                 break;
1744         case iro_ia32_fld1:
1745                 cnstr = new_rd_ia32_fld1;
1746                 break;
1747         case iro_ia32_fldpi:
1748                 cnstr = new_rd_ia32_fldpi;
1749                 break;
1750         case iro_ia32_fldl2e:
1751                 cnstr = new_rd_ia32_fldl2e;
1752                 break;
1753         case iro_ia32_fldl2t:
1754                 cnstr = new_rd_ia32_fldl2t;
1755                 break;
1756         case iro_ia32_fldlg2:
1757                 cnstr = new_rd_ia32_fldlg2;
1758                 break;
1759         case iro_ia32_fldln2:
1760                 cnstr = new_rd_ia32_fldln2;
1761                 break;
1762         default:
1763                 break;
1764         }
1765
1766         out = x87_get_irn_register(sim, n);
1767         op1 = x87_get_irn_register(sim, pred);
1768
1769         if (cnstr != NULL) {
1770                 /* copy a constant */
1771                 res = (*cnstr)(n_dbg, irg, block, mode);
1772
1773                 x87_push(state, arch_register_get_index(out), res);
1774
1775                 attr = get_ia32_x87_attr(res);
1776                 attr->x87[2] = &ia32_st_regs[0];
1777         } else {
1778                 int op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1779
1780                 res = new_rd_ia32_fpushCopy(n_dbg, irg, block, pred, mode);
1781
1782                 x87_push(state, arch_register_get_index(out), res);
1783
1784                 attr = get_ia32_x87_attr(res);
1785                 attr->x87[0] = &ia32_st_regs[op1_idx];
1786                 attr->x87[2] = &ia32_st_regs[0];
1787         }
1788         arch_set_irn_register(sim->arch_env, res, out);
1789
1790         return res;
1791 }  /* create_Copy */
1792
1793 /**
1794  * Simulate a be_Copy.
1795  *
1796  * @param state  the x87 state
1797  * @param n      the node that should be simulated (and patched)
1798  *
1799  * @return NO_NODE_ADDED
1800  */
1801 static int sim_Copy(x87_state *state, ir_node *n) {
1802         x87_simulator               *sim = state->sim;
1803         ir_node                     *pred;
1804         const arch_register_t       *out;
1805         const arch_register_t       *op1;
1806         const arch_register_class_t *class;
1807         ir_node                     *node, *next;
1808         ia32_x87_attr_t             *attr;
1809         int                         op1_idx, out_idx;
1810         unsigned                    live;
1811
1812         class = arch_get_irn_reg_class(sim->arch_env, n, -1);
1813         if (class->regs != ia32_vfp_regs)
1814                 return 0;
1815
1816         pred = get_irn_n(n, 0);
1817         out  = x87_get_irn_register(sim, n);
1818         op1  = x87_get_irn_register(sim, pred);
1819         live = vfp_live_args_after(sim, n, REGMASK(out));
1820
1821         DB((dbg, LEVEL_1, ">>> %+F %s -> %s\n", n,
1822                 arch_register_get_name(op1), arch_register_get_name(out)));
1823         DEBUG_ONLY(vfp_dump_live(live));
1824
1825         /* handle the infamous unknown value */
1826         if (arch_register_get_index(op1) == REG_VFP_UKNWN) {
1827                 /* Operand is still live, a real copy. We need here an fpush that can
1828                    hold a a register, so use the fpushCopy or recreate constants */
1829                 node = create_Copy(state, n);
1830
1831                 assert(is_ia32_fldz(node));
1832                 next = sched_next(n);
1833                 sched_remove(n);
1834                 exchange(n, node);
1835                 sched_add_before(next, node);
1836
1837                 DB((dbg, LEVEL_1, "<<< %+F %s -> %s\n", node, op1->name,
1838                     arch_get_irn_register(sim->arch_env, node)->name));
1839                 return NO_NODE_ADDED;
1840         }
1841
1842         op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1843
1844         if (is_vfp_live(arch_register_get_index(op1), live)) {
1845                 ir_node *pred = get_irn_n(n, 0);
1846
1847                 /* Operand is still live, a real copy. We need here an fpush that can
1848                    hold a a register, so use the fpushCopy or recreate constants */
1849                 node = create_Copy(state, n);
1850
1851                 /* We have to make sure the old value doesn't go dead (which can happen
1852                  * when we recreate constants). As the simulator expected that value in
1853                  * the pred blocks. This is unfortunate as removing it would save us 1
1854                  * instruction, but we would have to rerun all the simulation to get
1855                  * this correct...
1856                  */
1857                 next = sched_next(n);
1858                 sched_remove(n);
1859                 exchange(n, node);
1860                 sched_add_before(next, node);
1861
1862                 if(get_irn_n_edges(pred) == 0) {
1863                         keep_float_node_alive(state, pred);
1864                 }
1865
1866                 DB((dbg, LEVEL_1, "<<< %+F %s -> ?\n", node, op1->name));
1867         } else {
1868                 out_idx = x87_on_stack(state, arch_register_get_index(out));
1869
1870                 if (out_idx >= 0 && out_idx != op1_idx) {
1871                         /* Matze: out already on stack? how can this happen? */
1872                         assert(0);
1873
1874                         /* op1 must be killed and placed where out is */
1875                         if (out_idx == 0) {
1876                                 /* best case, simple remove and rename */
1877                                 x87_patch_insn(n, op_ia32_Pop);
1878                                 attr = get_ia32_x87_attr(n);
1879                                 attr->x87[0] = op1 = &ia32_st_regs[0];
1880
1881                                 x87_pop(state);
1882                                 x87_set_st(state, arch_register_get_index(out), n, op1_idx - 1);
1883                         } else {
1884                                 /* move op1 to tos, store and pop it */
1885                                 if (op1_idx != 0) {
1886                                         x87_create_fxch(state, n, op1_idx);
1887                                         op1_idx = 0;
1888                                 }
1889                                 x87_patch_insn(n, op_ia32_Pop);
1890                                 attr = get_ia32_x87_attr(n);
1891                                 attr->x87[0] = op1 = &ia32_st_regs[out_idx];
1892
1893                                 x87_pop(state);
1894                                 x87_set_st(state, arch_register_get_index(out), n, out_idx - 1);
1895                         }
1896                         DB((dbg, LEVEL_1, "<<< %+F %s\n", n, op1->name));
1897                 } else {
1898                         /* just a virtual copy */
1899                         x87_set_st(state, arch_register_get_index(out), get_unop_op(n), op1_idx);
1900                         /* don't remove the node to keep the verifier quiet :),
1901                            the emitter won't emit any code for the node */
1902 #if 0
1903                         sched_remove(n);
1904                         DB((dbg, LEVEL_1, "<<< KILLED %s\n", get_irn_opname(n)));
1905                         exchange(n, get_unop_op(n));
1906 #endif
1907                 }
1908         }
1909         return NO_NODE_ADDED;
1910 }  /* sim_Copy */
1911
1912 /**
1913  * Returns the result proj of the call
1914  */
1915 static ir_node *get_call_result_proj(ir_node *call) {
1916         const ir_edge_t *edge;
1917
1918         /* search the result proj */
1919         foreach_out_edge(call, edge) {
1920                 ir_node *proj = get_edge_src_irn(edge);
1921                 long pn = get_Proj_proj(proj);
1922
1923                 if (pn == pn_be_Call_first_res) {
1924                         return proj;
1925                 }
1926         }
1927
1928         return NULL;
1929 }  /* get_call_result_proj */
1930
1931 /**
1932  * Simulate a be_Call.
1933  *
1934  * @param state      the x87 state
1935  * @param n          the node that should be simulated
1936  *
1937  * @return NO_NODE_ADDED
1938  */
1939 static int sim_Call(x87_state *state, ir_node *n)
1940 {
1941         ir_type *call_tp = be_Call_get_type(n);
1942         ir_type *res_type;
1943         ir_mode *mode;
1944         ir_node *resproj;
1945         const arch_register_t *reg;
1946
1947         DB((dbg, LEVEL_1, ">>> %+F\n", n));
1948
1949         /* at the begin of a call the x87 state should be empty */
1950         assert(state->depth == 0 && "stack not empty before call");
1951
1952         if (get_method_n_ress(call_tp) <= 0)
1953                 goto end_call;
1954
1955         /*
1956          * If the called function returns a float, it is returned in st(0).
1957          * This even happens if the return value is NOT used.
1958          * Moreover, only one return result is supported.
1959          */
1960         res_type = get_method_res_type(call_tp, 0);
1961         mode     = get_type_mode(res_type);
1962
1963         if (mode == NULL || !mode_is_float(mode))
1964                 goto end_call;
1965
1966         resproj = get_call_result_proj(n);
1967         assert(resproj != NULL);
1968
1969         reg = x87_get_irn_register(state->sim, resproj);
1970         x87_push(state, arch_register_get_index(reg), resproj);
1971
1972 end_call:
1973         DB((dbg, LEVEL_1, "Stack after: "));
1974         DEBUG_ONLY(x87_dump_stack(state));
1975
1976         return NO_NODE_ADDED;
1977 }  /* sim_Call */
1978
1979 /**
1980  * Simulate a be_Spill.
1981  *
1982  * @param state  the x87 state
1983  * @param n      the node that should be simulated (and patched)
1984  *
1985  * Should not happen, spills are lowered before x87 simulator see them.
1986  */
1987 static int sim_Spill(x87_state *state, ir_node *n) {
1988         assert(0 && "Spill not lowered");
1989         return sim_fst(state, n);
1990 }  /* sim_Spill */
1991
1992 /**
1993  * Simulate a be_Reload.
1994  *
1995  * @param state  the x87 state
1996  * @param n      the node that should be simulated (and patched)
1997  *
1998  * Should not happen, reloads are lowered before x87 simulator see them.
1999  */
2000 static int sim_Reload(x87_state *state, ir_node *n) {
2001         assert(0 && "Reload not lowered");
2002         return sim_fld(state, n);
2003 }  /* sim_Reload */
2004
2005 /**
2006  * Simulate a be_Return.
2007  *
2008  * @param state  the x87 state
2009  * @param n      the node that should be simulated (and patched)
2010  *
2011  * @return NO_NODE_ADDED
2012  */
2013 static int sim_Return(x87_state *state, ir_node *n) {
2014         int n_res = be_Return_get_n_rets(n);
2015         int i, n_float_res = 0;
2016
2017         /* only floating point return values must resist on stack */
2018         for (i = 0; i < n_res; ++i) {
2019                 ir_node *res = get_irn_n(n, be_pos_Return_val + i);
2020
2021                 if (mode_is_float(get_irn_mode(res)))
2022                         ++n_float_res;
2023         }
2024         assert(x87_get_depth(state) == n_float_res);
2025
2026         /* pop them virtually */
2027         for (i = n_float_res - 1; i >= 0; --i)
2028                 x87_pop(state);
2029
2030         return NO_NODE_ADDED;
2031 }  /* sim_Return */
2032
2033 typedef struct _perm_data_t {
2034         const arch_register_t *in;
2035         const arch_register_t *out;
2036 } perm_data_t;
2037
2038 /**
2039  * Simulate a be_Perm.
2040  *
2041  * @param state  the x87 state
2042  * @param irn    the node that should be simulated (and patched)
2043  *
2044  * @return NO_NODE_ADDED
2045  */
2046 static int sim_Perm(x87_state *state, ir_node *irn) {
2047         int             i, n;
2048         x87_simulator   *sim = state->sim;
2049         ir_node         *pred = get_irn_n(irn, 0);
2050         int             *stack_pos;
2051         const ir_edge_t *edge;
2052
2053         /* handle only floating point Perms */
2054         if (! mode_is_float(get_irn_mode(pred)))
2055                 return NO_NODE_ADDED;
2056
2057         DB((dbg, LEVEL_1, ">>> %+F\n", irn));
2058
2059         /* Perm is a pure virtual instruction on x87.
2060            All inputs must be on the FPU stack and are pairwise
2061            different from each other.
2062            So, all we need to do is to permutate the stack state. */
2063         n = get_irn_arity(irn);
2064         NEW_ARR_A(int, stack_pos, n);
2065
2066         /* collect old stack positions */
2067         for (i = 0; i < n; ++i) {
2068                 const arch_register_t *inreg = x87_get_irn_register(sim, get_irn_n(irn, i));
2069                 int idx = x87_on_stack(state, arch_register_get_index(inreg));
2070
2071                 assert(idx >= 0 && "Perm argument not on x87 stack");
2072
2073                 stack_pos[i] = idx;
2074         }
2075         /* now do the permutation */
2076         foreach_out_edge(irn, edge) {
2077                 ir_node               *proj = get_edge_src_irn(edge);
2078                 const arch_register_t *out  = x87_get_irn_register(sim, proj);
2079                 long                  num   = get_Proj_proj(proj);
2080
2081                 assert(0 <= num && num < n && "More Proj's than Perm inputs");
2082                 x87_set_st(state, arch_register_get_index(out), proj, stack_pos[(unsigned)num]);
2083         }
2084         DB((dbg, LEVEL_1, "<<< %+F\n", irn));
2085
2086         return NO_NODE_ADDED;
2087 }  /* sim_Perm */
2088
2089 static int sim_Barrier(x87_state *state, ir_node *node) {
2090         //const arch_env_t *arch_env = state->sim->arch_env;
2091         int i, arity;
2092
2093         /* materialize unknown if needed */
2094         arity = get_irn_arity(node);
2095         for(i = 0; i < arity; ++i) {
2096                 const arch_register_t       *reg;
2097                 ir_node                     *zero;
2098                 ir_node                     *block;
2099                 ia32_x87_attr_t             *attr;
2100                 ir_node                     *in    = get_irn_n(node, i);
2101
2102                 if(!is_ia32_Unknown_VFP(in))
2103                         continue;
2104
2105                 /* TODO: not completely correct... */
2106                 reg = &ia32_vfp_regs[REG_VFP_UKNWN];
2107
2108                 /* create a zero */
2109                 block = get_nodes_block(node);
2110                 zero  = new_rd_ia32_fldz(NULL, current_ir_graph, block, mode_E);
2111                 x87_push(state, arch_register_get_index(reg), zero);
2112
2113                 attr = get_ia32_x87_attr(zero);
2114                 attr->x87[2] = &ia32_st_regs[0];
2115
2116                 sched_add_before(node, zero);
2117
2118                 set_irn_n(node, i, zero);
2119         }
2120
2121         return NO_NODE_ADDED;
2122 }
2123
2124
2125 /**
2126  * Kill any dead registers at block start by popping them from the stack.
2127  *
2128  * @param sim          the simulator handle
2129  * @param block        the current block
2130  * @param start_state  the x87 state at the begin of the block
2131  *
2132  * @return the x87 state after dead register killed
2133  */
2134 static x87_state *x87_kill_deads(x87_simulator *sim, ir_node *block, x87_state *start_state) {
2135         x87_state *state = start_state;
2136         ir_node *first_insn = sched_first(block);
2137         ir_node *keep = NULL;
2138         unsigned live = vfp_live_args_after(sim, block, 0);
2139         unsigned kill_mask;
2140         int i, depth, num_pop;
2141
2142         kill_mask = 0;
2143         depth = x87_get_depth(state);
2144         for (i = depth - 1; i >= 0; --i) {
2145                 int reg = x87_get_st_reg(state, i);
2146
2147                 if (! is_vfp_live(reg, live))
2148                         kill_mask |= (1 << i);
2149         }
2150
2151         if (kill_mask) {
2152                 /* create a new state, will be changed */
2153                 state = x87_clone_state(sim, state);
2154
2155                 DB((dbg, LEVEL_1, "Killing deads:\n"));
2156                 DEBUG_ONLY(vfp_dump_live(live));
2157                 DEBUG_ONLY(x87_dump_stack(state));
2158
2159                 if (kill_mask != 0 && live == 0) {
2160                         /* special case: kill all registers */
2161                         if (ia32_cg_config.use_femms || ia32_cg_config.use_emms) {
2162                                 if (ia32_cg_config.use_femms) {
2163                                         /* use FEMMS on AMD processors to clear all */
2164                                         keep = new_rd_ia32_femms(NULL, get_irn_irg(block), block);
2165                                 } else {
2166                                         /* use EMMS to clear all */
2167                                         keep = new_rd_ia32_emms(NULL, get_irn_irg(block), block);
2168                                 }
2169                                 sched_add_before(first_insn, keep);
2170                                 keep_alive(keep);
2171                                 x87_emms(state);
2172                                 return state;
2173                         }
2174                 }
2175                 /* now kill registers */
2176                 while (kill_mask) {
2177                         /* we can only kill from TOS, so bring them up */
2178                         if (! (kill_mask & 1)) {
2179                                 /* search from behind, because we can to a double-pop */
2180                                 for (i = depth - 1; i >= 0; --i) {
2181                                         if (kill_mask & (1 << i)) {
2182                                                 kill_mask &= ~(1 << i);
2183                                                 kill_mask |= 1;
2184                                                 break;
2185                                         }
2186                                 }
2187
2188                                 if (keep)
2189                                         x87_set_st(state, -1, keep, i);
2190                                 x87_create_fxch(state, first_insn, i);
2191                         }
2192
2193                         if ((kill_mask & 3) == 3) {
2194                                 /* we can do a double-pop */
2195                                 num_pop = 2;
2196                         }
2197                         else {
2198                                 /* only a single pop */
2199                                 num_pop = 1;
2200                         }
2201
2202                         depth -= num_pop;
2203                         kill_mask >>= num_pop;
2204                         keep = x87_create_fpop(state, first_insn, num_pop);
2205                 }
2206                 keep_alive(keep);
2207         }
2208         return state;
2209 }  /* x87_kill_deads */
2210
2211 /**
2212  * If we have PhiEs with unknown operands then we have to make sure that some
2213  * value is actually put onto the stack.
2214  */
2215 static void fix_unknown_phis(x87_state *state, ir_node *block,
2216                              ir_node *pred_block, int pos)
2217 {
2218         ir_node *node, *op;
2219
2220         sched_foreach(block, node) {
2221                 ir_node               *zero;
2222                 const arch_register_t *reg;
2223                 ia32_x87_attr_t       *attr;
2224
2225                 if(!is_Phi(node))
2226                         break;
2227
2228                 op = get_Phi_pred(node, pos);
2229                 if(!is_ia32_Unknown_VFP(op))
2230                         continue;
2231
2232                 reg = arch_get_irn_register(state->sim->arch_env, node);
2233
2234                 /* create a zero at end of pred block */
2235                 zero = new_rd_ia32_fldz(NULL, current_ir_graph, pred_block, mode_E);
2236                 x87_push(state, arch_register_get_index(reg), zero);
2237
2238                 attr = get_ia32_x87_attr(zero);
2239                 attr->x87[2] = &ia32_st_regs[0];
2240
2241                 assert(is_ia32_fldz(zero));
2242                 sched_add_before(sched_last(pred_block), zero);
2243
2244                 set_Phi_pred(node, pos, zero);
2245         }
2246 }
2247
2248 /**
2249  * Run a simulation and fix all virtual instructions for a block.
2250  *
2251  * @param sim          the simulator handle
2252  * @param block        the current block
2253  */
2254 static void x87_simulate_block(x87_simulator *sim, ir_node *block) {
2255         ir_node *n, *next;
2256         blk_state *bl_state = x87_get_bl_state(sim, block);
2257         x87_state *state = bl_state->begin;
2258         const ir_edge_t *edge;
2259         ir_node *start_block;
2260
2261         assert(state != NULL);
2262         /* already processed? */
2263         if (bl_state->end != NULL)
2264                 return;
2265
2266         DB((dbg, LEVEL_1, "Simulate %+F\n", block));
2267         DB((dbg, LEVEL_2, "State at Block begin:\n "));
2268         DEBUG_ONLY(x87_dump_stack(state));
2269
2270         /* at block begin, kill all dead registers */
2271         state = x87_kill_deads(sim, block, state);
2272         /* create a new state, will be changed */
2273         state = x87_clone_state(sim, state);
2274
2275         /* beware, n might change */
2276         for (n = sched_first(block); !sched_is_end(n); n = next) {
2277                 int node_inserted;
2278                 sim_func func;
2279                 ir_op *op = get_irn_op(n);
2280
2281                 next = sched_next(n);
2282                 if (op->ops.generic == NULL)
2283                         continue;
2284
2285                 func = (sim_func)op->ops.generic;
2286
2287                 /* simulate it */
2288                 node_inserted = (*func)(state, n);
2289
2290                 /*
2291                         sim_func might have added an additional node after n,
2292                         so update next node
2293                         beware: n must not be changed by sim_func
2294                         (i.e. removed from schedule) in this case
2295                 */
2296                 if (node_inserted != NO_NODE_ADDED)
2297                         next = sched_next(n);
2298         }
2299
2300         start_block = get_irg_start_block(get_irn_irg(block));
2301
2302         DB((dbg, LEVEL_2, "State at Block end:\n ")); DEBUG_ONLY(x87_dump_stack(state));
2303
2304         /* check if the state must be shuffled */
2305         foreach_block_succ(block, edge) {
2306                 ir_node *succ = get_edge_src_irn(edge);
2307                 blk_state *succ_state;
2308
2309                 if (succ == start_block)
2310                         continue;
2311
2312                 succ_state = x87_get_bl_state(sim, succ);
2313
2314                 fix_unknown_phis(state, succ, block, get_edge_src_pos(edge));
2315
2316                 if (succ_state->begin == NULL) {
2317                         DB((dbg, LEVEL_2, "Set begin state for succ %+F:\n", succ));
2318                         DEBUG_ONLY(x87_dump_stack(state));
2319                         succ_state->begin = state;
2320
2321                         waitq_put(sim->worklist, succ);
2322                 } else {
2323                         DB((dbg, LEVEL_2, "succ %+F already has a state, shuffling\n", succ));
2324                         /* There is already a begin state for the successor, bad.
2325                            Do the necessary permutations.
2326                            Note that critical edges are removed, so this is always possible:
2327                            If the successor has more than one possible input, then it must
2328                            be the only one.
2329                          */
2330                         x87_shuffle(sim, block, state, succ, succ_state->begin);
2331                 }
2332         }
2333         bl_state->end = state;
2334 }  /* x87_simulate_block */
2335
2336 static void register_sim(ir_op *op, sim_func func)
2337 {
2338         assert(op->ops.generic == NULL);
2339         op->ops.generic = (op_func) func;
2340 }
2341
2342 /**
2343  * Create a new x87 simulator.
2344  *
2345  * @param sim       a simulator handle, will be initialized
2346  * @param irg       the current graph
2347  * @param arch_env  the architecture environment
2348  */
2349 static void x87_init_simulator(x87_simulator *sim, ir_graph *irg,
2350                                const arch_env_t *arch_env)
2351 {
2352         obstack_init(&sim->obst);
2353         sim->blk_states = pmap_create();
2354         sim->arch_env   = arch_env;
2355         sim->n_idx      = get_irg_last_idx(irg);
2356         sim->live       = obstack_alloc(&sim->obst, sizeof(*sim->live) * sim->n_idx);
2357         sim->isa        = (ia32_isa_t *)arch_env->isa;
2358
2359         DB((dbg, LEVEL_1, "--------------------------------\n"
2360                 "x87 Simulator started for %+F\n", irg));
2361
2362         /* set the generic function pointer of instruction we must simulate */
2363         clear_irp_opcodes_generic_func();
2364
2365         register_sim(op_ia32_vfld,         sim_fld);
2366         register_sim(op_ia32_vfild,        sim_fild);
2367         register_sim(op_ia32_vfld1,        sim_fld1);
2368         register_sim(op_ia32_vfldz,        sim_fldz);
2369         register_sim(op_ia32_vfadd,        sim_fadd);
2370         register_sim(op_ia32_vfsub,        sim_fsub);
2371         register_sim(op_ia32_vfmul,        sim_fmul);
2372         register_sim(op_ia32_vfdiv,        sim_fdiv);
2373         register_sim(op_ia32_vfprem,       sim_fprem);
2374         register_sim(op_ia32_vfabs,        sim_fabs);
2375         register_sim(op_ia32_vfchs,        sim_fchs);
2376         register_sim(op_ia32_vfist,        sim_fist);
2377         register_sim(op_ia32_vfisttp,      sim_fisttp);
2378         register_sim(op_ia32_vfst,         sim_fst);
2379         register_sim(op_ia32_vFtstFnstsw,  sim_FtstFnstsw);
2380         register_sim(op_ia32_vFucomFnstsw, sim_Fucom);
2381         register_sim(op_ia32_vFucomi,      sim_Fucom);
2382         register_sim(op_be_Copy,           sim_Copy);
2383         register_sim(op_be_Call,           sim_Call);
2384         register_sim(op_be_Spill,          sim_Spill);
2385         register_sim(op_be_Reload,         sim_Reload);
2386         register_sim(op_be_Return,         sim_Return);
2387         register_sim(op_be_Perm,           sim_Perm);
2388         register_sim(op_be_Keep,           sim_Keep);
2389         register_sim(op_be_Barrier,        sim_Barrier);
2390 }  /* x87_init_simulator */
2391
2392 /**
2393  * Destroy a x87 simulator.
2394  *
2395  * @param sim  the simulator handle
2396  */
2397 static void x87_destroy_simulator(x87_simulator *sim) {
2398         pmap_destroy(sim->blk_states);
2399         obstack_free(&sim->obst, NULL);
2400         DB((dbg, LEVEL_1, "x87 Simulator stopped\n\n"));
2401 }  /* x87_destroy_simulator */
2402
2403 /**
2404  * Pre-block walker: calculate the liveness information for the block
2405  * and store it into the sim->live cache.
2406  */
2407 static void update_liveness_walker(ir_node *block, void *data) {
2408         x87_simulator *sim = data;
2409         update_liveness(sim, block);
2410 }  /* update_liveness_walker */
2411
2412 /**
2413  * Run a simulation and fix all virtual instructions for a graph.
2414  *
2415  * @param env       the architecture environment
2416  * @param irg       the current graph
2417  *
2418  * Needs a block-schedule.
2419  */
2420 void x87_simulate_graph(const arch_env_t *arch_env, be_irg_t *birg) {
2421         ir_node       *block, *start_block;
2422         blk_state     *bl_state;
2423         x87_simulator sim;
2424         ir_graph      *irg = be_get_birg_irg(birg);
2425
2426         /* create the simulator */
2427         x87_init_simulator(&sim, irg, arch_env);
2428
2429         start_block = get_irg_start_block(irg);
2430         bl_state    = x87_get_bl_state(&sim, start_block);
2431
2432         /* start with the empty state */
2433         bl_state->begin = empty;
2434         empty->sim      = &sim;
2435
2436         sim.worklist = new_waitq();
2437         waitq_put(sim.worklist, start_block);
2438
2439         be_assure_liveness(birg);
2440         sim.lv = be_get_birg_liveness(birg);
2441 //      sim.lv = be_liveness(be_get_birg_irg(birg));
2442         be_liveness_assure_sets(sim.lv);
2443
2444         /* Calculate the liveness for all nodes. We must precalculate this info,
2445          * because the simulator adds new nodes (possible before Phi nodes) which
2446          * would let a lazy calculation fail.
2447          * On the other hand we reduce the computation amount due to
2448          * precaching from O(n^2) to O(n) at the expense of O(n) cache memory.
2449          */
2450         irg_block_walk_graph(irg, update_liveness_walker, NULL, &sim);
2451
2452         /* iterate */
2453         do {
2454                 block = waitq_get(sim.worklist);
2455                 x87_simulate_block(&sim, block);
2456         } while (! waitq_empty(sim.worklist));
2457
2458         /* kill it */
2459         del_waitq(sim.worklist);
2460         x87_destroy_simulator(&sim);
2461 }  /* x87_simulate_graph */
2462
2463 void ia32_init_x87(void) {
2464         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.x87");
2465 }  /* ia32_init_x87 */