ac98c7d28438accd570e329d311331eacb1eaa88
[libfirm] / ir / be / ia32 / bearch_ia32.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 is the main ia32 firm backend driver.
23  * @author      Christian Wuerdig
24  */
25 #include "config.h"
26
27 #include "lc_opts.h"
28 #include "lc_opts_enum.h"
29
30 #include <math.h>
31
32 #include "irarch.h"
33 #include "irgwalk.h"
34 #include "irprog.h"
35 #include "irprintf.h"
36 #include "iredges_t.h"
37 #include "ircons.h"
38 #include "irflag.h"
39 #include "irgmod.h"
40 #include "irgopt.h"
41 #include "irbitset.h"
42 #include "irgopt.h"
43 #include "irdump.h"
44 #include "pdeq.h"
45 #include "pset.h"
46 #include "debug.h"
47 #include "error.h"
48 #include "xmalloc.h"
49 #include "irtools.h"
50 #include "iroptimize.h"
51 #include "instrument.h"
52 #include "iropt_t.h"
53 #include "lower_dw.h"
54 #include "lower_calls.h"
55 #include "lower_mode_b.h"
56 #include "lower_softfloat.h"
57
58 #include "beabi.h"
59 #include "beirg.h"
60 #include "benode.h"
61 #include "belower.h"
62 #include "besched.h"
63 #include "be.h"
64 #include "be_t.h"
65 #include "beirgmod.h"
66 #include "be_dbgout.h"
67 #include "beblocksched.h"
68 #include "bemachine.h"
69 #include "bespillutil.h"
70 #include "bespillslots.h"
71 #include "bemodule.h"
72 #include "begnuas.h"
73 #include "bestate.h"
74 #include "beflags.h"
75 #include "betranshlp.h"
76 #include "belistsched.h"
77 #include "beabihelper.h"
78 #include "bestack.h"
79
80 #include "bearch_ia32_t.h"
81
82 #include "ia32_new_nodes.h"
83 #include "gen_ia32_regalloc_if.h"
84 #include "gen_ia32_machine.h"
85 #include "ia32_common_transform.h"
86 #include "ia32_transform.h"
87 #include "ia32_emitter.h"
88 #include "ia32_optimize.h"
89 #include "ia32_x87.h"
90 #include "ia32_dbg_stat.h"
91 #include "ia32_finish.h"
92 #include "ia32_fpu.h"
93 #include "ia32_architecture.h"
94
95 #ifdef FIRM_GRGEN_BE
96 #include "ia32_pbqp_transform.h"
97
98 transformer_t be_transformer = TRANSFORMER_DEFAULT;
99 #endif
100
101 ir_mode *ia32_mode_fpcw;
102 ir_mode *ia32_mode_E;
103 ir_type *ia32_type_E;
104
105 /** The current omit-fp state */
106 static ir_type *omit_fp_between_type   = NULL;
107 static ir_type *between_type           = NULL;
108 static ir_entity *old_bp_ent           = NULL;
109 static ir_entity *ret_addr_ent         = NULL;
110 static ir_entity *omit_fp_ret_addr_ent = NULL;
111
112 /**
113  * The environment for the intrinsic mapping.
114  */
115 static ia32_intrinsic_env_t intrinsic_env = {
116         NULL,    /* the isa */
117         NULL,    /* the irg, these entities belong to */
118         NULL,    /* entity for __divdi3 library call */
119         NULL,    /* entity for __moddi3 library call */
120         NULL,    /* entity for __udivdi3 library call */
121         NULL,    /* entity for __umoddi3 library call */
122 };
123
124
125 typedef ir_node *(*create_const_node_func) (dbg_info *dbgi, ir_node *block);
126
127 /**
128  * Used to create per-graph unique pseudo nodes.
129  */
130 static inline ir_node *create_const(ir_graph *irg, ir_node **place,
131                                     create_const_node_func func,
132                                     const arch_register_t* reg)
133 {
134         ir_node *block, *res;
135
136         if (*place != NULL)
137                 return *place;
138
139         block = get_irg_start_block(irg);
140         res = func(NULL, block);
141         arch_set_irn_register(res, reg);
142         *place = res;
143
144         return res;
145 }
146
147 /* Creates the unique per irg GP NoReg node. */
148 ir_node *ia32_new_NoReg_gp(ir_graph *irg)
149 {
150         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
151         return create_const(irg, &irg_data->noreg_gp, new_bd_ia32_NoReg_GP,
152                             &ia32_registers[REG_GP_NOREG]);
153 }
154
155 ir_node *ia32_new_NoReg_vfp(ir_graph *irg)
156 {
157         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
158         return create_const(irg, &irg_data->noreg_vfp, new_bd_ia32_NoReg_VFP,
159                             &ia32_registers[REG_VFP_NOREG]);
160 }
161
162 ir_node *ia32_new_NoReg_xmm(ir_graph *irg)
163 {
164         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
165         return create_const(irg, &irg_data->noreg_xmm, new_bd_ia32_NoReg_XMM,
166                             &ia32_registers[REG_XMM_NOREG]);
167 }
168
169 ir_node *ia32_new_Fpu_truncate(ir_graph *irg)
170 {
171         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
172         return create_const(irg, &irg_data->fpu_trunc_mode, new_bd_ia32_ChangeCW,
173                         &ia32_registers[REG_FPCW]);
174 }
175
176
177 /**
178  * Returns the admissible noreg register node for input register pos of node irn.
179  */
180 static ir_node *ia32_get_admissible_noreg(ir_node *irn, int pos)
181 {
182         ir_graph                  *irg = get_irn_irg(irn);
183         const arch_register_req_t *req = arch_get_irn_register_req_in(irn, pos);
184
185         assert(req != NULL && "Missing register requirements");
186         if (req->cls == &ia32_reg_classes[CLASS_ia32_gp])
187                 return ia32_new_NoReg_gp(irg);
188
189         if (ia32_cg_config.use_sse2) {
190                 return ia32_new_NoReg_xmm(irg);
191         } else {
192                 return ia32_new_NoReg_vfp(irg);
193         }
194 }
195
196 static arch_irn_class_t ia32_classify(const ir_node *irn)
197 {
198         arch_irn_class_t classification = arch_irn_class_none;
199
200         assert(is_ia32_irn(irn));
201
202         if (is_ia32_is_reload(irn))
203                 classification |= arch_irn_class_reload;
204
205         if (is_ia32_is_spill(irn))
206                 classification |= arch_irn_class_spill;
207
208         if (is_ia32_is_remat(irn))
209                 classification |= arch_irn_class_remat;
210
211         return classification;
212 }
213
214 /**
215  * The IA32 ABI callback object.
216  */
217 typedef struct {
218         be_abi_call_flags_bits_t flags;  /**< The call flags. */
219         ir_graph *irg;                   /**< The associated graph. */
220 } ia32_abi_env_t;
221
222 static ir_entity *ia32_get_frame_entity(const ir_node *irn)
223 {
224         return is_ia32_irn(irn) ? get_ia32_frame_ent(irn) : NULL;
225 }
226
227 static void ia32_set_frame_entity(ir_node *node, ir_entity *entity)
228 {
229         if (is_be_node(node))
230                 be_node_set_frame_entity(node, entity);
231         else
232                 set_ia32_frame_ent(node, entity);
233 }
234
235 static void ia32_set_frame_offset(ir_node *irn, int bias)
236 {
237         if (get_ia32_frame_ent(irn) == NULL)
238                 return;
239
240         if (is_ia32_Pop(irn) || is_ia32_PopMem(irn)) {
241                 ir_graph          *irg     = get_irn_irg(irn);
242                 be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
243                 if (layout->sp_relative) {
244                         /* Pop nodes modify the stack pointer before calculating the
245                          * destination address, so fix this here
246                          */
247                         bias -= 4;
248                 }
249         }
250         add_ia32_am_offs_int(irn, bias);
251 }
252
253 static int ia32_get_sp_bias(const ir_node *node)
254 {
255         if (is_ia32_Call(node))
256                 return -(int)get_ia32_call_attr_const(node)->pop;
257
258         if (is_ia32_Push(node))
259                 return 4;
260
261         if (is_ia32_Pop(node) || is_ia32_PopMem(node))
262                 return -4;
263
264         if (is_ia32_Leave(node) || is_ia32_CopyEbpEsp(node)) {
265                 return SP_BIAS_RESET;
266         }
267
268         return 0;
269 }
270
271 /**
272  * Build the between type and entities if not already build.
273  */
274 static void ia32_build_between_type(void)
275 {
276 #define IDENT(s) new_id_from_chars(s, sizeof(s)-1)
277         if (! between_type) {
278                 ir_type *old_bp_type   = new_type_primitive(mode_Iu);
279                 ir_type *ret_addr_type = new_type_primitive(mode_Iu);
280
281                 between_type           = new_type_struct(IDENT("ia32_between_type"));
282                 old_bp_ent             = new_entity(between_type, IDENT("old_bp"), old_bp_type);
283                 ret_addr_ent           = new_entity(between_type, IDENT("ret_addr"), ret_addr_type);
284
285                 set_entity_offset(old_bp_ent, 0);
286                 set_entity_offset(ret_addr_ent, get_type_size_bytes(old_bp_type));
287                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
288                 set_type_state(between_type, layout_fixed);
289
290                 omit_fp_between_type = new_type_struct(IDENT("ia32_between_type_omit_fp"));
291                 omit_fp_ret_addr_ent = new_entity(omit_fp_between_type, IDENT("ret_addr"), ret_addr_type);
292
293                 set_entity_offset(omit_fp_ret_addr_ent, 0);
294                 set_type_size_bytes(omit_fp_between_type, get_type_size_bytes(ret_addr_type));
295                 set_type_state(omit_fp_between_type, layout_fixed);
296         }
297 #undef IDENT
298 }
299
300 /**
301  * Produces the type which sits between the stack args and the locals on the stack.
302  * it will contain the return address and space to store the old base pointer.
303  * @return The Firm type modeling the ABI between type.
304  */
305 static ir_type *ia32_abi_get_between_type(ir_graph *irg)
306 {
307         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
308         ia32_build_between_type();
309         return layout->sp_relative ? omit_fp_between_type : between_type;
310 }
311
312 /**
313  * Return the stack entity that contains the return address.
314  */
315 ir_entity *ia32_get_return_address_entity(ir_graph *irg)
316 {
317         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
318         ia32_build_between_type();
319         return layout->sp_relative ? omit_fp_ret_addr_ent : ret_addr_ent;
320 }
321
322 /**
323  * Return the stack entity that contains the frame address.
324  */
325 ir_entity *ia32_get_frame_address_entity(ir_graph *irg)
326 {
327         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
328         ia32_build_between_type();
329         return layout->sp_relative ? NULL : old_bp_ent;
330 }
331
332 /**
333  * Get the estimated cycle count for @p irn.
334  *
335  * @param self The this pointer.
336  * @param irn  The node.
337  *
338  * @return     The estimated cycle count for this operation
339  */
340 static int ia32_get_op_estimated_cost(const ir_node *irn)
341 {
342         int            cost;
343         ia32_op_type_t op_tp;
344
345         if (is_Proj(irn))
346                 return 0;
347         if (!is_ia32_irn(irn))
348                 return 0;
349
350         assert(is_ia32_irn(irn));
351
352         cost  = get_ia32_latency(irn);
353         op_tp = get_ia32_op_type(irn);
354
355         if (is_ia32_CopyB(irn)) {
356                 cost = 250;
357         }
358         else if (is_ia32_CopyB_i(irn)) {
359                 int size = get_ia32_copyb_size(irn);
360                 cost     = 20 + (int)ceil((4/3) * size);
361         }
362         /* in case of address mode operations add additional cycles */
363         else if (op_tp == ia32_AddrModeD || op_tp == ia32_AddrModeS) {
364                 /*
365                         In case of stack access and access to fixed addresses add 5 cycles
366                         (we assume they are in cache), other memory operations cost 20
367                         cycles.
368                 */
369                 if (is_ia32_use_frame(irn) || (
370                     is_ia32_NoReg_GP(get_irn_n(irn, n_ia32_base)) &&
371                     is_ia32_NoReg_GP(get_irn_n(irn, n_ia32_index))
372                     )) {
373                         cost += 5;
374                 } else {
375                         cost += 20;
376                 }
377         }
378
379         return cost;
380 }
381
382 /**
383  * Returns the inverse operation if @p irn, recalculating the argument at position @p i.
384  *
385  * @param irn       The original operation
386  * @param i         Index of the argument we want the inverse operation to yield
387  * @param inverse   struct to be filled with the resulting inverse op
388  * @param obstack   The obstack to use for allocation of the returned nodes array
389  * @return          The inverse operation or NULL if operation invertible
390  */
391 static arch_inverse_t *ia32_get_inverse(const ir_node *irn, int i, arch_inverse_t *inverse, struct obstack *obst)
392 {
393         (void) irn;
394         (void) i;
395         (void) inverse;
396         (void) obst;
397         return NULL;
398
399 #if 0
400         ir_mode  *mode;
401         ir_mode  *irn_mode;
402         ir_node  *block, *noreg, *nomem;
403         dbg_info *dbgi;
404
405         /* we cannot invert non-ia32 irns */
406         if (! is_ia32_irn(irn))
407                 return NULL;
408
409         /* operand must always be a real operand (not base, index or mem) */
410         if (i != n_ia32_binary_left && i != n_ia32_binary_right)
411                 return NULL;
412
413         /* we don't invert address mode operations */
414         if (get_ia32_op_type(irn) != ia32_Normal)
415                 return NULL;
416
417         /* TODO: adjust for new immediates... */
418         ir_fprintf(stderr, "TODO: fix get_inverse for new immediates (%+F)\n",
419                    irn);
420         return NULL;
421
422         block    = get_nodes_block(irn);
423         mode     = get_irn_mode(irn);
424         irn_mode = get_irn_mode(irn);
425         noreg    = get_irn_n(irn, 0);
426         nomem    = get_irg_no_mem(irg);
427         dbgi     = get_irn_dbg_info(irn);
428
429         /* initialize structure */
430         inverse->nodes = obstack_alloc(obst, 2 * sizeof(inverse->nodes[0]));
431         inverse->costs = 0;
432         inverse->n     = 1;
433
434         switch (get_ia32_irn_opcode(irn)) {
435                 case iro_ia32_Add:
436                         if (get_ia32_immop_type(irn) == ia32_ImmConst) {
437                                 /* we have an add with a const here */
438                                 /* invers == add with negated const */
439                                 inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
440                                 inverse->costs   += 1;
441                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
442                                 set_ia32_Immop_tarval(inverse->nodes[0], tarval_neg(get_ia32_Immop_tarval(irn)));
443                                 set_ia32_commutative(inverse->nodes[0]);
444                         }
445                         else if (get_ia32_immop_type(irn) == ia32_ImmSymConst) {
446                                 /* we have an add with a symconst here */
447                                 /* invers == sub with const */
448                                 inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
449                                 inverse->costs   += 2;
450                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
451                         }
452                         else {
453                                 /* normal add: inverse == sub */
454                                 inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, i ^ 1));
455                                 inverse->costs   += 2;
456                         }
457                         break;
458                 case iro_ia32_Sub:
459                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
460                                 /* we have a sub with a const/symconst here */
461                                 /* invers == add with this const */
462                                 inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
463                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
464                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
465                         }
466                         else {
467                                 /* normal sub */
468                                 if (i == n_ia32_binary_left) {
469                                         inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, 3));
470                                 }
471                                 else {
472                                         inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, n_ia32_binary_left), (ir_node*) irn);
473                                 }
474                                 inverse->costs += 1;
475                         }
476                         break;
477                 case iro_ia32_Xor:
478                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
479                                 /* xor with const: inverse = xor */
480                                 inverse->nodes[0] = new_bd_ia32_Xor(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
481                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
482                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
483                         }
484                         else {
485                                 /* normal xor */
486                                 inverse->nodes[0] = new_bd_ia32_Xor(dbgi, block, noreg, noreg, nomem, (ir_node *) irn, get_irn_n(irn, i));
487                                 inverse->costs   += 1;
488                         }
489                         break;
490                 case iro_ia32_Not: {
491                         inverse->nodes[0] = new_bd_ia32_Not(dbgi, block, (ir_node*) irn);
492                         inverse->costs   += 1;
493                         break;
494                 }
495                 case iro_ia32_Neg: {
496                         inverse->nodes[0] = new_bd_ia32_Neg(dbgi, block, (ir_node*) irn);
497                         inverse->costs   += 1;
498                         break;
499                 }
500                 default:
501                         /* inverse operation not supported */
502                         return NULL;
503         }
504
505         return inverse;
506 #endif
507 }
508
509 static ir_mode *get_spill_mode_mode(const ir_mode *mode)
510 {
511         if (mode_is_float(mode))
512                 return mode_D;
513
514         return mode_Iu;
515 }
516
517 /**
518  * Get the mode that should be used for spilling value node
519  */
520 static ir_mode *get_spill_mode(const ir_node *node)
521 {
522         ir_mode *mode = get_irn_mode(node);
523         return get_spill_mode_mode(mode);
524 }
525
526 /**
527  * Checks whether an addressmode reload for a node with mode mode is compatible
528  * with a spillslot of mode spill_mode
529  */
530 static int ia32_is_spillmode_compatible(const ir_mode *mode, const ir_mode *spillmode)
531 {
532         return !mode_is_float(mode) || mode == spillmode;
533 }
534
535 /**
536  * Check if irn can load its operand at position i from memory (source addressmode).
537  * @param irn    The irn to be checked
538  * @param i      The operands position
539  * @return Non-Zero if operand can be loaded
540  */
541 static int ia32_possible_memory_operand(const ir_node *irn, unsigned int i)
542 {
543         ir_node       *op        = get_irn_n(irn, i);
544         const ir_mode *mode      = get_irn_mode(op);
545         const ir_mode *spillmode = get_spill_mode(op);
546
547         if (!is_ia32_irn(irn)                              ||  /* must be an ia32 irn */
548             get_ia32_op_type(irn) != ia32_Normal           ||  /* must not already be a addressmode irn */
549             !ia32_is_spillmode_compatible(mode, spillmode) ||
550             is_ia32_use_frame(irn))                            /* must not already use frame */
551                 return 0;
552
553         switch (get_ia32_am_support(irn)) {
554                 case ia32_am_none:
555                         return 0;
556
557                 case ia32_am_unary:
558                         if (i != n_ia32_unary_op)
559                                 return 0;
560                         break;
561
562                 case ia32_am_binary:
563                         switch (i) {
564                                 case n_ia32_binary_left: {
565                                         const arch_register_req_t *req;
566                                         if (!is_ia32_commutative(irn))
567                                                 return 0;
568
569                                         /* we can't swap left/right for limited registers
570                                          * (As this (currently) breaks constraint handling copies)
571                                          */
572                                         req = arch_get_irn_register_req_in(irn, n_ia32_binary_left);
573                                         if (req->type & arch_register_req_type_limited)
574                                                 return 0;
575                                         break;
576                                 }
577
578                                 case n_ia32_binary_right:
579                                         break;
580
581                                 default:
582                                         return 0;
583                         }
584                         break;
585
586                 default:
587                         panic("Unknown AM type");
588         }
589
590         /* HACK: must not already use "real" memory.
591          * This can happen for Call and Div */
592         if (!is_NoMem(get_irn_n(irn, n_ia32_mem)))
593                 return 0;
594
595         return 1;
596 }
597
598 static void ia32_perform_memory_operand(ir_node *irn, ir_node *spill,
599                                         unsigned int i)
600 {
601         ir_mode *load_mode;
602         ir_mode *dest_op_mode;
603
604         assert(ia32_possible_memory_operand(irn, i) && "Cannot perform memory operand change");
605
606         set_ia32_op_type(irn, ia32_AddrModeS);
607
608         load_mode    = get_irn_mode(get_irn_n(irn, i));
609         dest_op_mode = get_ia32_ls_mode(irn);
610         if (get_mode_size_bits(load_mode) <= get_mode_size_bits(dest_op_mode)) {
611                 set_ia32_ls_mode(irn, load_mode);
612         }
613         set_ia32_use_frame(irn);
614         set_ia32_need_stackent(irn);
615
616         if (i == n_ia32_binary_left                    &&
617             get_ia32_am_support(irn) == ia32_am_binary &&
618             /* immediates are only allowed on the right side */
619             !is_ia32_Immediate(get_irn_n(irn, n_ia32_binary_right))) {
620                 ia32_swap_left_right(irn);
621                 i = n_ia32_binary_right;
622         }
623
624         assert(is_NoMem(get_irn_n(irn, n_ia32_mem)));
625
626         set_irn_n(irn, n_ia32_base, get_irg_frame(get_irn_irg(irn)));
627         set_irn_n(irn, n_ia32_mem,  spill);
628         set_irn_n(irn, i,           ia32_get_admissible_noreg(irn, i));
629         set_ia32_is_reload(irn);
630 }
631
632 static const be_abi_callbacks_t ia32_abi_callbacks = {
633         ia32_abi_get_between_type,
634 };
635
636 /* register allocator interface */
637 static const arch_irn_ops_t ia32_irn_ops = {
638         ia32_classify,
639         ia32_get_frame_entity,
640         ia32_set_frame_offset,
641         ia32_get_sp_bias,
642         ia32_get_inverse,
643         ia32_get_op_estimated_cost,
644         ia32_possible_memory_operand,
645         ia32_perform_memory_operand,
646 };
647
648 static ir_entity *mcount = NULL;
649 static int gprof = 0;
650
651 static void ia32_before_abi(ir_graph *irg)
652 {
653         if (gprof) {
654                 if (mcount == NULL) {
655                         ir_type *tp = new_type_method(0, 0);
656                         ident   *id = new_id_from_str("mcount");
657                         mcount = new_entity(get_glob_type(), id, tp);
658                         /* FIXME: enter the right ld_ident here */
659                         set_entity_ld_ident(mcount, get_entity_ident(mcount));
660                         set_entity_visibility(mcount, ir_visibility_external);
661                 }
662                 instrument_initcall(irg, mcount);
663         }
664 }
665
666 /**
667  * Transforms the standard firm graph into
668  * an ia32 firm graph
669  */
670 static void ia32_prepare_graph(ir_graph *irg)
671 {
672         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
673
674 #ifdef FIRM_GRGEN_BE
675         switch (be_transformer) {
676         case TRANSFORMER_DEFAULT:
677                 /* transform remaining nodes into assembler instructions */
678                 ia32_transform_graph(irg);
679                 break;
680
681         case TRANSFORMER_PBQP:
682         case TRANSFORMER_RAND:
683                 /* transform nodes into assembler instructions by PBQP magic */
684                 ia32_transform_graph_by_pbqp(irg);
685                 break;
686
687         default:
688                 panic("invalid transformer");
689         }
690 #else
691         ia32_transform_graph(irg);
692 #endif
693
694         /* do local optimizations (mainly CSE) */
695         optimize_graph_df(irg);
696         /* backend code expects that outedges are always enabled */
697         edges_assure(irg);
698
699         if (irg_data->dump)
700                 dump_ir_graph(irg, "transformed");
701
702         /* optimize address mode */
703         ia32_optimize_graph(irg);
704
705         /* do code placement, to optimize the position of constants */
706         place_code(irg);
707         /* backend code expects that outedges are always enabled */
708         edges_assure(irg);
709
710         if (irg_data->dump)
711                 dump_ir_graph(irg, "place");
712 }
713
714 ir_node *ia32_turn_back_am(ir_node *node)
715 {
716         dbg_info *dbgi  = get_irn_dbg_info(node);
717         ir_graph *irg   = get_irn_irg(node);
718         ir_node  *block = get_nodes_block(node);
719         ir_node  *base  = get_irn_n(node, n_ia32_base);
720         ir_node  *idx   = get_irn_n(node, n_ia32_index);
721         ir_node  *mem   = get_irn_n(node, n_ia32_mem);
722         ir_node  *noreg;
723
724         ir_node  *load     = new_bd_ia32_Load(dbgi, block, base, idx, mem);
725         ir_node  *load_res = new_rd_Proj(dbgi, load, mode_Iu, pn_ia32_Load_res);
726
727         ia32_copy_am_attrs(load, node);
728         if (is_ia32_is_reload(node))
729                 set_ia32_is_reload(load);
730         set_irn_n(node, n_ia32_mem, get_irg_no_mem(irg));
731
732         switch (get_ia32_am_support(node)) {
733                 case ia32_am_unary:
734                         set_irn_n(node, n_ia32_unary_op, load_res);
735                         break;
736
737                 case ia32_am_binary:
738                         if (is_ia32_Immediate(get_irn_n(node, n_ia32_binary_right))) {
739                                 set_irn_n(node, n_ia32_binary_left, load_res);
740                         } else {
741                                 set_irn_n(node, n_ia32_binary_right, load_res);
742                         }
743                         break;
744
745                 default:
746                         panic("Unknown AM type");
747         }
748         noreg = ia32_new_NoReg_gp(current_ir_graph);
749         set_irn_n(node, n_ia32_base,  noreg);
750         set_irn_n(node, n_ia32_index, noreg);
751         set_ia32_am_offs_int(node, 0);
752         set_ia32_am_sc(node, NULL);
753         set_ia32_am_scale(node, 0);
754         clear_ia32_am_sc_sign(node);
755
756         /* rewire mem-proj */
757         if (get_irn_mode(node) == mode_T) {
758                 const ir_edge_t *edge;
759                 foreach_out_edge(node, edge) {
760                         ir_node *out = get_edge_src_irn(edge);
761                         if (get_irn_mode(out) == mode_M) {
762                                 set_Proj_pred(out, load);
763                                 set_Proj_proj(out, pn_ia32_Load_M);
764                                 break;
765                         }
766                 }
767         }
768
769         set_ia32_op_type(node, ia32_Normal);
770         if (sched_is_scheduled(node))
771                 sched_add_before(node, load);
772
773         return load_res;
774 }
775
776 static ir_node *flags_remat(ir_node *node, ir_node *after)
777 {
778         /* we should turn back source address mode when rematerializing nodes */
779         ia32_op_type_t type;
780         ir_node        *block;
781         ir_node        *copy;
782
783         if (is_Block(after)) {
784                 block = after;
785         } else {
786                 block = get_nodes_block(after);
787         }
788
789         type = get_ia32_op_type(node);
790         switch (type) {
791                 case ia32_AddrModeS:
792                         ia32_turn_back_am(node);
793                         break;
794
795                 case ia32_AddrModeD:
796                         /* TODO implement this later... */
797                         panic("found DestAM with flag user %+F this should not happen", node);
798
799                 default: assert(type == ia32_Normal); break;
800         }
801
802         copy = exact_copy(node);
803         set_nodes_block(copy, block);
804         sched_add_after(after, copy);
805
806         return copy;
807 }
808
809 /**
810  * Called before the register allocator.
811  */
812 static void ia32_before_ra(ir_graph *irg)
813 {
814         /* setup fpu rounding modes */
815         ia32_setup_fpu_mode(irg);
816
817         /* fixup flags */
818         be_sched_fix_flags(irg, &ia32_reg_classes[CLASS_ia32_flags],
819                            &flags_remat, NULL);
820
821         be_add_missing_keeps(irg);
822 }
823
824
825 /**
826  * Transforms a be_Reload into a ia32 Load.
827  */
828 static void transform_to_Load(ir_node *node)
829 {
830         ir_graph *irg        = get_irn_irg(node);
831         dbg_info *dbgi       = get_irn_dbg_info(node);
832         ir_node *block       = get_nodes_block(node);
833         ir_entity *ent       = be_get_frame_entity(node);
834         ir_mode *mode        = get_irn_mode(node);
835         ir_mode *spillmode   = get_spill_mode(node);
836         ir_node *noreg       = ia32_new_NoReg_gp(irg);
837         ir_node *sched_point = NULL;
838         ir_node *ptr         = get_irg_frame(irg);
839         ir_node *mem         = get_irn_n(node, n_be_Reload_mem);
840         ir_node *new_op, *proj;
841         const arch_register_t *reg;
842
843         if (sched_is_scheduled(node)) {
844                 sched_point = sched_prev(node);
845         }
846
847         if (mode_is_float(spillmode)) {
848                 if (ia32_cg_config.use_sse2)
849                         new_op = new_bd_ia32_xLoad(dbgi, block, ptr, noreg, mem, spillmode);
850                 else
851                         new_op = new_bd_ia32_vfld(dbgi, block, ptr, noreg, mem, spillmode);
852         }
853         else if (get_mode_size_bits(spillmode) == 128) {
854                 /* Reload 128 bit SSE registers */
855                 new_op = new_bd_ia32_xxLoad(dbgi, block, ptr, noreg, mem);
856         }
857         else
858                 new_op = new_bd_ia32_Load(dbgi, block, ptr, noreg, mem);
859
860         set_ia32_op_type(new_op, ia32_AddrModeS);
861         set_ia32_ls_mode(new_op, spillmode);
862         set_ia32_frame_ent(new_op, ent);
863         set_ia32_use_frame(new_op);
864         set_ia32_is_reload(new_op);
865
866         DBG_OPT_RELOAD2LD(node, new_op);
867
868         proj = new_rd_Proj(dbgi, new_op, mode, pn_ia32_Load_res);
869
870         if (sched_point) {
871                 sched_add_after(sched_point, new_op);
872                 sched_remove(node);
873         }
874
875         /* copy the register from the old node to the new Load */
876         reg = arch_get_irn_register(node);
877         arch_set_irn_register(proj, reg);
878
879         SET_IA32_ORIG_NODE(new_op, node);
880
881         exchange(node, proj);
882 }
883
884 /**
885  * Transforms a be_Spill node into a ia32 Store.
886  */
887 static void transform_to_Store(ir_node *node)
888 {
889         ir_graph *irg  = get_irn_irg(node);
890         dbg_info *dbgi = get_irn_dbg_info(node);
891         ir_node *block = get_nodes_block(node);
892         ir_entity *ent = be_get_frame_entity(node);
893         const ir_node *spillval = get_irn_n(node, n_be_Spill_val);
894         ir_mode *mode  = get_spill_mode(spillval);
895         ir_node *noreg = ia32_new_NoReg_gp(irg);
896         ir_node *nomem = get_irg_no_mem(irg);
897         ir_node *ptr   = get_irg_frame(irg);
898         ir_node *val   = get_irn_n(node, n_be_Spill_val);
899         ir_node *res;
900         ir_node *store;
901         ir_node *sched_point = NULL;
902
903         if (sched_is_scheduled(node)) {
904                 sched_point = sched_prev(node);
905         }
906
907         if (mode_is_float(mode)) {
908                 if (ia32_cg_config.use_sse2) {
909                         store = new_bd_ia32_xStore(dbgi, block, ptr, noreg, nomem, val);
910                         res   = new_r_Proj(store, mode_M, pn_ia32_xStore_M);
911                 } else {
912                         store = new_bd_ia32_vfst(dbgi, block, ptr, noreg, nomem, val, mode);
913                         res   = new_r_Proj(store, mode_M, pn_ia32_vfst_M);
914                 }
915         } else if (get_mode_size_bits(mode) == 128) {
916                 /* Spill 128 bit SSE registers */
917                 store = new_bd_ia32_xxStore(dbgi, block, ptr, noreg, nomem, val);
918                 res   = new_r_Proj(store, mode_M, pn_ia32_xxStore_M);
919         } else if (get_mode_size_bits(mode) == 8) {
920                 store = new_bd_ia32_Store8Bit(dbgi, block, ptr, noreg, nomem, val);
921                 res   = new_r_Proj(store, mode_M, pn_ia32_Store8Bit_M);
922         } else {
923                 store = new_bd_ia32_Store(dbgi, block, ptr, noreg, nomem, val);
924                 res   = new_r_Proj(store, mode_M, pn_ia32_Store_M);
925         }
926
927         set_ia32_op_type(store, ia32_AddrModeD);
928         set_ia32_ls_mode(store, mode);
929         set_ia32_frame_ent(store, ent);
930         set_ia32_use_frame(store);
931         set_ia32_is_spill(store);
932         SET_IA32_ORIG_NODE(store, node);
933         DBG_OPT_SPILL2ST(node, store);
934
935         if (sched_point) {
936                 sched_add_after(sched_point, store);
937                 sched_remove(node);
938         }
939
940         exchange(node, res);
941 }
942
943 static ir_node *create_push(ir_node *node, ir_node *schedpoint, ir_node *sp, ir_node *mem, ir_entity *ent)
944 {
945         dbg_info *dbgi  = get_irn_dbg_info(node);
946         ir_node  *block = get_nodes_block(node);
947         ir_graph *irg   = get_irn_irg(node);
948         ir_node  *noreg = ia32_new_NoReg_gp(irg);
949         ir_node  *frame = get_irg_frame(irg);
950
951         ir_node *push = new_bd_ia32_Push(dbgi, block, frame, noreg, mem, noreg, sp);
952
953         set_ia32_frame_ent(push, ent);
954         set_ia32_use_frame(push);
955         set_ia32_op_type(push, ia32_AddrModeS);
956         set_ia32_ls_mode(push, mode_Is);
957         set_ia32_is_spill(push);
958
959         sched_add_before(schedpoint, push);
960         return push;
961 }
962
963 static ir_node *create_pop(ir_node *node, ir_node *schedpoint, ir_node *sp, ir_entity *ent)
964 {
965         dbg_info *dbgi  = get_irn_dbg_info(node);
966         ir_node  *block = get_nodes_block(node);
967         ir_graph *irg   = get_irn_irg(node);
968         ir_node  *noreg = ia32_new_NoReg_gp(irg);
969         ir_node  *frame = get_irg_frame(irg);
970
971         ir_node *pop = new_bd_ia32_PopMem(dbgi, block, frame, noreg,
972                                           get_irg_no_mem(irg), sp);
973
974         set_ia32_frame_ent(pop, ent);
975         set_ia32_use_frame(pop);
976         set_ia32_op_type(pop, ia32_AddrModeD);
977         set_ia32_ls_mode(pop, mode_Is);
978         set_ia32_is_reload(pop);
979
980         sched_add_before(schedpoint, pop);
981
982         return pop;
983 }
984
985 static ir_node* create_spproj(ir_node *node, ir_node *pred, int pos)
986 {
987         dbg_info *dbgi   = get_irn_dbg_info(node);
988         ir_mode  *spmode = mode_Iu;
989         const arch_register_t *spreg = &ia32_registers[REG_ESP];
990         ir_node *sp;
991
992         sp = new_rd_Proj(dbgi, pred, spmode, pos);
993         arch_set_irn_register(sp, spreg);
994
995         return sp;
996 }
997
998 /**
999  * Transform MemPerm, currently we do this the ugly way and produce
1000  * push/pop into/from memory cascades. This is possible without using
1001  * any registers.
1002  */
1003 static void transform_MemPerm(ir_node *node)
1004 {
1005         ir_node         *block = get_nodes_block(node);
1006         ir_graph        *irg   = get_irn_irg(node);
1007         ir_node         *sp    = be_get_initial_reg_value(irg, &ia32_registers[REG_ESP]);
1008         int              arity = be_get_MemPerm_entity_arity(node);
1009         ir_node        **pops  = ALLOCAN(ir_node*, arity);
1010         ir_node         *in[1];
1011         ir_node         *keep;
1012         int              i;
1013         const ir_edge_t *edge;
1014         const ir_edge_t *next;
1015
1016         /* create Pushs */
1017         for (i = 0; i < arity; ++i) {
1018                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1019                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1020                 ir_type *enttype = get_entity_type(inent);
1021                 unsigned entsize = get_type_size_bytes(enttype);
1022                 unsigned entsize2 = get_type_size_bytes(get_entity_type(outent));
1023                 ir_node *mem = get_irn_n(node, i + 1);
1024                 ir_node *push;
1025
1026                 /* work around cases where entities have different sizes */
1027                 if (entsize2 < entsize)
1028                         entsize = entsize2;
1029                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1030
1031                 push = create_push(node, node, sp, mem, inent);
1032                 sp = create_spproj(node, push, pn_ia32_Push_stack);
1033                 if (entsize == 8) {
1034                         /* add another push after the first one */
1035                         push = create_push(node, node, sp, mem, inent);
1036                         add_ia32_am_offs_int(push, 4);
1037                         sp = create_spproj(node, push, pn_ia32_Push_stack);
1038                 }
1039
1040                 set_irn_n(node, i, new_r_Bad(irg, mode_X));
1041         }
1042
1043         /* create pops */
1044         for (i = arity - 1; i >= 0; --i) {
1045                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1046                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1047                 ir_type *enttype = get_entity_type(outent);
1048                 unsigned entsize = get_type_size_bytes(enttype);
1049                 unsigned entsize2 = get_type_size_bytes(get_entity_type(inent));
1050                 ir_node *pop;
1051
1052                 /* work around cases where entities have different sizes */
1053                 if (entsize2 < entsize)
1054                         entsize = entsize2;
1055                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1056
1057                 pop = create_pop(node, node, sp, outent);
1058                 sp = create_spproj(node, pop, pn_ia32_Pop_stack);
1059                 if (entsize == 8) {
1060                         add_ia32_am_offs_int(pop, 4);
1061
1062                         /* add another pop after the first one */
1063                         pop = create_pop(node, node, sp, outent);
1064                         sp = create_spproj(node, pop, pn_ia32_Pop_stack);
1065                 }
1066
1067                 pops[i] = pop;
1068         }
1069
1070         in[0] = sp;
1071         keep  = be_new_Keep(block, 1, in);
1072         sched_add_before(node, keep);
1073
1074         /* exchange memprojs */
1075         foreach_out_edge_safe(node, edge, next) {
1076                 ir_node *proj = get_edge_src_irn(edge);
1077                 int p = get_Proj_proj(proj);
1078
1079                 assert(p < arity);
1080
1081                 set_Proj_pred(proj, pops[p]);
1082                 set_Proj_proj(proj, pn_ia32_Pop_M);
1083         }
1084
1085         /* remove memperm */
1086         sched_remove(node);
1087         kill_node(node);
1088 }
1089
1090 /**
1091  * Block-Walker: Calls the transform functions Spill and Reload.
1092  */
1093 static void ia32_after_ra_walker(ir_node *block, void *env)
1094 {
1095         ir_node *node, *prev;
1096         (void) env;
1097
1098         /* beware: the schedule is changed here */
1099         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
1100                 prev = sched_prev(node);
1101
1102                 if (be_is_Reload(node)) {
1103                         transform_to_Load(node);
1104                 } else if (be_is_Spill(node)) {
1105                         transform_to_Store(node);
1106                 } else if (be_is_MemPerm(node)) {
1107                         transform_MemPerm(node);
1108                 }
1109         }
1110 }
1111
1112 /**
1113  * Collects nodes that need frame entities assigned.
1114  */
1115 static void ia32_collect_frame_entity_nodes(ir_node *node, void *data)
1116 {
1117         be_fec_env_t  *env = (be_fec_env_t*)data;
1118         const ir_mode *mode;
1119         int            align;
1120
1121         if (be_is_Reload(node) && be_get_frame_entity(node) == NULL) {
1122                 mode  = get_spill_mode_mode(get_irn_mode(node));
1123                 align = get_mode_size_bytes(mode);
1124         } else if (is_ia32_irn(node)         &&
1125                         get_ia32_frame_ent(node) == NULL &&
1126                         is_ia32_use_frame(node)) {
1127                 if (is_ia32_need_stackent(node))
1128                         goto need_stackent;
1129
1130                 switch (get_ia32_irn_opcode(node)) {
1131 need_stackent:
1132                         case iro_ia32_Load: {
1133                                 const ia32_attr_t *attr = get_ia32_attr_const(node);
1134
1135                                 if (attr->data.need_32bit_stackent) {
1136                                         mode = mode_Is;
1137                                 } else if (attr->data.need_64bit_stackent) {
1138                                         mode = mode_Ls;
1139                                 } else {
1140                                         mode = get_ia32_ls_mode(node);
1141                                         if (is_ia32_is_reload(node))
1142                                                 mode = get_spill_mode_mode(mode);
1143                                 }
1144                                 align = get_mode_size_bytes(mode);
1145                                 break;
1146                         }
1147
1148                         case iro_ia32_vfild:
1149                         case iro_ia32_vfld:
1150                         case iro_ia32_xLoad: {
1151                                 mode  = get_ia32_ls_mode(node);
1152                                 align = 4;
1153                                 break;
1154                         }
1155
1156                         case iro_ia32_FldCW: {
1157                                 /* although 2 byte would be enough 4 byte performs best */
1158                                 mode  = mode_Iu;
1159                                 align = 4;
1160                                 break;
1161                         }
1162
1163                         default:
1164 #ifndef NDEBUG
1165                                 panic("unexpected frame user while collection frame entity nodes");
1166
1167                         case iro_ia32_FnstCW:
1168                         case iro_ia32_Store8Bit:
1169                         case iro_ia32_Store:
1170                         case iro_ia32_fst:
1171                         case iro_ia32_fstp:
1172                         case iro_ia32_vfist:
1173                         case iro_ia32_vfisttp:
1174                         case iro_ia32_vfst:
1175                         case iro_ia32_xStore:
1176                         case iro_ia32_xStoreSimple:
1177 #endif
1178                                 return;
1179                 }
1180         } else {
1181                 return;
1182         }
1183         be_node_needs_frame_entity(env, node, mode, align);
1184 }
1185
1186 static int determine_ebp_input(ir_node *ret)
1187 {
1188         const arch_register_t *bp = &ia32_registers[REG_EBP];
1189         int   arity               = get_irn_arity(ret);
1190         int   i;
1191
1192         for (i = 0; i < arity; ++i) {
1193                 ir_node *input = get_irn_n(ret, i);
1194                 if (arch_get_irn_register(input) == bp)
1195                         return i;
1196         }
1197         panic("no ebp input found at %+F", ret);
1198 }
1199
1200 static void introduce_epilog(ir_node *ret)
1201 {
1202         const arch_register_t *sp         = &ia32_registers[REG_ESP];
1203         const arch_register_t *bp         = &ia32_registers[REG_EBP];
1204         ir_graph              *irg        = get_irn_irg(ret);
1205         ir_type               *frame_type = get_irg_frame_type(irg);
1206         unsigned               frame_size = get_type_size_bytes(frame_type);
1207         be_stack_layout_t     *layout     = be_get_irg_stack_layout(irg);
1208         ir_node               *block      = get_nodes_block(ret);
1209         ir_node               *first_sp   = get_irn_n(ret, n_be_Return_sp);
1210         ir_node               *curr_sp    = first_sp;
1211         ir_mode               *mode_gp    = mode_Iu;
1212
1213         if (!layout->sp_relative) {
1214                 int      n_ebp   = determine_ebp_input(ret);
1215                 ir_node *curr_bp = get_irn_n(ret, n_ebp);
1216                 if (ia32_cg_config.use_leave) {
1217                         ir_node *leave = new_bd_ia32_Leave(NULL, block, curr_bp);
1218                         curr_bp        = new_r_Proj(leave, mode_gp, pn_ia32_Leave_frame);
1219                         curr_sp        = new_r_Proj(leave, mode_gp, pn_ia32_Leave_stack);
1220                         arch_set_irn_register(curr_bp, bp);
1221                         arch_set_irn_register(curr_sp, sp);
1222                         sched_add_before(ret, leave);
1223                 } else {
1224                         ir_node *pop;
1225                         ir_node *curr_mem = get_irn_n(ret, n_be_Return_mem);
1226                         /* copy ebp to esp */
1227                         curr_sp = new_bd_ia32_CopyEbpEsp(NULL, block, curr_bp);
1228                         arch_set_irn_register(curr_sp, sp);
1229                         sched_add_before(ret, curr_sp);
1230
1231                         /* pop ebp */
1232                         pop      = new_bd_ia32_PopEbp(NULL, block, curr_mem, curr_sp);
1233                         curr_bp  = new_r_Proj(pop, mode_gp, pn_ia32_PopEbp_res);
1234                         curr_sp  = new_r_Proj(pop, mode_gp, pn_ia32_PopEbp_stack);
1235                         curr_mem = new_r_Proj(pop, mode_M, pn_ia32_Pop_M);
1236                         arch_set_irn_register(curr_bp, bp);
1237                         arch_set_irn_register(curr_sp, sp);
1238                         sched_add_before(ret, pop);
1239
1240                         set_irn_n(ret, n_be_Return_mem, curr_mem);
1241                 }
1242                 set_irn_n(ret, n_ebp, curr_bp);
1243         } else {
1244                 ir_node *incsp = be_new_IncSP(sp, block, curr_sp, -(int)frame_size, 0);
1245                 sched_add_before(ret, incsp);
1246                 curr_sp = incsp;
1247         }
1248         set_irn_n(ret, n_be_Return_sp, curr_sp);
1249
1250         /* keep verifier happy... */
1251         if (get_irn_n_edges(first_sp) == 0 && is_Proj(first_sp)) {
1252                 kill_node(first_sp);
1253         }
1254 }
1255
1256 /**
1257  * put the Prolog code at the beginning, epilog code before each return
1258  */
1259 static void introduce_prolog_epilog(ir_graph *irg)
1260 {
1261         const arch_register_t *sp         = &ia32_registers[REG_ESP];
1262         const arch_register_t *bp         = &ia32_registers[REG_EBP];
1263         ir_node               *start      = get_irg_start(irg);
1264         ir_node               *block      = get_nodes_block(start);
1265         ir_type               *frame_type = get_irg_frame_type(irg);
1266         unsigned               frame_size = get_type_size_bytes(frame_type);
1267         be_stack_layout_t     *layout     = be_get_irg_stack_layout(irg);
1268         ir_node               *initial_sp = be_get_initial_reg_value(irg, sp);
1269         ir_node               *curr_sp    = initial_sp;
1270         ir_mode               *mode_gp    = mode_Iu;
1271
1272         if (!layout->sp_relative) {
1273                 /* push ebp */
1274                 ir_node *mem        = get_irg_initial_mem(irg);
1275                 ir_node *noreg      = ia32_new_NoReg_gp(irg);
1276                 ir_node *initial_bp = be_get_initial_reg_value(irg, bp);
1277                 ir_node *curr_bp    = initial_bp;
1278                 ir_node *push       = new_bd_ia32_Push(NULL, block, noreg, noreg, mem, curr_bp, curr_sp);
1279                 ir_node *incsp;
1280
1281                 curr_sp = new_r_Proj(push, mode_gp, pn_ia32_Push_stack);
1282                 mem     = new_r_Proj(push, mode_M, pn_ia32_Push_M);
1283                 arch_set_irn_register(curr_sp, sp);
1284                 sched_add_after(start, push);
1285
1286                 /* move esp to ebp */
1287                 curr_bp = be_new_Copy(block, curr_sp);
1288                 sched_add_after(push, curr_bp);
1289                 be_set_constr_single_reg_out(curr_bp, 0, bp, arch_register_req_type_ignore);
1290                 curr_sp = be_new_CopyKeep_single(block, curr_sp, curr_bp);
1291                 sched_add_after(curr_bp, curr_sp);
1292                 be_set_constr_single_reg_out(curr_sp, 0, sp, arch_register_req_type_produces_sp);
1293                 edges_reroute(initial_bp, curr_bp);
1294                 set_irn_n(push, n_ia32_Push_val, initial_bp);
1295
1296                 incsp = be_new_IncSP(sp, block, curr_sp, frame_size, 0);
1297                 edges_reroute(initial_sp, incsp);
1298                 set_irn_n(push, n_ia32_Push_stack, initial_sp);
1299                 sched_add_after(curr_sp, incsp);
1300
1301                 /* make sure the initial IncSP is really used by someone */
1302                 if (get_irn_n_edges(incsp) <= 1) {
1303                         ir_node *in[] = { incsp };
1304                         ir_node *keep = be_new_Keep(block, 1, in);
1305                         sched_add_after(incsp, keep);
1306                 }
1307
1308                 layout->initial_bias = -4;
1309         } else {
1310                 ir_node *incsp = be_new_IncSP(sp, block, curr_sp, frame_size, 0);
1311                 edges_reroute(initial_sp, incsp);
1312                 be_set_IncSP_pred(incsp, curr_sp);
1313                 sched_add_after(start, incsp);
1314         }
1315
1316         /* introduce epilog for every return node */
1317         {
1318                 ir_node *end_block = get_irg_end_block(irg);
1319                 int      arity     = get_irn_arity(end_block);
1320                 int      i;
1321
1322                 for (i = 0; i < arity; ++i) {
1323                         ir_node *ret = get_irn_n(end_block, i);
1324                         assert(be_is_Return(ret));
1325                         introduce_epilog(ret);
1326                 }
1327         }
1328 }
1329
1330 /**
1331  * Last touchups for the graph before emit: x87 simulation to replace the
1332  * virtual with real x87 instructions, creating a block schedule and peephole
1333  * optimisations.
1334  */
1335 static void ia32_finish(ir_graph *irg)
1336 {
1337         ia32_irg_data_t   *irg_data     = ia32_get_irg_data(irg);
1338         be_stack_layout_t *stack_layout = be_get_irg_stack_layout(irg);
1339         bool               at_begin     = stack_layout->sp_relative ? true : false;
1340         be_fec_env_t      *fec_env      = be_new_frame_entity_coalescer(irg);
1341
1342         /* create and coalesce frame entities */
1343         irg_walk_graph(irg, NULL, ia32_collect_frame_entity_nodes, fec_env);
1344         be_assign_entities(fec_env, ia32_set_frame_entity, at_begin);
1345         be_free_frame_entity_coalescer(fec_env);
1346
1347         irg_block_walk_graph(irg, NULL, ia32_after_ra_walker, NULL);
1348
1349         introduce_prolog_epilog(irg);
1350
1351         /* fix stack entity offsets */
1352         be_abi_fix_stack_nodes(irg);
1353         be_abi_fix_stack_bias(irg);
1354
1355         /* fix 2-address code constraints */
1356         ia32_finish_irg(irg);
1357
1358         /* we might have to rewrite x87 virtual registers */
1359         if (irg_data->do_x87_sim) {
1360                 ia32_x87_simulate_graph(irg);
1361         }
1362
1363         /* do peephole optimisations */
1364         ia32_peephole_optimization(irg);
1365
1366         be_remove_dead_nodes_from_schedule(irg);
1367
1368         /* create block schedule, this also removes empty blocks which might
1369          * produce critical edges */
1370         irg_data->blk_sched = be_create_block_schedule(irg);
1371 }
1372
1373 /**
1374  * Emits the code, closes the output file and frees
1375  * the code generator interface.
1376  */
1377 static void ia32_emit(ir_graph *irg)
1378 {
1379         if (ia32_cg_config.emit_machcode) {
1380                 ia32_gen_binary_routine(irg);
1381         } else {
1382                 ia32_gen_routine(irg);
1383         }
1384 }
1385
1386 /**
1387  * Returns the node representing the PIC base.
1388  */
1389 static ir_node *ia32_get_pic_base(ir_graph *irg)
1390 {
1391         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
1392         ir_node         *block;
1393         ir_node         *get_eip = irg_data->get_eip;
1394         if (get_eip != NULL)
1395                 return get_eip;
1396
1397         block             = get_irg_start_block(irg);
1398         get_eip           = new_bd_ia32_GetEIP(NULL, block);
1399         irg_data->get_eip = get_eip;
1400
1401         return get_eip;
1402 }
1403
1404 /**
1405  * Initializes a IA32 code generator.
1406  */
1407 static void ia32_init_graph(ir_graph *irg)
1408 {
1409         struct obstack  *obst     = be_get_be_obst(irg);
1410         ia32_irg_data_t *irg_data = OALLOCZ(obst, ia32_irg_data_t);
1411
1412         irg_data->dump = (be_get_irg_options(irg)->dump_flags & DUMP_BE) ? 1 : 0;
1413
1414         if (gprof) {
1415                 /* Linux gprof implementation needs base pointer */
1416                 be_get_irg_options(irg)->omit_fp = 0;
1417         }
1418
1419         be_birg_from_irg(irg)->isa_link = irg_data;
1420 }
1421
1422
1423 /**
1424  * Set output modes for GCC
1425  */
1426 static const tarval_mode_info mo_integer = {
1427         TVO_HEX,
1428         "0x",
1429         NULL,
1430 };
1431
1432 /*
1433  * set the tarval output mode of all integer modes to decimal
1434  */
1435 static void set_tarval_output_modes(void)
1436 {
1437         size_t i;
1438
1439         for (i = get_irp_n_modes(); i > 0;) {
1440                 ir_mode *mode = get_irp_mode(--i);
1441
1442                 if (mode_is_int(mode))
1443                         set_tarval_mode_output_option(mode, &mo_integer);
1444         }
1445 }
1446
1447 extern const arch_isa_if_t ia32_isa_if;
1448
1449 /**
1450  * The template that generates a new ISA object.
1451  * Note that this template can be changed by command line
1452  * arguments.
1453  */
1454 static ia32_isa_t ia32_isa_template = {
1455         {
1456                 &ia32_isa_if,            /* isa interface implementation */
1457                 N_IA32_REGISTERS,
1458                 ia32_registers,
1459                 N_IA32_CLASSES,
1460                 ia32_reg_classes,
1461                 &ia32_registers[REG_ESP],  /* stack pointer register */
1462                 &ia32_registers[REG_EBP],  /* base pointer register */
1463                 &ia32_reg_classes[CLASS_ia32_gp],  /* static link pointer register class */
1464                 2,                       /* power of two stack alignment, 2^2 == 4 */
1465                 NULL,                    /* main environment */
1466                 7,                       /* costs for a spill instruction */
1467                 5,                       /* costs for a reload instruction */
1468                 false,                   /* no custom abi handling */
1469         },
1470         NULL,                    /* tv_ents */
1471         NULL,                    /* abstract machine */
1472         IA32_FPU_ARCH_X87,       /* FPU architecture */
1473 };
1474
1475 static void init_asm_constraints(void)
1476 {
1477         be_init_default_asm_constraint_flags();
1478
1479         asm_constraint_flags['a'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1480         asm_constraint_flags['b'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1481         asm_constraint_flags['c'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1482         asm_constraint_flags['d'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1483         asm_constraint_flags['D'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1484         asm_constraint_flags['S'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1485         asm_constraint_flags['Q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1486         asm_constraint_flags['q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1487         asm_constraint_flags['A'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1488         asm_constraint_flags['l'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1489         asm_constraint_flags['R'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1490         asm_constraint_flags['r'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1491         asm_constraint_flags['p'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1492         asm_constraint_flags['f'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1493         asm_constraint_flags['t'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1494         asm_constraint_flags['u'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1495         asm_constraint_flags['Y'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1496         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1497         asm_constraint_flags['n'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1498         asm_constraint_flags['g'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1499
1500         /* no support for autodecrement/autoincrement */
1501         asm_constraint_flags['<'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1502         asm_constraint_flags['>'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1503         /* no float consts */
1504         asm_constraint_flags['E'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1505         asm_constraint_flags['F'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1506         /* makes no sense on x86 */
1507         asm_constraint_flags['s'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1508         /* no support for sse consts yet */
1509         asm_constraint_flags['C'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1510         /* no support for x87 consts yet */
1511         asm_constraint_flags['G'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1512         /* no support for mmx registers yet */
1513         asm_constraint_flags['y'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1514         /* not available in 32bit mode */
1515         asm_constraint_flags['Z'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1516         asm_constraint_flags['e'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1517
1518         /* no code yet to determine register class needed... */
1519         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1520 }
1521
1522 /**
1523  * Initializes the backend ISA.
1524  */
1525 static arch_env_t *ia32_init(const be_main_env_t *env)
1526 {
1527         ia32_isa_t *isa = XMALLOC(ia32_isa_t);
1528
1529         set_tarval_output_modes();
1530
1531         *isa = ia32_isa_template;
1532
1533         if (ia32_mode_fpcw == NULL) {
1534                 ia32_mode_fpcw = new_int_mode("Fpcw", irma_twos_complement, 16, 0, 0);
1535         }
1536
1537         ia32_register_init();
1538         ia32_create_opcodes(&ia32_irn_ops);
1539
1540         isa->tv_ent         = pmap_create();
1541         isa->cpu            = ia32_init_machine_description();
1542
1543         /* enter the ISA object into the intrinsic environment */
1544         intrinsic_env.isa = isa;
1545
1546         be_emit_init(env->file_handle);
1547         be_gas_begin_compilation_unit(env);
1548
1549         return &isa->base;
1550 }
1551
1552 /**
1553  * Closes the output file and frees the ISA structure.
1554  */
1555 static void ia32_done(void *self)
1556 {
1557         ia32_isa_t *isa = (ia32_isa_t*)self;
1558
1559         /* emit now all global declarations */
1560         be_gas_end_compilation_unit(isa->base.main_env);
1561
1562         be_emit_exit();
1563
1564         pmap_destroy(isa->tv_ent);
1565         free(self);
1566 }
1567
1568 /**
1569  * Returns the register for parameter nr.
1570  */
1571 static const arch_register_t *ia32_get_RegParam_reg(unsigned cc, unsigned nr,
1572                                                     const ir_mode *mode)
1573 {
1574         static const arch_register_t *gpreg_param_reg_fastcall[] = {
1575                 &ia32_registers[REG_ECX],
1576                 &ia32_registers[REG_EDX],
1577                 NULL
1578         };
1579         static const unsigned MAXNUM_GPREG_ARGS = 3;
1580
1581         static const arch_register_t *gpreg_param_reg_regparam[] = {
1582                 &ia32_registers[REG_EAX],
1583                 &ia32_registers[REG_EDX],
1584                 &ia32_registers[REG_ECX]
1585         };
1586
1587         static const arch_register_t *gpreg_param_reg_this[] = {
1588                 &ia32_registers[REG_ECX],
1589                 NULL,
1590                 NULL
1591         };
1592
1593         static const arch_register_t *fpreg_sse_param_reg_std[] = {
1594                 &ia32_registers[REG_XMM0],
1595                 &ia32_registers[REG_XMM1],
1596                 &ia32_registers[REG_XMM2],
1597                 &ia32_registers[REG_XMM3],
1598                 &ia32_registers[REG_XMM4],
1599                 &ia32_registers[REG_XMM5],
1600                 &ia32_registers[REG_XMM6],
1601                 &ia32_registers[REG_XMM7]
1602         };
1603
1604         static const arch_register_t *fpreg_sse_param_reg_this[] = {
1605                 NULL,  /* in case of a "this" pointer, the first parameter must not be a float */
1606         };
1607         static const unsigned MAXNUM_SSE_ARGS = 8;
1608
1609         if ((cc & cc_this_call) && nr == 0)
1610                 return gpreg_param_reg_this[0];
1611
1612         if (! (cc & cc_reg_param))
1613                 return NULL;
1614
1615         if (mode_is_float(mode)) {
1616                 if (!ia32_cg_config.use_sse2 || (cc & cc_fpreg_param) == 0)
1617                         return NULL;
1618                 if (nr >= MAXNUM_SSE_ARGS)
1619                         return NULL;
1620
1621                 if (cc & cc_this_call) {
1622                         return fpreg_sse_param_reg_this[nr];
1623                 }
1624                 return fpreg_sse_param_reg_std[nr];
1625         } else if (mode_is_int(mode) || mode_is_reference(mode)) {
1626                 unsigned num_regparam;
1627
1628                 if (get_mode_size_bits(mode) > 32)
1629                         return NULL;
1630
1631                 if (nr >= MAXNUM_GPREG_ARGS)
1632                         return NULL;
1633
1634                 if (cc & cc_this_call) {
1635                         return gpreg_param_reg_this[nr];
1636                 }
1637                 num_regparam = cc & ~cc_bits;
1638                 if (num_regparam == 0) {
1639                         /* default fastcall */
1640                         return gpreg_param_reg_fastcall[nr];
1641                 }
1642                 if (nr < num_regparam)
1643                         return gpreg_param_reg_regparam[nr];
1644                 return NULL;
1645         }
1646
1647         panic("unknown argument mode");
1648 }
1649
1650 /**
1651  * Get the ABI restrictions for procedure calls.
1652  * @param self        The this pointer.
1653  * @param method_type The type of the method (procedure) in question.
1654  * @param abi         The abi object to be modified
1655  */
1656 static void ia32_get_call_abi(const void *self, ir_type *method_type,
1657                               be_abi_call_t *abi)
1658 {
1659         unsigned  cc;
1660         int       n, i, regnum;
1661         int                 pop_amount = 0;
1662         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
1663
1664         (void) self;
1665
1666         /* set abi flags for calls */
1667         call_flags.bits.store_args_sequential = 0;
1668         /* call_flags.bits.try_omit_fp                 not changed: can handle both settings */
1669         call_flags.bits.fp_free               = 0;  /* the frame pointer is fixed in IA32 */
1670         call_flags.bits.call_has_imm          = 0;  /* No call immediate, we handle this by ourselves */
1671
1672         /* set parameter passing style */
1673         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
1674
1675         cc = get_method_calling_convention(method_type);
1676         if (get_method_variadicity(method_type) == variadicity_variadic) {
1677                 /* pass all parameters of a variadic function on the stack */
1678                 cc = cc_cdecl_set | (cc & cc_this_call);
1679         } else {
1680                 if (get_method_additional_properties(method_type) & mtp_property_private &&
1681                     ia32_cg_config.optimize_cc) {
1682                         /* set the fast calling conventions (allowing up to 3) */
1683                         cc = SET_FASTCALL(cc) | 3;
1684                 }
1685         }
1686
1687         /* we have to pop the shadow parameter ourself for compound calls */
1688         if ( (get_method_calling_convention(method_type) & cc_compound_ret)
1689                         && !(cc & cc_reg_param)) {
1690                 pop_amount += get_mode_size_bytes(mode_P_data);
1691         }
1692
1693         n = get_method_n_params(method_type);
1694         for (i = regnum = 0; i < n; i++) {
1695                 const arch_register_t *reg  = NULL;
1696                 ir_type               *tp   = get_method_param_type(method_type, i);
1697                 ir_mode               *mode = get_type_mode(tp);
1698
1699                 if (mode != NULL) {
1700                         reg  = ia32_get_RegParam_reg(cc, regnum, mode);
1701                 }
1702                 if (reg != NULL) {
1703                         be_abi_call_param_reg(abi, i, reg, ABI_CONTEXT_BOTH);
1704                         ++regnum;
1705                 } else {
1706                         /* Micro optimisation: if the mode is shorter than 4 bytes, load 4 bytes.
1707                          * movl has a shorter opcode than mov[sz][bw]l */
1708                         ir_mode *load_mode = mode;
1709
1710                         if (mode != NULL) {
1711                                 unsigned size = get_mode_size_bytes(mode);
1712
1713                                 if (cc & cc_callee_clear_stk) {
1714                                         pop_amount += (size + 3U) & ~3U;
1715                                 }
1716
1717                                 if (size < 4) load_mode = mode_Iu;
1718                         }
1719
1720                         be_abi_call_param_stack(abi, i, load_mode, 4, 0, 0, ABI_CONTEXT_BOTH);
1721                 }
1722         }
1723
1724         be_abi_call_set_pop(abi, pop_amount);
1725
1726         /* set return registers */
1727         n = get_method_n_ress(method_type);
1728
1729         assert(n <= 2 && "more than two results not supported");
1730
1731         /* In case of 64bit returns, we will have two 32bit values */
1732         if (n == 2) {
1733                 ir_type *tp   = get_method_res_type(method_type, 0);
1734                 ir_mode *mode = get_type_mode(tp);
1735
1736                 assert(!mode_is_float(mode) && "two FP results not supported");
1737
1738                 tp   = get_method_res_type(method_type, 1);
1739                 mode = get_type_mode(tp);
1740
1741                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
1742
1743                 be_abi_call_res_reg(abi, 0, &ia32_registers[REG_EAX], ABI_CONTEXT_BOTH);
1744                 be_abi_call_res_reg(abi, 1, &ia32_registers[REG_EDX], ABI_CONTEXT_BOTH);
1745         }
1746         else if (n == 1) {
1747                 ir_type *tp   = get_method_res_type(method_type, 0);
1748                 ir_mode *mode = get_type_mode(tp);
1749                 const arch_register_t *reg;
1750                 assert(is_atomic_type(tp));
1751
1752                 reg = mode_is_float(mode) ? &ia32_registers[REG_VF0] : &ia32_registers[REG_EAX];
1753
1754                 be_abi_call_res_reg(abi, 0, reg, ABI_CONTEXT_BOTH);
1755         }
1756 }
1757
1758 static void ia32_mark_remat(ir_node *node)
1759 {
1760         if (is_ia32_irn(node)) {
1761                 set_ia32_is_remat(node);
1762         }
1763 }
1764
1765 /**
1766  * Check if Mux(sel, mux_true, mux_false) would represent a Max or Min operation
1767  */
1768 static bool mux_is_float_min_max(ir_node *sel, ir_node *mux_true,
1769                                  ir_node *mux_false)
1770 {
1771         ir_node    *cmp_l;
1772         ir_node    *cmp_r;
1773         ir_relation relation;
1774
1775         if (!is_Cmp(sel))
1776                 return false;
1777
1778         cmp_l = get_Cmp_left(sel);
1779         cmp_r = get_Cmp_right(sel);
1780         if (!mode_is_float(get_irn_mode(cmp_l)))
1781                 return false;
1782
1783         /* check for min/max. They're defined as (C-Semantik):
1784          *  min(a, b) = a < b ? a : b
1785          *  or min(a, b) = a <= b ? a : b
1786          *  max(a, b) = a > b ? a : b
1787          *  or max(a, b) = a >= b ? a : b
1788          * (Note we only handle float min/max here)
1789          */
1790         relation = get_Cmp_relation(sel);
1791         switch (relation) {
1792         case ir_relation_greater_equal:
1793         case ir_relation_greater:
1794                 /* this is a max */
1795                 if (cmp_l == mux_true && cmp_r == mux_false)
1796                         return true;
1797                 break;
1798         case ir_relation_less_equal:
1799         case ir_relation_less:
1800                 /* this is a min */
1801                 if (cmp_l == mux_true && cmp_r == mux_false)
1802                         return true;
1803                 break;
1804         case ir_relation_unordered_greater_equal:
1805         case ir_relation_unordered_greater:
1806                 /* this is a min */
1807                 if (cmp_l == mux_false && cmp_r == mux_true)
1808                         return true;
1809                 break;
1810         case ir_relation_unordered_less_equal:
1811         case ir_relation_unordered_less:
1812                 /* this is a max */
1813                 if (cmp_l == mux_false && cmp_r == mux_true)
1814                         return true;
1815                 break;
1816
1817         default:
1818                 break;
1819         }
1820
1821         return false;
1822 }
1823
1824 static bool mux_is_set(ir_node *sel, ir_node *mux_true, ir_node *mux_false)
1825 {
1826         ir_mode *mode = get_irn_mode(mux_true);
1827         (void) sel;
1828
1829         if (!mode_is_int(mode) && !mode_is_reference(mode)
1830                         && mode != mode_b)
1831                 return false;
1832
1833         if (is_Const(mux_true) && is_Const(mux_false)) {
1834                 /* we can create a set plus up two 3 instructions for any combination
1835                  * of constants */
1836                 return true;
1837         }
1838
1839         return false;
1840 }
1841
1842 static bool mux_is_float_const_const(ir_node *sel, ir_node *mux_true,
1843                                      ir_node *mux_false)
1844 {
1845         (void) sel;
1846
1847         if (!mode_is_float(get_irn_mode(mux_true)))
1848                 return false;
1849
1850         return is_Const(mux_true) && is_Const(mux_false);
1851 }
1852
1853 static bool mux_is_doz(ir_node *sel, ir_node *mux_true, ir_node *mux_false)
1854 {
1855         ir_node    *cmp_left;
1856         ir_node    *cmp_right;
1857         ir_node    *sub_left;
1858         ir_node    *sub_right;
1859         ir_mode    *mode;
1860         ir_relation relation;
1861
1862         if (!is_Cmp(sel))
1863                 return false;
1864
1865         mode = get_irn_mode(mux_true);
1866         if (mode_is_signed(mode) || mode_is_float(mode))
1867                 return false;
1868
1869         relation  = get_Cmp_relation(sel);
1870         cmp_left  = get_Cmp_left(sel);
1871         cmp_right = get_Cmp_right(sel);
1872
1873         /* "move" zero constant to false input */
1874         if (is_Const(mux_true) && is_Const_null(mux_true)) {
1875                 ir_node *tmp = mux_false;
1876                 mux_false = mux_true;
1877                 mux_true  = tmp;
1878                 relation = get_negated_relation(relation);
1879         }
1880         if (!is_Const(mux_false) || !is_Const_null(mux_false))
1881                 return false;
1882         if (!is_Sub(mux_true))
1883                 return false;
1884         sub_left  = get_Sub_left(mux_true);
1885         sub_right = get_Sub_right(mux_true);
1886
1887         /* Mux(a >=u b, 0, a-b) */
1888         if ((relation & ir_relation_greater)
1889                         && sub_left == cmp_left && sub_right == cmp_right)
1890                 return true;
1891         /* Mux(a <=u b, 0, b-a) */
1892         if ((relation & ir_relation_less)
1893                         && sub_left == cmp_right && sub_right == cmp_left)
1894                 return true;
1895
1896         return false;
1897 }
1898
1899 static int ia32_is_mux_allowed(ir_node *sel, ir_node *mux_false,
1900                                ir_node *mux_true)
1901 {
1902         ir_mode *mode;
1903
1904         /* middleend can handle some things */
1905         if (ir_is_optimizable_mux(sel, mux_false, mux_true))
1906                 return true;
1907         /* we can handle Set for all modes and compares */
1908         if (mux_is_set(sel, mux_true, mux_false))
1909                 return true;
1910         /* SSE has own min/max operations */
1911         if (ia32_cg_config.use_sse2
1912                         && mux_is_float_min_max(sel, mux_true, mux_false))
1913                 return true;
1914         /* we can handle Mux(?, Const[f], Const[f]) */
1915         if (mux_is_float_const_const(sel, mux_true, mux_false)) {
1916 #ifdef FIRM_GRGEN_BE
1917                 /* well, some code selectors can't handle it */
1918                 if (be_transformer != TRANSFORMER_PBQP
1919                                 || be_transformer != TRANSFORMER_RAND)
1920                         return true;
1921 #else
1922                 return true;
1923 #endif
1924         }
1925
1926         /* no support for 64bit inputs to cmov */
1927         mode = get_irn_mode(mux_true);
1928         if (get_mode_size_bits(mode) > 32)
1929                 return false;
1930         /* we can handle Abs for all modes and compares (except 64bit) */
1931         if (ir_mux_is_abs(sel, mux_false, mux_true) != 0)
1932                 return true;
1933         /* we can't handle MuxF yet */
1934         if (mode_is_float(mode))
1935                 return false;
1936
1937         if (mux_is_doz(sel, mux_true, mux_false))
1938                 return true;
1939
1940         /* Check Cmp before the node */
1941         if (is_Cmp(sel)) {
1942                 ir_mode *cmp_mode = get_irn_mode(get_Cmp_left(sel));
1943
1944                 /* we can't handle 64bit compares */
1945                 if (get_mode_size_bits(cmp_mode) > 32)
1946                         return false;
1947
1948                 /* we can't handle float compares */
1949                 if (mode_is_float(cmp_mode))
1950                         return false;
1951         }
1952
1953         /* did we disable cmov generation? */
1954         if (!ia32_cg_config.use_cmov)
1955                 return false;
1956
1957         /* we can use a cmov */
1958         return true;
1959 }
1960
1961 static asm_constraint_flags_t ia32_parse_asm_constraint(const char **c)
1962 {
1963         (void) c;
1964
1965         /* we already added all our simple flags to the flags modifier list in
1966          * init, so this flag we don't know. */
1967         return ASM_CONSTRAINT_FLAG_INVALID;
1968 }
1969
1970 static int ia32_is_valid_clobber(const char *clobber)
1971 {
1972         return ia32_get_clobber_register(clobber) != NULL;
1973 }
1974
1975 static void ia32_lower_for_target(void)
1976 {
1977         size_t i, n_irgs = get_irp_n_irgs();
1978
1979         /* perform doubleword lowering */
1980         lwrdw_param_t lower_dw_params = {
1981                 1,  /* little endian */
1982                 64, /* doubleword size */
1983                 ia32_create_intrinsic_fkt,
1984                 &intrinsic_env,
1985         };
1986
1987         ia32_create_opcodes(&ia32_irn_ops);
1988
1989         /* lower compound param handling
1990          * Note: we lower compound arguments ourself, since on ia32 we don't
1991          * have hidden parameters but know where to find the structs on the stack.
1992          * (This also forces us to always allocate space for the compound arguments
1993          *  on the callframe and we can't just use an arbitrary position on the
1994          *  stackframe)
1995          */
1996         lower_calls_with_compounds(LF_RETURN_HIDDEN | LF_DONT_LOWER_ARGUMENTS);
1997
1998         /* replace floating point operations by function calls */
1999         if (ia32_cg_config.use_softfloat) {
2000                 lower_floating_point();
2001         }
2002
2003         ir_prepare_dw_lowering(&lower_dw_params);
2004         ir_lower_dw_ops();
2005
2006         for (i = 0; i < n_irgs; ++i) {
2007                 ir_graph *irg = get_irp_irg(i);
2008                 /* lower for mode_b stuff */
2009                 ir_lower_mode_b(irg, mode_Iu);
2010                 /* break up switches with wide ranges */
2011                 lower_switch(irg, 4, 256, false);
2012         }
2013
2014         for (i = 0; i < n_irgs; ++i) {
2015                 ir_graph *irg = get_irp_irg(i);
2016                 /* Turn all small CopyBs into loads/stores, keep medium-sized CopyBs,
2017                  * so we can generate rep movs later, and turn all big CopyBs into
2018                  * memcpy calls. */
2019                 lower_CopyB(irg, 64, 8193, true);
2020         }
2021 }
2022
2023 /**
2024  * Create the trampoline code.
2025  */
2026 static ir_node *ia32_create_trampoline_fkt(ir_node *block, ir_node *mem, ir_node *trampoline, ir_node *env, ir_node *callee)
2027 {
2028         ir_graph *const irg  = get_irn_irg(block);
2029         ir_node  *      p    = trampoline;
2030         ir_mode  *const mode = get_irn_mode(p);
2031         ir_node  *const one  = new_r_Const(irg, get_mode_one(mode_Iu));
2032         ir_node  *const four = new_r_Const_long(irg, mode_Iu, 4);
2033         ir_node  *      st;
2034
2035         /* mov  ecx,<env> */
2036         st  = new_r_Store(block, mem, p, new_r_Const_long(irg, mode_Bu, 0xb9), cons_none);
2037         mem = new_r_Proj(st, mode_M, pn_Store_M);
2038         p   = new_r_Add(block, p, one, mode);
2039         st  = new_r_Store(block, mem, p, env, cons_none);
2040         mem = new_r_Proj(st, mode_M, pn_Store_M);
2041         p   = new_r_Add(block, p, four, mode);
2042         /* jmp  <callee> */
2043         st  = new_r_Store(block, mem, p, new_r_Const_long(irg, mode_Bu, 0xe9), cons_none);
2044         mem = new_r_Proj(st, mode_M, pn_Store_M);
2045         p   = new_r_Add(block, p, one, mode);
2046         st  = new_r_Store(block, mem, p, callee, cons_none);
2047         mem = new_r_Proj(st, mode_M, pn_Store_M);
2048         p   = new_r_Add(block, p, four, mode);
2049
2050         return mem;
2051 }
2052
2053 /**
2054  * Returns the libFirm configuration parameter for this backend.
2055  */
2056 static const backend_params *ia32_get_libfirm_params(void)
2057 {
2058         static const ir_settings_arch_dep_t ad = {
2059                 1,                   /* also use subs */
2060                 4,                   /* maximum shifts */
2061                 63,                  /* maximum shift amount */
2062                 ia32_evaluate_insn,  /* evaluate the instruction sequence */
2063
2064                 1,  /* allow Mulhs */
2065                 1,  /* allow Mulus */
2066                 32, /* Mulh allowed up to 32 bit */
2067         };
2068         static backend_params p = {
2069                 1,     /* support inline assembly */
2070                 1,     /* support Rotl nodes */
2071                 0,     /* little endian */
2072                 1,     /* modulo shift efficient */
2073                 0,     /* non-modulo shift not efficient */
2074                 &ad,   /* will be set later */
2075                 ia32_is_mux_allowed,
2076                 32,    /* machine_size */
2077                 NULL,  /* float arithmetic mode, will be set below */
2078                 NULL,  /* long long type */
2079                 NULL,  /* unsigned long long type */
2080                 NULL,  /* long double type */
2081                 12,    /* size of trampoline code */
2082                 4,     /* alignment of trampoline code */
2083                 ia32_create_trampoline_fkt,
2084                 4      /* alignment of stack parameter */
2085         };
2086
2087         if (ia32_mode_E == NULL) {
2088                 /* note mantissa is 64bit but with explicitely encoded 1 so the really
2089                  * usable part as counted by firm is only 63 bits */
2090                 ia32_mode_E = new_float_mode("E", irma_x86_extended_float, 15, 63);
2091                 ia32_type_E = new_type_primitive(ia32_mode_E);
2092                 set_type_size_bytes(ia32_type_E, 12);
2093                 set_type_alignment_bytes(ia32_type_E, 16);
2094         }
2095
2096         ir_mode *mode_long_long
2097                 = new_int_mode("long long", irma_twos_complement, 64, 1, 64);
2098         ir_type *type_long_long = new_type_primitive(mode_long_long);
2099         ir_mode *mode_unsigned_long_long
2100                 = new_int_mode("unsigned long long", irma_twos_complement, 64, 0, 64);
2101         ir_type *type_unsigned_long_long
2102                 = new_type_primitive(mode_unsigned_long_long);
2103
2104         ia32_setup_cg_config();
2105
2106         /* doesn't really belong here, but this is the earliest place the backend
2107          * is called... */
2108         init_asm_constraints();
2109
2110         p.type_long_long          = type_long_long;
2111         p.type_unsigned_long_long = type_unsigned_long_long;
2112
2113         if (ia32_cg_config.use_sse2 || ia32_cg_config.use_softfloat) {
2114                 p.mode_float_arithmetic = NULL;
2115                 p.type_long_double = NULL;
2116         } else {
2117                 p.mode_float_arithmetic = ia32_mode_E;
2118                 p.type_long_double      = ia32_type_E;
2119         }
2120         return &p;
2121 }
2122
2123 /**
2124  * Check if the given register is callee or caller save.
2125  */
2126 static int ia32_register_saved_by(const arch_register_t *reg, int callee)
2127 {
2128         if (callee) {
2129                 /* check for callee saved */
2130                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_gp]) {
2131                         switch (reg->index) {
2132                         case REG_GP_EBX:
2133                         case REG_GP_ESI:
2134                         case REG_GP_EDI:
2135                         case REG_GP_EBP:
2136                                 return 1;
2137                         default:
2138                                 return 0;
2139                         }
2140                 }
2141         } else {
2142                 /* check for caller saved */
2143                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_gp]) {
2144                         switch (reg->index) {
2145                         case REG_GP_EDX:
2146                         case REG_GP_ECX:
2147                         case REG_GP_EAX:
2148                                 return 1;
2149                         default:
2150                                 return 0;
2151                         }
2152                 } else if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_xmm]) {
2153                         /* all XMM registers are caller save */
2154                         return reg->index != REG_XMM_NOREG;
2155                 } else if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]) {
2156                         /* all VFP registers are caller save */
2157                         return reg->index != REG_VFP_NOREG;
2158                 }
2159         }
2160         return 0;
2161 }
2162
2163 static const lc_opt_enum_int_items_t gas_items[] = {
2164         { "elf",   OBJECT_FILE_FORMAT_ELF    },
2165         { "mingw", OBJECT_FILE_FORMAT_COFF   },
2166         { "macho", OBJECT_FILE_FORMAT_MACH_O },
2167         { NULL,    0 }
2168 };
2169
2170 static lc_opt_enum_int_var_t gas_var = {
2171         (int*) &be_gas_object_file_format, gas_items
2172 };
2173
2174 #ifdef FIRM_GRGEN_BE
2175 static const lc_opt_enum_int_items_t transformer_items[] = {
2176         { "default", TRANSFORMER_DEFAULT },
2177         { "pbqp",    TRANSFORMER_PBQP    },
2178         { "random",  TRANSFORMER_RAND    },
2179         { NULL,      0                   }
2180 };
2181
2182 static lc_opt_enum_int_var_t transformer_var = {
2183         (int*)&be_transformer, transformer_items
2184 };
2185 #endif
2186
2187 static const lc_opt_table_entry_t ia32_options[] = {
2188         LC_OPT_ENT_ENUM_INT("gasmode", "set the GAS compatibility mode", &gas_var),
2189 #ifdef FIRM_GRGEN_BE
2190         LC_OPT_ENT_ENUM_INT("transformer", "the transformer used for code selection", &transformer_var),
2191 #endif
2192         LC_OPT_ENT_INT ("stackalign", "set power of two stack alignment for calls",
2193                         &ia32_isa_template.base.stack_alignment),
2194         LC_OPT_ENT_BOOL("gprof",      "create gprof profiling code",                                    &gprof),
2195         LC_OPT_LAST
2196 };
2197
2198 const arch_isa_if_t ia32_isa_if = {
2199         ia32_init,
2200         ia32_lower_for_target,
2201         ia32_done,
2202         ia32_handle_intrinsics,
2203         ia32_get_call_abi,
2204         ia32_get_libfirm_params,
2205         ia32_mark_remat,
2206         ia32_parse_asm_constraint,
2207         ia32_is_valid_clobber,
2208
2209         ia32_init_graph,
2210         ia32_get_pic_base,   /* return node used as base in pic code addresses */
2211         ia32_before_abi,     /* before abi introduce hook */
2212         ia32_prepare_graph,
2213         ia32_before_ra,      /* before register allocation hook */
2214         ia32_finish,         /* called before codegen */
2215         ia32_emit,           /* emit && done */
2216         ia32_register_saved_by,
2217         be_new_spill,
2218         be_new_reload
2219 };
2220
2221 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_ia32)
2222 void be_init_arch_ia32(void)
2223 {
2224         lc_opt_entry_t *be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2225         lc_opt_entry_t *ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2226
2227         lc_opt_add_table(ia32_grp, ia32_options);
2228         be_register_isa_if("ia32", &ia32_isa_if);
2229
2230         ia32_init_emitter();
2231         ia32_init_finish();
2232         ia32_init_optimize();
2233         ia32_init_transform();
2234         ia32_init_x87();
2235         ia32_init_architecture();
2236 }