add Linux grof support
[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  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "lc_opts.h"
31 #include "lc_opts_enum.h"
32
33 #include <math.h>
34
35 #include "pseudo_irg.h"
36 #include "irarch.h"
37 #include "irgwalk.h"
38 #include "irprog.h"
39 #include "irprintf.h"
40 #include "iredges_t.h"
41 #include "ircons.h"
42 #include "irgmod.h"
43 #include "irgopt.h"
44 #include "irbitset.h"
45 #include "irgopt.h"
46 #include "irdump_grgen.h"
47 #include "pdeq.h"
48 #include "pset.h"
49 #include "debug.h"
50 #include "error.h"
51 #include "xmalloc.h"
52 #include "irtools.h"
53 #include "iroptimize.h"
54 #include "instrument.h"
55
56 #include "../beabi.h"
57 #include "../beirg_t.h"
58 #include "../benode_t.h"
59 #include "../belower.h"
60 #include "../besched_t.h"
61 #include "be.h"
62 #include "../be_t.h"
63 #include "../beirgmod.h"
64 #include "../be_dbgout.h"
65 #include "../beblocksched.h"
66 #include "../bemachine.h"
67 #include "../beilpsched.h"
68 #include "../bespillslots.h"
69 #include "../bemodule.h"
70 #include "../begnuas.h"
71 #include "../bestate.h"
72 #include "../beflags.h"
73
74 #include "bearch_ia32_t.h"
75
76 #include "ia32_new_nodes.h"
77 #include "gen_ia32_regalloc_if.h"
78 #include "gen_ia32_machine.h"
79 #include "ia32_transform.h"
80 #include "ia32_emitter.h"
81 #include "ia32_map_regs.h"
82 #include "ia32_optimize.h"
83 #include "ia32_x87.h"
84 #include "ia32_dbg_stat.h"
85 #include "ia32_finish.h"
86 #include "ia32_util.h"
87 #include "ia32_fpu.h"
88 #include "ia32_architecture.h"
89
90 #ifdef FIRM_GRGEN_BE
91 #include "ia32_pbqp_transform.h"
92 #endif
93
94 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
95
96 /* TODO: ugly */
97 static set *cur_reg_set = NULL;
98
99 ir_mode         *mode_fpcw       = NULL;
100 ia32_code_gen_t *ia32_current_cg = NULL;
101
102 /**
103  * The environment for the intrinsic mapping.
104  */
105 static ia32_intrinsic_env_t intrinsic_env = {
106         NULL,    /* the isa */
107         NULL,    /* the irg, these entities belong to */
108         NULL,    /* entity for first div operand (move into FPU) */
109         NULL,    /* entity for second div operand (move into FPU) */
110         NULL,    /* entity for converts ll -> d */
111         NULL,    /* entity for converts d -> ll */
112         NULL,    /* entity for __divdi3 library call */
113         NULL,    /* entity for __moddi3 library call */
114         NULL,    /* entity for __udivdi3 library call */
115         NULL,    /* entity for __umoddi3 library call */
116         NULL,    /* bias value for conversion from float to unsigned 64 */
117 };
118
119
120 typedef ir_node *(*create_const_node_func) (dbg_info *dbg, ir_graph *irg, ir_node *block);
121
122 static INLINE ir_node *create_const(ia32_code_gen_t *cg, ir_node **place,
123                                     create_const_node_func func,
124                                     const arch_register_t* reg)
125 {
126         ir_node *block, *res;
127
128         if(*place != NULL)
129                 return *place;
130
131         block = get_irg_start_block(cg->irg);
132         res = func(NULL, cg->irg, block);
133         arch_set_irn_register(cg->arch_env, res, reg);
134         *place = res;
135
136         add_irn_dep(get_irg_end(cg->irg), res);
137         /* add_irn_dep(get_irg_start(cg->irg), res); */
138
139         return res;
140 }
141
142 /* Creates the unique per irg GP NoReg node. */
143 ir_node *ia32_new_NoReg_gp(ia32_code_gen_t *cg) {
144         return create_const(cg, &cg->noreg_gp, new_rd_ia32_NoReg_GP,
145                             &ia32_gp_regs[REG_GP_NOREG]);
146 }
147
148 ir_node *ia32_new_NoReg_vfp(ia32_code_gen_t *cg) {
149         return create_const(cg, &cg->noreg_vfp, new_rd_ia32_NoReg_VFP,
150                             &ia32_vfp_regs[REG_VFP_NOREG]);
151 }
152
153 ir_node *ia32_new_NoReg_xmm(ia32_code_gen_t *cg) {
154         return create_const(cg, &cg->noreg_xmm, new_rd_ia32_NoReg_XMM,
155                             &ia32_xmm_regs[REG_XMM_NOREG]);
156 }
157
158 ir_node *ia32_new_Unknown_gp(ia32_code_gen_t *cg) {
159         return create_const(cg, &cg->unknown_gp, new_rd_ia32_Unknown_GP,
160                             &ia32_gp_regs[REG_GP_UKNWN]);
161 }
162
163 ir_node *ia32_new_Unknown_vfp(ia32_code_gen_t *cg) {
164         return create_const(cg, &cg->unknown_vfp, new_rd_ia32_Unknown_VFP,
165                             &ia32_vfp_regs[REG_VFP_UKNWN]);
166 }
167
168 ir_node *ia32_new_Unknown_xmm(ia32_code_gen_t *cg) {
169         return create_const(cg, &cg->unknown_xmm, new_rd_ia32_Unknown_XMM,
170                             &ia32_xmm_regs[REG_XMM_UKNWN]);
171 }
172
173 ir_node *ia32_new_Fpu_truncate(ia32_code_gen_t *cg) {
174         return create_const(cg, &cg->fpu_trunc_mode, new_rd_ia32_ChangeCW,
175                         &ia32_fp_cw_regs[REG_FPCW]);
176 }
177
178
179 /**
180  * Returns gp_noreg or fp_noreg, depending in input requirements.
181  */
182 ir_node *ia32_get_admissible_noreg(ia32_code_gen_t *cg, ir_node *irn, int pos) {
183         const arch_register_req_t *req;
184
185         req = arch_get_register_req(cg->arch_env, irn, pos);
186         assert(req != NULL && "Missing register requirements");
187         if (req->cls == &ia32_reg_classes[CLASS_ia32_gp])
188                 return ia32_new_NoReg_gp(cg);
189
190         if (ia32_cg_config.use_sse2) {
191                 return ia32_new_NoReg_xmm(cg);
192         } else {
193                 return ia32_new_NoReg_vfp(cg);
194         }
195 }
196
197 /**************************************************
198  *                         _ _              _  __
199  *                        | | |            (_)/ _|
200  *  _ __ ___  __ _    __ _| | | ___   ___   _| |_
201  * | '__/ _ \/ _` |  / _` | | |/ _ \ / __| | |  _|
202  * | | |  __/ (_| | | (_| | | | (_) | (__  | | |
203  * |_|  \___|\__, |  \__,_|_|_|\___/ \___| |_|_|
204  *            __/ |
205  *           |___/
206  **************************************************/
207
208 /**
209  * Return register requirements for an ia32 node.
210  * If the node returns a tuple (mode_T) then the proj's
211  * will be asked for this information.
212  */
213 static const arch_register_req_t *ia32_get_irn_reg_req(const void *self,
214                                                        const ir_node *node,
215                                                                                                            int pos)
216 {
217         long node_pos = pos == -1 ? 0 : pos;
218         ir_mode *mode     = is_Block(node) ? NULL : get_irn_mode(node);
219         (void) self;
220
221         if (is_Block(node) || mode == mode_X) {
222                 return arch_no_register_req;
223         }
224
225         if (mode == mode_T && pos < 0) {
226                 return arch_no_register_req;
227         }
228
229         if (is_Proj(node)) {
230                 if(mode == mode_M)
231                         return arch_no_register_req;
232
233                 if(pos >= 0) {
234                         return arch_no_register_req;
235                 }
236
237                 node_pos = (pos == -1) ? get_Proj_proj(node) : pos;
238                 node     = skip_Proj_const(node);
239         }
240
241         if (is_ia32_irn(node)) {
242                 const arch_register_req_t *req;
243                 if(pos >= 0)
244                         req = get_ia32_in_req(node, pos);
245                 else
246                         req = get_ia32_out_req(node, node_pos);
247
248                 assert(req != NULL);
249
250                 return req;
251         }
252
253         /* unknowns should be transformed already */
254         assert(!is_Unknown(node));
255
256         return arch_no_register_req;
257 }
258
259 static void ia32_set_irn_reg(const void *self, ir_node *irn,
260                              const arch_register_t *reg)
261 {
262         int                   pos = 0;
263         (void) self;
264
265         if (get_irn_mode(irn) == mode_X) {
266                 return;
267         }
268
269         if (is_Proj(irn)) {
270                 pos = get_Proj_proj(irn);
271                 irn = skip_Proj(irn);
272         }
273
274         if (is_ia32_irn(irn)) {
275                 const arch_register_t **slots;
276
277                 slots      = get_ia32_slots(irn);
278                 slots[pos] = reg;
279         } else {
280                 ia32_set_firm_reg(irn, reg, cur_reg_set);
281         }
282 }
283
284 static const arch_register_t *ia32_get_irn_reg(const void *self,
285                                                const ir_node *irn)
286 {
287         int pos = 0;
288         const arch_register_t *reg = NULL;
289         (void) self;
290
291         if (is_Proj(irn)) {
292
293                 if (get_irn_mode(irn) == mode_X) {
294                         return NULL;
295                 }
296
297                 pos = get_Proj_proj(irn);
298                 irn = skip_Proj_const(irn);
299         }
300
301         if (is_ia32_irn(irn)) {
302                 const arch_register_t **slots;
303                 slots = get_ia32_slots(irn);
304                 assert(pos < get_ia32_n_res(irn));
305                 reg   = slots[pos];
306         } else {
307                 reg = ia32_get_firm_reg(irn, cur_reg_set);
308         }
309
310         return reg;
311 }
312
313 static arch_irn_class_t ia32_classify(const void *self, const ir_node *irn) {
314         arch_irn_class_t classification = arch_irn_class_normal;
315         (void) self;
316
317         irn = skip_Proj_const(irn);
318
319         if (is_cfop(irn))
320                 classification |= arch_irn_class_branch;
321
322         if (! is_ia32_irn(irn))
323                 return classification & ~arch_irn_class_normal;
324
325         if (is_ia32_Ld(irn))
326                 classification |= arch_irn_class_load;
327
328         if (is_ia32_St(irn))
329                 classification |= arch_irn_class_store;
330
331         if (is_ia32_need_stackent(irn))
332                 classification |= arch_irn_class_reload;
333
334         return classification;
335 }
336
337 static arch_irn_flags_t ia32_get_flags(const void *self, const ir_node *irn) {
338         arch_irn_flags_t flags = arch_irn_flags_none;
339         (void) self;
340
341         if (is_Unknown(irn))
342                 return arch_irn_flags_ignore;
343
344         if(is_Proj(irn) && mode_is_datab(get_irn_mode(irn))) {
345                 ir_node *pred = get_Proj_pred(irn);
346
347                 if(is_ia32_irn(pred)) {
348                         flags = get_ia32_out_flags(pred, get_Proj_proj(irn));
349                 }
350
351                 irn = pred;
352         }
353
354         if (is_ia32_irn(irn)) {
355                 flags |= get_ia32_flags(irn);
356         }
357
358         return flags;
359 }
360
361 /**
362  * The IA32 ABI callback object.
363  */
364 typedef struct {
365         be_abi_call_flags_bits_t flags;  /**< The call flags. */
366         const arch_isa_t *isa;           /**< The ISA handle. */
367         const arch_env_t *aenv;          /**< The architecture environment. */
368         ir_graph *irg;                   /**< The associated graph. */
369 } ia32_abi_env_t;
370
371 static ir_entity *ia32_get_frame_entity(const void *self, const ir_node *irn) {
372         (void) self;
373         return is_ia32_irn(irn) ? get_ia32_frame_ent(irn) : NULL;
374 }
375
376 static void ia32_set_frame_entity(const void *self, ir_node *irn, ir_entity *ent) {
377         (void) self;
378         set_ia32_frame_ent(irn, ent);
379 }
380
381 static void ia32_set_frame_offset(const void *self, ir_node *irn, int bias)
382 {
383         const ia32_irn_ops_t *ops = self;
384
385         if (get_ia32_frame_ent(irn) == NULL)
386                 return;
387
388         if (is_ia32_Pop(irn)) {
389                 int omit_fp = be_abi_omit_fp(ops->cg->birg->abi);
390                 if (omit_fp) {
391                         /* Pop nodes modify the stack pointer before calculating the
392                          * destination address, so fix this here
393                          */
394                         bias -= 4;
395                 }
396         }
397         add_ia32_am_offs_int(irn, bias);
398 }
399
400 static int ia32_get_sp_bias(const void *self, const ir_node *node)
401 {
402         (void) self;
403
404         if (is_ia32_Push(node))
405                 return 4;
406
407         if (is_ia32_Pop(node))
408                 return -4;
409
410         return 0;
411 }
412
413 /**
414  * Put all registers which are saved by the prologue/epilogue in a set.
415  *
416  * @param self  The callback object.
417  * @param s     The result set.
418  */
419 static void ia32_abi_dont_save_regs(void *self, pset *s)
420 {
421         ia32_abi_env_t *env = self;
422         if(env->flags.try_omit_fp)
423                 pset_insert_ptr(s, env->isa->bp);
424 }
425
426 /**
427  * Generate the routine prologue.
428  *
429  * @param self    The callback object.
430  * @param mem     A pointer to the mem node. Update this if you define new memory.
431  * @param reg_map A map mapping all callee_save/ignore/parameter registers to their defining nodes.
432  *
433  * @return        The register which shall be used as a stack frame base.
434  *
435  * All nodes which define registers in @p reg_map must keep @p reg_map current.
436  */
437 static const arch_register_t *ia32_abi_prologue(void *self, ir_node **mem, pmap *reg_map)
438 {
439         ia32_abi_env_t *env = self;
440         const ia32_isa_t *isa     = (ia32_isa_t *)env->isa;
441         ia32_code_gen_t *cg = isa->cg;
442
443         if (! env->flags.try_omit_fp) {
444                 ir_node *bl      = get_irg_start_block(env->irg);
445                 ir_node *curr_sp = be_abi_reg_map_get(reg_map, env->isa->sp);
446                 ir_node *curr_bp = be_abi_reg_map_get(reg_map, env->isa->bp);
447                 ir_node *noreg = ia32_new_NoReg_gp(cg);
448                 ir_node *push;
449
450                 /* ALL nodes representing bp must be set to ignore. */
451                 be_node_set_flags(get_Proj_pred(curr_bp), BE_OUT_POS(get_Proj_proj(curr_bp)), arch_irn_flags_ignore);
452
453                 /* push ebp */
454                 push    = new_rd_ia32_Push(NULL, env->irg, bl, noreg, noreg, *mem, curr_sp, curr_bp);
455                 curr_sp = new_r_Proj(env->irg, bl, push, get_irn_mode(curr_sp), pn_ia32_Push_stack);
456                 *mem    = new_r_Proj(env->irg, bl, push, mode_M, pn_ia32_Push_M);
457
458                 /* the push must have SP out register */
459                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
460                 set_ia32_flags(push, arch_irn_flags_ignore);
461
462                 /* move esp to ebp */
463                 curr_bp  = be_new_Copy(env->isa->bp->reg_class, env->irg, bl, curr_sp);
464                 be_set_constr_single_reg(curr_bp, BE_OUT_POS(0), env->isa->bp);
465                 arch_set_irn_register(env->aenv, curr_bp, env->isa->bp);
466                 be_node_set_flags(curr_bp, BE_OUT_POS(0), arch_irn_flags_ignore);
467
468                 /* beware: the copy must be done before any other sp use */
469                 curr_sp = be_new_CopyKeep_single(env->isa->sp->reg_class, env->irg, bl, curr_sp, curr_bp, get_irn_mode(curr_sp));
470                 be_set_constr_single_reg(curr_sp, BE_OUT_POS(0), env->isa->sp);
471                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
472                 be_node_set_flags(curr_sp, BE_OUT_POS(0), arch_irn_flags_ignore);
473
474                 be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
475                 be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
476
477                 return env->isa->bp;
478         }
479
480         return env->isa->sp;
481 }
482
483 /**
484  * Generate the routine epilogue.
485  * @param self    The callback object.
486  * @param bl      The block for the epilog
487  * @param mem     A pointer to the mem node. Update this if you define new memory.
488  * @param reg_map A map mapping all callee_save/ignore/parameter registers to their defining nodes.
489  * @return        The register which shall be used as a stack frame base.
490  *
491  * All nodes which define registers in @p reg_map must keep @p reg_map current.
492  */
493 static void ia32_abi_epilogue(void *self, ir_node *bl, ir_node **mem, pmap *reg_map)
494 {
495         ia32_abi_env_t *env     = self;
496         ir_node        *curr_sp = be_abi_reg_map_get(reg_map, env->isa->sp);
497         ir_node        *curr_bp = be_abi_reg_map_get(reg_map, env->isa->bp);
498
499         if (env->flags.try_omit_fp) {
500                 /* simply remove the stack frame here */
501                 curr_sp = be_new_IncSP(env->isa->sp, env->irg, bl, curr_sp, BE_STACK_FRAME_SIZE_SHRINK, 0);
502                 add_irn_dep(curr_sp, *mem);
503         } else {
504                 const ia32_isa_t *isa     = (ia32_isa_t *)env->isa;
505                 ia32_code_gen_t *cg = isa->cg;
506                 ir_mode         *mode_bp = env->isa->bp->reg_class->mode;
507                 ir_graph        *irg     = current_ir_graph;
508
509                 if (ia32_cg_config.use_leave) {
510                         ir_node *leave;
511
512                         /* leave */
513                         leave   = new_rd_ia32_Leave(NULL, irg, bl, curr_sp, curr_bp);
514                         set_ia32_flags(leave, arch_irn_flags_ignore);
515                         curr_bp = new_r_Proj(irg, bl, leave, mode_bp, pn_ia32_Leave_frame);
516                         curr_sp = new_r_Proj(irg, bl, leave, get_irn_mode(curr_sp), pn_ia32_Leave_stack);
517                 } else {
518                         ir_node *noreg = ia32_new_NoReg_gp(cg);
519                         ir_node *pop;
520
521                         /* the old SP is not needed anymore (kill the proj) */
522                         assert(is_Proj(curr_sp));
523                         be_kill_node(curr_sp);
524
525                         /* copy ebp to esp */
526                         curr_sp = be_new_Copy(&ia32_reg_classes[CLASS_ia32_gp], irg, bl, curr_bp);
527                         arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
528                         be_node_set_flags(curr_sp, BE_OUT_POS(0), arch_irn_flags_ignore);
529
530                         /* pop ebp */
531                         pop     = new_rd_ia32_Pop(NULL, env->irg, bl, noreg, noreg, *mem, curr_sp);
532                         set_ia32_flags(pop, arch_irn_flags_ignore);
533                         curr_bp = new_r_Proj(irg, bl, pop, mode_bp, pn_ia32_Pop_res);
534                         curr_sp = new_r_Proj(irg, bl, pop, get_irn_mode(curr_sp), pn_ia32_Pop_stack);
535
536                         *mem = new_r_Proj(irg, bl, pop, mode_M, pn_ia32_Pop_M);
537                 }
538                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
539                 arch_set_irn_register(env->aenv, curr_bp, env->isa->bp);
540         }
541
542         be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
543         be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
544 }
545
546 /**
547  * Initialize the callback object.
548  * @param call The call object.
549  * @param aenv The architecture environment.
550  * @param irg  The graph with the method.
551  * @return     Some pointer. This pointer is passed to all other callback functions as self object.
552  */
553 static void *ia32_abi_init(const be_abi_call_t *call, const arch_env_t *aenv, ir_graph *irg)
554 {
555         ia32_abi_env_t *env    = xmalloc(sizeof(env[0]));
556         be_abi_call_flags_t fl = be_abi_call_get_flags(call);
557         env->flags = fl.bits;
558         env->irg   = irg;
559         env->aenv  = aenv;
560         env->isa   = aenv->isa;
561         return env;
562 }
563
564 /**
565  * Destroy the callback object.
566  * @param self The callback object.
567  */
568 static void ia32_abi_done(void *self) {
569         free(self);
570 }
571
572 /**
573  * Produces the type which sits between the stack args and the locals on the stack.
574  * it will contain the return address and space to store the old base pointer.
575  * @return The Firm type modeling the ABI between type.
576  */
577 static ir_type *ia32_abi_get_between_type(void *self)
578 {
579 #define IDENT(s) new_id_from_chars(s, sizeof(s)-1)
580         static ir_type *omit_fp_between_type = NULL;
581         static ir_type *between_type         = NULL;
582
583         ia32_abi_env_t *env = self;
584
585         if (! between_type) {
586                 ir_entity *old_bp_ent;
587                 ir_entity *ret_addr_ent;
588                 ir_entity *omit_fp_ret_addr_ent;
589
590                 ir_type *old_bp_type   = new_type_primitive(IDENT("bp"), mode_Iu);
591                 ir_type *ret_addr_type = new_type_primitive(IDENT("return_addr"), mode_Iu);
592
593                 between_type           = new_type_struct(IDENT("ia32_between_type"));
594                 old_bp_ent             = new_entity(between_type, IDENT("old_bp"), old_bp_type);
595                 ret_addr_ent           = new_entity(between_type, IDENT("ret_addr"), ret_addr_type);
596
597                 set_entity_offset(old_bp_ent, 0);
598                 set_entity_offset(ret_addr_ent, get_type_size_bytes(old_bp_type));
599                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
600                 set_type_state(between_type, layout_fixed);
601
602                 omit_fp_between_type = new_type_struct(IDENT("ia32_between_type_omit_fp"));
603                 omit_fp_ret_addr_ent = new_entity(omit_fp_between_type, IDENT("ret_addr"), ret_addr_type);
604
605                 set_entity_offset(omit_fp_ret_addr_ent, 0);
606                 set_type_size_bytes(omit_fp_between_type, get_type_size_bytes(ret_addr_type));
607                 set_type_state(omit_fp_between_type, layout_fixed);
608         }
609
610         return env->flags.try_omit_fp ? omit_fp_between_type : between_type;
611 #undef IDENT
612 }
613
614 /**
615  * Get the estimated cycle count for @p irn.
616  *
617  * @param self The this pointer.
618  * @param irn  The node.
619  *
620  * @return     The estimated cycle count for this operation
621  */
622 static int ia32_get_op_estimated_cost(const void *self, const ir_node *irn)
623 {
624         int            cost;
625         ia32_op_type_t op_tp;
626         (void) self;
627
628         if (is_Proj(irn))
629                 return 0;
630         if (!is_ia32_irn(irn))
631                 return 0;
632
633         assert(is_ia32_irn(irn));
634
635         cost  = get_ia32_latency(irn);
636         op_tp = get_ia32_op_type(irn);
637
638         if (is_ia32_CopyB(irn)) {
639                 cost = 250;
640         }
641         else if (is_ia32_CopyB_i(irn)) {
642                 int size = get_ia32_copyb_size(irn);
643                 cost     = 20 + (int)ceil((4/3) * size);
644         }
645         /* in case of address mode operations add additional cycles */
646         else if (op_tp == ia32_AddrModeD || op_tp == ia32_AddrModeS) {
647                 /*
648                         In case of stack access and access to fixed addresses add 5 cycles
649                         (we assume they are in cache), other memory operations cost 20
650                         cycles.
651                 */
652                 if(is_ia32_use_frame(irn) ||
653                                 (is_ia32_NoReg_GP(get_irn_n(irn, 0)) &&
654                          is_ia32_NoReg_GP(get_irn_n(irn, 1)))) {
655                         cost += 5;
656                 } else {
657                         cost += 20;
658                 }
659         }
660
661         return cost;
662 }
663
664 /**
665  * Returns the inverse operation if @p irn, recalculating the argument at position @p i.
666  *
667  * @param irn       The original operation
668  * @param i         Index of the argument we want the inverse operation to yield
669  * @param inverse   struct to be filled with the resulting inverse op
670  * @param obstack   The obstack to use for allocation of the returned nodes array
671  * @return          The inverse operation or NULL if operation invertible
672  */
673 static arch_inverse_t *ia32_get_inverse(const void *self, const ir_node *irn, int i, arch_inverse_t *inverse, struct obstack *obst) {
674         ir_graph *irg;
675         ir_mode  *mode;
676         ir_mode  *irn_mode;
677         ir_node  *block, *noreg, *nomem;
678         dbg_info *dbg;
679         (void) self;
680
681         /* we cannot invert non-ia32 irns */
682         if (! is_ia32_irn(irn))
683                 return NULL;
684
685         /* operand must always be a real operand (not base, index or mem) */
686         if (i != n_ia32_binary_left && i != n_ia32_binary_right)
687                 return NULL;
688
689         /* we don't invert address mode operations */
690         if (get_ia32_op_type(irn) != ia32_Normal)
691                 return NULL;
692
693         /* TODO: adjust for new immediates... */
694         ir_fprintf(stderr, "TODO: fix get_inverse for new immediates (%+F)\n",
695                    irn);
696         return NULL;
697
698         irg      = get_irn_irg(irn);
699         block    = get_nodes_block(irn);
700         mode     = get_irn_mode(irn);
701         irn_mode = get_irn_mode(irn);
702         noreg    = get_irn_n(irn, 0);
703         nomem    = new_r_NoMem(irg);
704         dbg      = get_irn_dbg_info(irn);
705
706         /* initialize structure */
707         inverse->nodes = obstack_alloc(obst, 2 * sizeof(inverse->nodes[0]));
708         inverse->costs = 0;
709         inverse->n     = 1;
710
711         switch (get_ia32_irn_opcode(irn)) {
712                 case iro_ia32_Add:
713 #if 0
714                         if (get_ia32_immop_type(irn) == ia32_ImmConst) {
715                                 /* we have an add with a const here */
716                                 /* invers == add with negated const */
717                                 inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
718                                 inverse->costs   += 1;
719                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
720                                 set_ia32_Immop_tarval(inverse->nodes[0], tarval_neg(get_ia32_Immop_tarval(irn)));
721                                 set_ia32_commutative(inverse->nodes[0]);
722                         }
723                         else if (get_ia32_immop_type(irn) == ia32_ImmSymConst) {
724                                 /* we have an add with a symconst here */
725                                 /* invers == sub with const */
726                                 inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
727                                 inverse->costs   += 2;
728                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
729                         }
730                         else {
731                                 /* normal add: inverse == sub */
732                                 inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, i ^ 1));
733                                 inverse->costs   += 2;
734                         }
735 #endif
736                         break;
737                 case iro_ia32_Sub:
738 #if 0
739                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
740                                 /* we have a sub with a const/symconst here */
741                                 /* invers == add with this const */
742                                 inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
743                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
744                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
745                         }
746                         else {
747                                 /* normal sub */
748                                 if (i == n_ia32_binary_left) {
749                                         inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, 3));
750                                 }
751                                 else {
752                                         inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, nomem, get_irn_n(irn, n_ia32_binary_left), (ir_node*) irn);
753                                 }
754                                 inverse->costs += 1;
755                         }
756 #endif
757                         break;
758                 case iro_ia32_Xor:
759 #if 0
760                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
761                                 /* xor with const: inverse = xor */
762                                 inverse->nodes[0] = new_rd_ia32_Xor(dbg, irg, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
763                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
764                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
765                         }
766                         else {
767                                 /* normal xor */
768                                 inverse->nodes[0] = new_rd_ia32_Xor(dbg, irg, block, noreg, noreg, nomem, (ir_node *) irn, get_irn_n(irn, i));
769                                 inverse->costs   += 1;
770                         }
771 #endif
772                         break;
773                 case iro_ia32_Not: {
774                         inverse->nodes[0] = new_rd_ia32_Not(dbg, irg, block, (ir_node*) irn);
775                         inverse->costs   += 1;
776                         break;
777                 }
778                 case iro_ia32_Neg: {
779                         inverse->nodes[0] = new_rd_ia32_Neg(dbg, irg, block, (ir_node*) irn);
780                         inverse->costs   += 1;
781                         break;
782                 }
783                 default:
784                         /* inverse operation not supported */
785                         return NULL;
786         }
787
788         return inverse;
789 }
790
791 static ir_mode *get_spill_mode_mode(const ir_mode *mode)
792 {
793         if(mode_is_float(mode))
794                 return mode_D;
795
796         return mode_Iu;
797 }
798
799 /**
800  * Get the mode that should be used for spilling value node
801  */
802 static ir_mode *get_spill_mode(const ir_node *node)
803 {
804         ir_mode *mode = get_irn_mode(node);
805         return get_spill_mode_mode(mode);
806 }
807
808 /**
809  * Checks whether an addressmode reload for a node with mode mode is compatible
810  * with a spillslot of mode spill_mode
811  */
812 static int ia32_is_spillmode_compatible(const ir_mode *mode, const ir_mode *spillmode)
813 {
814         if(mode_is_float(mode)) {
815                 return mode == spillmode;
816         } else {
817                 return 1;
818         }
819 }
820
821 /**
822  * Check if irn can load it's operand at position i from memory (source addressmode).
823  * @param self   Pointer to irn ops itself
824  * @param irn    The irn to be checked
825  * @param i      The operands position
826  * @return Non-Zero if operand can be loaded
827  */
828 static int ia32_possible_memory_operand(const void *self, const ir_node *irn, unsigned int i) {
829         ir_node *op = get_irn_n(irn, i);
830         const ir_mode *mode = get_irn_mode(op);
831         const ir_mode *spillmode = get_spill_mode(op);
832         (void) self;
833
834         if (! is_ia32_irn(irn)                                  ||  /* must be an ia32 irn */
835                 get_ia32_am_arity(irn) != ia32_am_binary              ||  /* must be a binary operation TODO is this necessary? */
836                 get_ia32_op_type(irn) != ia32_Normal                  ||  /* must not already be a addressmode irn */
837                 ! (get_ia32_am_support(irn) & ia32_am_Source)         ||  /* must be capable of source addressmode */
838                 ! ia32_is_spillmode_compatible(mode, spillmode)       ||
839                 (i != n_ia32_binary_left && i != n_ia32_binary_right) || /* a "real" operand position must be requested */
840                 is_ia32_use_frame(irn))                                  /* must not already use frame */
841                 return 0;
842
843         if (i == n_ia32_binary_left) {
844                 const arch_register_req_t *req;
845                 if(!is_ia32_commutative(irn))
846                         return 0;
847                 /* we can't swap left/right for limited registers
848                  * (As this (currently) breaks constraint handling copies)
849                  */
850                 req = get_ia32_in_req(irn, n_ia32_binary_left);
851                 if(req->type & arch_register_req_type_limited) {
852                         return 0;
853                 }
854         }
855
856         return 1;
857 }
858
859 static void ia32_perform_memory_operand(const void *self, ir_node *irn,
860                                         ir_node *spill, unsigned int i)
861 {
862         const ia32_irn_ops_t *ops = self;
863         ia32_code_gen_t      *cg  = ops->cg;
864
865         assert(ia32_possible_memory_operand(self, irn, i) && "Cannot perform memory operand change");
866
867         if (i == n_ia32_binary_left) {
868                 ia32_swap_left_right(irn);
869         }
870
871         set_ia32_op_type(irn, ia32_AddrModeS);
872         set_ia32_ls_mode(irn, get_irn_mode(get_irn_n(irn, i)));
873         set_ia32_use_frame(irn);
874         set_ia32_need_stackent(irn);
875
876         set_irn_n(irn, n_ia32_base, get_irg_frame(get_irn_irg(irn)));
877         set_irn_n(irn, n_ia32_binary_right, ia32_get_admissible_noreg(cg, irn, n_ia32_binary_right));
878         set_irn_n(irn, n_ia32_mem, spill);
879
880         /* immediates are only allowed on the right side */
881         if (i == n_ia32_binary_left && is_ia32_Immediate(get_irn_n(irn, n_ia32_binary_left))) {
882                 ia32_swap_left_right(irn);
883         }
884 }
885
886 static const be_abi_callbacks_t ia32_abi_callbacks = {
887         ia32_abi_init,
888         ia32_abi_done,
889         ia32_abi_get_between_type,
890         ia32_abi_dont_save_regs,
891         ia32_abi_prologue,
892         ia32_abi_epilogue
893 };
894
895 /* fill register allocator interface */
896
897 static const arch_irn_ops_if_t ia32_irn_ops_if = {
898         ia32_get_irn_reg_req,
899         ia32_set_irn_reg,
900         ia32_get_irn_reg,
901         ia32_classify,
902         ia32_get_flags,
903         ia32_get_frame_entity,
904         ia32_set_frame_entity,
905         ia32_set_frame_offset,
906         ia32_get_sp_bias,
907         ia32_get_inverse,
908         ia32_get_op_estimated_cost,
909         ia32_possible_memory_operand,
910         ia32_perform_memory_operand,
911 };
912
913 static ia32_irn_ops_t ia32_irn_ops = {
914         &ia32_irn_ops_if,
915         NULL
916 };
917
918
919
920 /**************************************************
921  *                _                         _  __
922  *               | |                       (_)/ _|
923  *   ___ ___   __| | ___  __ _  ___ _ __    _| |_
924  *  / __/ _ \ / _` |/ _ \/ _` |/ _ \ '_ \  | |  _|
925  * | (_| (_) | (_| |  __/ (_| |  __/ | | | | | |
926  *  \___\___/ \__,_|\___|\__, |\___|_| |_| |_|_|
927  *                        __/ |
928  *                       |___/
929  **************************************************/
930
931 static ir_entity *mcount = NULL;
932
933 #define ID(s) new_id_from_chars(s, sizeof(s) - 1)
934
935 static void ia32_before_abi(void *self) {
936         lower_mode_b_config_t lower_mode_b_config = {
937                 mode_Iu,  /* lowered mode */
938                 mode_Bu,  /* prefered mode for set */
939                 0,        /* don't lower direct compares */
940         };
941         ia32_code_gen_t *cg = self;
942
943         ir_lower_mode_b(cg->irg, &lower_mode_b_config);
944         if (cg->dump)
945                 be_dump(cg->irg, "-lower_modeb", dump_ir_block_graph_sched);
946         if (cg->gprof) {
947                 if (mcount == NULL) {
948                         ir_type *tp = new_type_method(ID("FKT.mcount"), 0, 0);
949                         mcount = new_entity(get_glob_type(), ID("mcount"), tp);
950                         /* FIXME: enter the right ld_ident here */
951                         set_entity_ld_ident(mcount, get_entity_ident(mcount));
952                         set_entity_visibility(mcount, visibility_external_allocated);
953                 }
954                 instrument_initcall(cg->irg, mcount);
955         }
956 }
957
958 /**
959  * Transforms the standard firm graph into
960  * an ia32 firm graph
961  */
962 static void ia32_prepare_graph(void *self) {
963         ia32_code_gen_t *cg = self;
964
965         /* do local optimisations */
966         optimize_graph_df(cg->irg);
967
968         /* TODO: we often have dead code reachable through out-edges here. So for
969          * now we rebuild edges (as we need correct user count for code selection)
970          */
971 #if 1
972         edges_deactivate(cg->irg);
973         edges_activate(cg->irg);
974 #endif
975
976         if (cg->dump)
977                 be_dump(cg->irg, "-pre_transform", dump_ir_block_graph_sched);
978
979 #ifdef FIRM_GRGEN_BE
980         /* transform nodes into assembler instructions by PBQP magic */
981         ia32_transform_graph_by_pbqp(cg);
982 #endif
983
984         if (cg->dump)
985                 be_dump(cg->irg, "-after_pbqp_transform", dump_ir_block_graph_sched);
986
987         /* transform remaining nodes into assembler instructions */
988         ia32_transform_graph(cg);
989
990         /* do local optimisations (mainly CSE) */
991         optimize_graph_df(cg->irg);
992
993         if (cg->dump)
994                 be_dump(cg->irg, "-transformed", dump_ir_block_graph_sched);
995
996         /* optimize address mode */
997         ia32_optimize_graph(cg);
998
999         if (cg->dump)
1000                 be_dump(cg->irg, "-am", dump_ir_block_graph_sched);
1001
1002         /* do code placement, to optimize the position of constants */
1003         place_code(cg->irg);
1004
1005         if (cg->dump)
1006                 be_dump(cg->irg, "-place", dump_ir_block_graph_sched);
1007 }
1008
1009 /**
1010  * Dummy functions for hooks we don't need but which must be filled.
1011  */
1012 static void ia32_before_sched(void *self) {
1013         (void) self;
1014 }
1015
1016 static void turn_back_am(ir_node *node)
1017 {
1018         ir_graph *irg   = current_ir_graph;
1019         dbg_info *dbgi  = get_irn_dbg_info(node);
1020         ir_node  *block = get_nodes_block(node);
1021         ir_node  *base  = get_irn_n(node, n_ia32_base);
1022         ir_node  *index = get_irn_n(node, n_ia32_index);
1023         ir_node  *mem   = get_irn_n(node, n_ia32_mem);
1024         ir_node  *noreg = ia32_new_NoReg_gp(ia32_current_cg);
1025         ir_node  *load;
1026         ir_node  *load_res;
1027         ir_node  *mem_proj;
1028         const ir_edge_t *edge;
1029
1030         load     = new_rd_ia32_Load(dbgi, irg, block, base, index, mem);
1031         load_res = new_rd_Proj(dbgi, irg, block, load, mode_Iu, pn_ia32_Load_res);
1032
1033         ia32_copy_am_attrs(load, node);
1034         set_irn_n(node, n_ia32_mem, new_NoMem());
1035
1036         switch (get_ia32_am_arity(node)) {
1037                 case ia32_am_unary:
1038                         set_irn_n(node, n_ia32_unary_op, load_res);
1039                         break;
1040
1041                 case ia32_am_binary:
1042                         if (is_ia32_Immediate(get_irn_n(node, n_ia32_Cmp_right))) {
1043                                 assert(is_ia32_Cmp(node)  || is_ia32_Cmp8Bit(node) ||
1044                                        is_ia32_Test(node) || is_ia32_Test8Bit(node));
1045                                 set_irn_n(node, n_ia32_binary_left, load_res);
1046                         } else {
1047                                 set_irn_n(node, n_ia32_binary_right, load_res);
1048                         }
1049                         break;
1050
1051                 case ia32_am_ternary:
1052                         set_irn_n(node, n_ia32_binary_right, load_res);
1053                         break;
1054
1055                 default: break;
1056         }
1057         set_irn_n(node, n_ia32_base, noreg);
1058         set_irn_n(node, n_ia32_index, noreg);
1059         set_ia32_am_offs_int(node, 0);
1060         set_ia32_am_sc(node, NULL);
1061         set_ia32_am_scale(node, 0);
1062         clear_ia32_am_sc_sign(node);
1063
1064         /* rewire mem-proj */
1065         if (get_irn_mode(node) == mode_T) {
1066                 mem_proj = NULL;
1067                 foreach_out_edge(node, edge) {
1068                         ir_node *out = get_edge_src_irn(edge);
1069                         if(get_Proj_proj(out) == pn_ia32_mem) {
1070                                 mem_proj = out;
1071                                 break;
1072                         }
1073                 }
1074
1075                 if(mem_proj != NULL) {
1076                         set_Proj_pred(mem_proj, load);
1077                         set_Proj_proj(mem_proj, pn_ia32_Load_M);
1078                 }
1079         }
1080
1081         set_ia32_op_type(node, ia32_Normal);
1082         if (sched_is_scheduled(node))
1083                 sched_add_before(node, load);
1084 }
1085
1086 static ir_node *flags_remat(ir_node *node, ir_node *after)
1087 {
1088         /* we should turn back source address mode when rematerializing nodes */
1089         ia32_op_type_t  type = get_ia32_op_type(node);
1090         ir_node        *block;
1091         ir_node        *copy;
1092
1093         if (is_Block(after)) {
1094                 block = after;
1095         } else {
1096                 block = get_nodes_block(after);
1097         }
1098
1099         switch (type) {
1100                 case ia32_AddrModeS: turn_back_am(node); break;
1101
1102                 case ia32_AddrModeD:
1103                         /* TODO implement this later... */
1104                         panic("found DestAM with flag user %+F this should not happen", node);
1105                         break;
1106
1107                 default: assert(type == ia32_Normal); break;
1108         }
1109
1110         copy = exact_copy(node);
1111         set_nodes_block(copy, block);
1112         sched_add_after(after, copy);
1113
1114         return copy;
1115 }
1116
1117 /**
1118  * Called before the register allocator.
1119  * Calculate a block schedule here. We need it for the x87
1120  * simulator and the emitter.
1121  */
1122 static void ia32_before_ra(void *self) {
1123         ia32_code_gen_t *cg = self;
1124
1125         /* setup fpu rounding modes */
1126         ia32_setup_fpu_mode(cg);
1127
1128         /* fixup flags */
1129         be_sched_fix_flags(cg->birg, &ia32_reg_classes[CLASS_ia32_flags],
1130                            &flags_remat);
1131
1132         ia32_add_missing_keeps(cg);
1133 }
1134
1135
1136 /**
1137  * Transforms a be_Reload into a ia32 Load.
1138  */
1139 static void transform_to_Load(ia32_code_gen_t *cg, ir_node *node) {
1140         ir_graph *irg        = get_irn_irg(node);
1141         dbg_info *dbg        = get_irn_dbg_info(node);
1142         ir_node *block       = get_nodes_block(node);
1143         ir_entity *ent       = be_get_frame_entity(node);
1144         ir_mode *mode        = get_irn_mode(node);
1145         ir_mode *spillmode   = get_spill_mode(node);
1146         ir_node *noreg       = ia32_new_NoReg_gp(cg);
1147         ir_node *sched_point = NULL;
1148         ir_node *ptr         = get_irg_frame(irg);
1149         ir_node *mem         = get_irn_n(node, be_pos_Reload_mem);
1150         ir_node *new_op, *proj;
1151         const arch_register_t *reg;
1152
1153         if (sched_is_scheduled(node)) {
1154                 sched_point = sched_prev(node);
1155         }
1156
1157         if (mode_is_float(spillmode)) {
1158                 if (ia32_cg_config.use_sse2)
1159                         new_op = new_rd_ia32_xLoad(dbg, irg, block, ptr, noreg, mem, spillmode);
1160                 else
1161                         new_op = new_rd_ia32_vfld(dbg, irg, block, ptr, noreg, mem, spillmode);
1162         }
1163         else if (get_mode_size_bits(spillmode) == 128) {
1164                 // Reload 128 bit sse registers
1165                 new_op = new_rd_ia32_xxLoad(dbg, irg, block, ptr, noreg, mem);
1166         }
1167         else
1168                 new_op = new_rd_ia32_Load(dbg, irg, block, ptr, noreg, mem);
1169
1170         set_ia32_op_type(new_op, ia32_AddrModeS);
1171         set_ia32_ls_mode(new_op, spillmode);
1172         set_ia32_frame_ent(new_op, ent);
1173         set_ia32_use_frame(new_op);
1174
1175         DBG_OPT_RELOAD2LD(node, new_op);
1176
1177         proj = new_rd_Proj(dbg, irg, block, new_op, mode, pn_ia32_Load_res);
1178
1179         if (sched_point) {
1180                 sched_add_after(sched_point, new_op);
1181                 sched_remove(node);
1182         }
1183
1184         /* copy the register from the old node to the new Load */
1185         reg = arch_get_irn_register(cg->arch_env, node);
1186         arch_set_irn_register(cg->arch_env, new_op, reg);
1187
1188         SET_IA32_ORIG_NODE(new_op, ia32_get_old_node_name(cg, node));
1189
1190         exchange(node, proj);
1191 }
1192
1193 /**
1194  * Transforms a be_Spill node into a ia32 Store.
1195  */
1196 static void transform_to_Store(ia32_code_gen_t *cg, ir_node *node) {
1197         ir_graph *irg  = get_irn_irg(node);
1198         dbg_info *dbg  = get_irn_dbg_info(node);
1199         ir_node *block = get_nodes_block(node);
1200         ir_entity *ent = be_get_frame_entity(node);
1201         const ir_node *spillval = get_irn_n(node, be_pos_Spill_val);
1202         ir_mode *mode  = get_spill_mode(spillval);
1203         ir_node *noreg = ia32_new_NoReg_gp(cg);
1204         ir_node *nomem = new_rd_NoMem(irg);
1205         ir_node *ptr   = get_irg_frame(irg);
1206         ir_node *val   = get_irn_n(node, be_pos_Spill_val);
1207         ir_node *store;
1208         ir_node *sched_point = NULL;
1209
1210         if (sched_is_scheduled(node)) {
1211                 sched_point = sched_prev(node);
1212         }
1213
1214         /* No need to spill unknown values... */
1215         if(is_ia32_Unknown_GP(val) ||
1216                 is_ia32_Unknown_VFP(val) ||
1217                 is_ia32_Unknown_XMM(val)) {
1218                 store = nomem;
1219                 if(sched_point)
1220                         sched_remove(node);
1221
1222                 exchange(node, store);
1223                 return;
1224         }
1225
1226         if (mode_is_float(mode)) {
1227                 if (ia32_cg_config.use_sse2)
1228                         store = new_rd_ia32_xStore(dbg, irg, block, ptr, noreg, nomem, val);
1229                 else
1230                         store = new_rd_ia32_vfst(dbg, irg, block, ptr, noreg, nomem, val, mode);
1231         } else if (get_mode_size_bits(mode) == 128) {
1232                 // Spill 128 bit SSE registers
1233                 store = new_rd_ia32_xxStore(dbg, irg, block, ptr, noreg, nomem, val);
1234         } else if (get_mode_size_bits(mode) == 8) {
1235                 store = new_rd_ia32_Store8Bit(dbg, irg, block, ptr, noreg, nomem, val);
1236         } else {
1237                 store = new_rd_ia32_Store(dbg, irg, block, ptr, noreg, nomem, val);
1238         }
1239
1240         set_ia32_op_type(store, ia32_AddrModeD);
1241         set_ia32_ls_mode(store, mode);
1242         set_ia32_frame_ent(store, ent);
1243         set_ia32_use_frame(store);
1244         SET_IA32_ORIG_NODE(store, ia32_get_old_node_name(cg, node));
1245         DBG_OPT_SPILL2ST(node, store);
1246
1247         if (sched_point) {
1248                 sched_add_after(sched_point, store);
1249                 sched_remove(node);
1250         }
1251
1252         exchange(node, store);
1253 }
1254
1255 static ir_node *create_push(ia32_code_gen_t *cg, ir_node *node, ir_node *schedpoint, ir_node *sp, ir_node *mem, ir_entity *ent) {
1256         ir_graph *irg = get_irn_irg(node);
1257         dbg_info *dbg = get_irn_dbg_info(node);
1258         ir_node *block = get_nodes_block(node);
1259         ir_node *noreg = ia32_new_NoReg_gp(cg);
1260         ir_node *frame = get_irg_frame(irg);
1261
1262         ir_node *push = new_rd_ia32_Push(dbg, irg, block, frame, noreg, mem, sp, noreg);
1263
1264         set_ia32_frame_ent(push, ent);
1265         set_ia32_use_frame(push);
1266         set_ia32_op_type(push, ia32_AddrModeS);
1267         set_ia32_ls_mode(push, mode_Is);
1268
1269         sched_add_before(schedpoint, push);
1270         return push;
1271 }
1272
1273 static ir_node *create_pop(ia32_code_gen_t *cg, ir_node *node, ir_node *schedpoint, ir_node *sp, ir_entity *ent) {
1274         ir_graph *irg = get_irn_irg(node);
1275         dbg_info *dbg = get_irn_dbg_info(node);
1276         ir_node *block = get_nodes_block(node);
1277         ir_node *noreg = ia32_new_NoReg_gp(cg);
1278         ir_node *frame = get_irg_frame(irg);
1279
1280         ir_node *pop = new_rd_ia32_Pop(dbg, irg, block, frame, noreg, new_NoMem(), sp);
1281
1282         set_ia32_frame_ent(pop, ent);
1283         set_ia32_use_frame(pop);
1284         set_ia32_op_type(pop, ia32_AddrModeD);
1285         set_ia32_ls_mode(pop, mode_Is);
1286
1287         sched_add_before(schedpoint, pop);
1288
1289         return pop;
1290 }
1291
1292 static ir_node* create_spproj(ia32_code_gen_t *cg, ir_node *node, ir_node *pred, int pos) {
1293         ir_graph *irg = get_irn_irg(node);
1294         dbg_info *dbg = get_irn_dbg_info(node);
1295         ir_node *block = get_nodes_block(node);
1296         ir_mode *spmode = mode_Iu;
1297         const arch_register_t *spreg = &ia32_gp_regs[REG_ESP];
1298         ir_node *sp;
1299
1300         sp = new_rd_Proj(dbg, irg, block, pred, spmode, pos);
1301         arch_set_irn_register(cg->arch_env, sp, spreg);
1302
1303         return sp;
1304 }
1305
1306 /**
1307  * Transform memperm, currently we do this the ugly way and produce
1308  * push/pop into/from memory cascades. This is possible without using
1309  * any registers.
1310  */
1311 static void transform_MemPerm(ia32_code_gen_t *cg, ir_node *node) {
1312         ir_graph *irg = get_irn_irg(node);
1313         ir_node *block = get_nodes_block(node);
1314         ir_node *in[1];
1315         ir_node *keep;
1316         int i, arity;
1317         ir_node *sp = be_abi_get_ignore_irn(cg->birg->abi, &ia32_gp_regs[REG_ESP]);
1318         const ir_edge_t *edge;
1319         const ir_edge_t *next;
1320         ir_node **pops;
1321
1322         arity = be_get_MemPerm_entity_arity(node);
1323         pops = alloca(arity * sizeof(pops[0]));
1324
1325         /* create Pushs */
1326         for(i = 0; i < arity; ++i) {
1327                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1328                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1329                 ir_type *enttype = get_entity_type(inent);
1330                 unsigned entsize = get_type_size_bytes(enttype);
1331                 unsigned entsize2 = get_type_size_bytes(get_entity_type(outent));
1332                 ir_node *mem = get_irn_n(node, i + 1);
1333                 ir_node *push;
1334
1335                 /* work around cases where entities have different sizes */
1336                 if(entsize2 < entsize)
1337                         entsize = entsize2;
1338                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1339
1340                 push = create_push(cg, node, node, sp, mem, inent);
1341                 sp = create_spproj(cg, node, push, pn_ia32_Push_stack);
1342                 if(entsize == 8) {
1343                         /* add another push after the first one */
1344                         push = create_push(cg, node, node, sp, mem, inent);
1345                         add_ia32_am_offs_int(push, 4);
1346                         sp = create_spproj(cg, node, push, pn_ia32_Push_stack);
1347                 }
1348
1349                 set_irn_n(node, i, new_Bad());
1350         }
1351
1352         /* create pops */
1353         for(i = arity - 1; i >= 0; --i) {
1354                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1355                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1356                 ir_type *enttype = get_entity_type(outent);
1357                 unsigned entsize = get_type_size_bytes(enttype);
1358                 unsigned entsize2 = get_type_size_bytes(get_entity_type(inent));
1359                 ir_node *pop;
1360
1361                 /* work around cases where entities have different sizes */
1362                 if(entsize2 < entsize)
1363                         entsize = entsize2;
1364                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1365
1366                 pop = create_pop(cg, node, node, sp, outent);
1367                 sp = create_spproj(cg, node, pop, pn_ia32_Pop_stack);
1368                 if(entsize == 8) {
1369                         add_ia32_am_offs_int(pop, 4);
1370
1371                         /* add another pop after the first one */
1372                         pop = create_pop(cg, node, node, sp, outent);
1373                         sp = create_spproj(cg, node, pop, pn_ia32_Pop_stack);
1374                 }
1375
1376                 pops[i] = pop;
1377         }
1378
1379         in[0] = sp;
1380         keep  = be_new_Keep(&ia32_reg_classes[CLASS_ia32_gp], irg, block, 1, in);
1381         sched_add_before(node, keep);
1382
1383         /* exchange memprojs */
1384         foreach_out_edge_safe(node, edge, next) {
1385                 ir_node *proj = get_edge_src_irn(edge);
1386                 int p = get_Proj_proj(proj);
1387
1388                 assert(p < arity);
1389
1390                 set_Proj_pred(proj, pops[p]);
1391                 set_Proj_proj(proj, pn_ia32_Pop_M);
1392         }
1393
1394         /* remove memperm */
1395         arity = get_irn_arity(node);
1396         for(i = 0; i < arity; ++i) {
1397                 set_irn_n(node, i, new_Bad());
1398         }
1399         sched_remove(node);
1400 }
1401
1402 /**
1403  * Block-Walker: Calls the transform functions Spill and Reload.
1404  */
1405 static void ia32_after_ra_walker(ir_node *block, void *env) {
1406         ir_node *node, *prev;
1407         ia32_code_gen_t *cg = env;
1408
1409         /* beware: the schedule is changed here */
1410         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
1411                 prev = sched_prev(node);
1412
1413                 if (be_is_Reload(node)) {
1414                         transform_to_Load(cg, node);
1415                 } else if (be_is_Spill(node)) {
1416                         transform_to_Store(cg, node);
1417                 } else if(be_is_MemPerm(node)) {
1418                         transform_MemPerm(cg, node);
1419                 }
1420         }
1421 }
1422
1423 /**
1424  * Collects nodes that need frame entities assigned.
1425  */
1426 static void ia32_collect_frame_entity_nodes(ir_node *node, void *data)
1427 {
1428         be_fec_env_t *env = data;
1429
1430         if (be_is_Reload(node) && be_get_frame_entity(node) == NULL) {
1431                 const ir_mode *mode = get_spill_mode_mode(get_irn_mode(node));
1432                 int align = get_mode_size_bytes(mode);
1433                 be_node_needs_frame_entity(env, node, mode, align);
1434         } else if(is_ia32_irn(node) && get_ia32_frame_ent(node) == NULL
1435                   && is_ia32_use_frame(node)) {
1436                 if (is_ia32_need_stackent(node) || is_ia32_Load(node)) {
1437                         const ir_mode     *mode  = get_ia32_ls_mode(node);
1438                         const ia32_attr_t *attr  = get_ia32_attr_const(node);
1439                         int                align = get_mode_size_bytes(mode);
1440
1441                         if(attr->data.need_64bit_stackent) {
1442                                 mode = mode_Ls;
1443                         }
1444                         if(attr->data.need_32bit_stackent) {
1445                                 mode = mode_Is;
1446                         }
1447                         be_node_needs_frame_entity(env, node, mode, align);
1448                 } else if (is_ia32_vfild(node) || is_ia32_xLoad(node)
1449                            || is_ia32_vfld(node)) {
1450                         const ir_mode *mode  = get_ia32_ls_mode(node);
1451                         int            align = 4;
1452                         be_node_needs_frame_entity(env, node, mode, align);
1453                 } else if(is_ia32_FldCW(node)) {
1454                         /* although 2 byte would be enough 4 byte performs best */
1455                         const ir_mode *mode  = mode_Iu;
1456                         int            align = 4;
1457                         be_node_needs_frame_entity(env, node, mode, align);
1458                 } else {
1459 #ifndef NDEBUG
1460                         assert(is_ia32_St(node) ||
1461                                    is_ia32_xStoreSimple(node) ||
1462                                    is_ia32_vfst(node) ||
1463                                    is_ia32_vfist(node) ||
1464                                is_ia32_FnstCW(node));
1465 #endif
1466                 }
1467         }
1468 }
1469
1470 /**
1471  * We transform Spill and Reload here. This needs to be done before
1472  * stack biasing otherwise we would miss the corrected offset for these nodes.
1473  */
1474 static void ia32_after_ra(void *self) {
1475         ia32_code_gen_t *cg = self;
1476         ir_graph *irg = cg->irg;
1477         be_fec_env_t *fec_env = be_new_frame_entity_coalescer(cg->birg);
1478
1479         /* create and coalesce frame entities */
1480         irg_walk_graph(irg, NULL, ia32_collect_frame_entity_nodes, fec_env);
1481         be_assign_entities(fec_env);
1482         be_free_frame_entity_coalescer(fec_env);
1483
1484         irg_block_walk_graph(irg, NULL, ia32_after_ra_walker, cg);
1485 }
1486
1487 /**
1488  * Last touchups for the graph before emit: x87 simulation to replace the
1489  * virtual with real x87 instructions, creating a block schedule and peephole
1490  * optimisations.
1491  */
1492 static void ia32_finish(void *self) {
1493         ia32_code_gen_t *cg = self;
1494         ir_graph        *irg = cg->irg;
1495
1496         ia32_finish_irg(irg, cg);
1497
1498         /* we might have to rewrite x87 virtual registers */
1499         if (cg->do_x87_sim) {
1500                 x87_simulate_graph(cg->arch_env, cg->birg);
1501         }
1502
1503         /* do peephole optimisations */
1504         ia32_peephole_optimization(cg);
1505
1506         /* create block schedule, this also removes empty blocks which might
1507          * produce critical edges */
1508         cg->blk_sched = be_create_block_schedule(irg, cg->birg->exec_freq);
1509 }
1510
1511 /**
1512  * Emits the code, closes the output file and frees
1513  * the code generator interface.
1514  */
1515 static void ia32_codegen(void *self) {
1516         ia32_code_gen_t *cg = self;
1517         ir_graph        *irg = cg->irg;
1518
1519         ia32_gen_routine(cg, irg);
1520
1521         cur_reg_set = NULL;
1522
1523         /* remove it from the isa */
1524         cg->isa->cg = NULL;
1525
1526         assert(ia32_current_cg == cg);
1527         ia32_current_cg = NULL;
1528
1529         /* de-allocate code generator */
1530         del_set(cg->reg_set);
1531         free(cg);
1532 }
1533
1534 /**
1535  * Returns the node representing the PIC base.
1536  */
1537 static ir_node *ia32_get_pic_base(void *self) {
1538         ir_node         *block;
1539         ia32_code_gen_t *cg      = self;
1540         ir_node         *get_eip = cg->get_eip;
1541         if (get_eip != NULL)
1542                 return get_eip;
1543
1544         block       = get_irg_start_block(cg->irg);
1545         get_eip     = new_rd_ia32_GetEIP(NULL, cg->irg, block);
1546         cg->get_eip = get_eip;
1547
1548         add_irn_dep(get_eip, get_irg_frame(cg->irg));
1549
1550         return get_eip;
1551 }
1552
1553 static void *ia32_cg_init(be_irg_t *birg);
1554
1555 static const arch_code_generator_if_t ia32_code_gen_if = {
1556         ia32_cg_init,
1557         ia32_get_pic_base,   /* return node used as base in pic code addresses */
1558         ia32_before_abi,     /* before abi introduce hook */
1559         ia32_prepare_graph,
1560         NULL,                /* spill */
1561         ia32_before_sched,   /* before scheduling hook */
1562         ia32_before_ra,      /* before register allocation hook */
1563         ia32_after_ra,       /* after register allocation hook */
1564         ia32_finish,         /* called before codegen */
1565         ia32_codegen         /* emit && done */
1566 };
1567
1568 /**
1569  * Initializes a IA32 code generator.
1570  */
1571 static void *ia32_cg_init(be_irg_t *birg) {
1572         ia32_isa_t      *isa = (ia32_isa_t *)birg->main_env->arch_env.isa;
1573         ia32_code_gen_t *cg  = xcalloc(1, sizeof(*cg));
1574
1575         cg->impl      = &ia32_code_gen_if;
1576         cg->irg       = birg->irg;
1577         cg->reg_set   = new_set(ia32_cmp_irn_reg_assoc, 1024);
1578         cg->arch_env  = &birg->main_env->arch_env;
1579         cg->isa       = isa;
1580         cg->birg      = birg;
1581         cg->blk_sched = NULL;
1582         cg->dump      = (birg->main_env->options->dump_flags & DUMP_BE) ? 1 : 0;
1583         cg->gprof     = (birg->main_env->options->gprof) ? 1 : 0;
1584
1585         /* enter it */
1586         isa->cg = cg;
1587
1588 #ifndef NDEBUG
1589         if (isa->name_obst) {
1590                 obstack_free(isa->name_obst, NULL);
1591                 obstack_init(isa->name_obst);
1592         }
1593 #endif /* NDEBUG */
1594
1595         cur_reg_set = cg->reg_set;
1596
1597         ia32_irn_ops.cg = cg;
1598
1599         assert(ia32_current_cg == NULL);
1600         ia32_current_cg = cg;
1601
1602         return (arch_code_generator_t *)cg;
1603 }
1604
1605
1606
1607 /*****************************************************************
1608  *  ____             _                  _   _____  _____
1609  * |  _ \           | |                | | |_   _|/ ____|  /\
1610  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
1611  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
1612  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
1613  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
1614  *
1615  *****************************************************************/
1616
1617 /**
1618  * Set output modes for GCC
1619  */
1620 static const tarval_mode_info mo_integer = {
1621         TVO_HEX,
1622         "0x",
1623         NULL,
1624 };
1625
1626 /*
1627  * set the tarval output mode of all integer modes to decimal
1628  */
1629 static void set_tarval_output_modes(void)
1630 {
1631         int i;
1632
1633         for (i = get_irp_n_modes() - 1; i >= 0; --i) {
1634                 ir_mode *mode = get_irp_mode(i);
1635
1636                 if (mode_is_int(mode))
1637                         set_tarval_mode_output_option(mode, &mo_integer);
1638         }
1639 }
1640
1641 const arch_isa_if_t ia32_isa_if;
1642
1643 /**
1644  * The template that generates a new ISA object.
1645  * Note that this template can be changed by command line
1646  * arguments.
1647  */
1648 static ia32_isa_t ia32_isa_template = {
1649         {
1650                 &ia32_isa_if,            /* isa interface implementation */
1651                 &ia32_gp_regs[REG_ESP],  /* stack pointer register */
1652                 &ia32_gp_regs[REG_EBP],  /* base pointer register */
1653                 -1,                      /* stack direction */
1654                 16,                      /* stack alignment */
1655                 NULL,                    /* main environment */
1656                 7,                       /* costs for a spill instruction */
1657                 5,                       /* costs for a reload instruction */
1658         },
1659         NULL,                    /* 16bit register names */
1660         NULL,                    /* 8bit register names */
1661         NULL,                    /* 8bit register names high */
1662         NULL,                    /* types */
1663         NULL,                    /* tv_ents */
1664         NULL,                    /* current code generator */
1665         NULL,                    /* abstract machine */
1666 #ifndef NDEBUG
1667         NULL,                    /* name obstack */
1668 #endif
1669 };
1670
1671 /**
1672  * Initializes the backend ISA.
1673  */
1674 static void *ia32_init(FILE *file_handle) {
1675         static int inited = 0;
1676         ia32_isa_t *isa;
1677
1678         if (inited)
1679                 return NULL;
1680         inited = 1;
1681
1682         set_tarval_output_modes();
1683
1684         isa = xmalloc(sizeof(*isa));
1685         memcpy(isa, &ia32_isa_template, sizeof(*isa));
1686
1687         if(mode_fpcw == NULL) {
1688                 mode_fpcw = new_ir_mode("Fpcw", irms_int_number, 16, 0, irma_none, 0);
1689         }
1690
1691         ia32_register_init();
1692         ia32_create_opcodes();
1693
1694         be_emit_init(file_handle);
1695         isa->regs_16bit     = pmap_create();
1696         isa->regs_8bit      = pmap_create();
1697         isa->regs_8bit_high = pmap_create();
1698         isa->types          = pmap_create();
1699         isa->tv_ent         = pmap_create();
1700         isa->cpu            = ia32_init_machine_description();
1701
1702         ia32_build_16bit_reg_map(isa->regs_16bit);
1703         ia32_build_8bit_reg_map(isa->regs_8bit);
1704         ia32_build_8bit_reg_map_high(isa->regs_8bit_high);
1705
1706 #ifndef NDEBUG
1707         isa->name_obst = xmalloc(sizeof(*isa->name_obst));
1708         obstack_init(isa->name_obst);
1709 #endif /* NDEBUG */
1710
1711         /* enter the ISA object into the intrinsic environment */
1712         intrinsic_env.isa = isa;
1713         ia32_handle_intrinsics();
1714
1715         /* needed for the debug support */
1716         be_gas_emit_switch_section(GAS_SECTION_TEXT);
1717         be_emit_cstring(".Ltext0:\n");
1718         be_emit_write_line();
1719
1720         /* we mark referenced global entities, so we can only emit those which
1721          * are actually referenced. (Note: you mustn't use the type visited flag
1722          * elsewhere in the backend)
1723          */
1724         inc_master_type_visited();
1725
1726         return isa;
1727 }
1728
1729
1730
1731 /**
1732  * Closes the output file and frees the ISA structure.
1733  */
1734 static void ia32_done(void *self) {
1735         ia32_isa_t *isa = self;
1736
1737         /* emit now all global declarations */
1738         be_gas_emit_decls(isa->arch_isa.main_env, 1);
1739
1740         pmap_destroy(isa->regs_16bit);
1741         pmap_destroy(isa->regs_8bit);
1742         pmap_destroy(isa->regs_8bit_high);
1743         pmap_destroy(isa->tv_ent);
1744         pmap_destroy(isa->types);
1745
1746 #ifndef NDEBUG
1747         obstack_free(isa->name_obst, NULL);
1748 #endif /* NDEBUG */
1749
1750         be_emit_exit();
1751
1752         free(self);
1753 }
1754
1755
1756 /**
1757  * Return the number of register classes for this architecture.
1758  * We report always these:
1759  *  - the general purpose registers
1760  *  - the SSE floating point register set
1761  *  - the virtual floating point registers
1762  *  - the SSE vector register set
1763  */
1764 static unsigned ia32_get_n_reg_class(const void *self) {
1765         (void) self;
1766         return N_CLASSES;
1767 }
1768
1769 /**
1770  * Return the register class for index i.
1771  */
1772 static const arch_register_class_t *ia32_get_reg_class(const void *self,
1773                                                        unsigned i)
1774 {
1775         (void) self;
1776         assert(i < N_CLASSES);
1777         return &ia32_reg_classes[i];
1778 }
1779
1780 /**
1781  * Get the register class which shall be used to store a value of a given mode.
1782  * @param self The this pointer.
1783  * @param mode The mode in question.
1784  * @return A register class which can hold values of the given mode.
1785  */
1786 const arch_register_class_t *ia32_get_reg_class_for_mode(const void *self,
1787                 const ir_mode *mode)
1788 {
1789         (void) self;
1790
1791         if (mode_is_float(mode)) {
1792                 return ia32_cg_config.use_sse2 ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
1793         }
1794         else
1795                 return &ia32_reg_classes[CLASS_ia32_gp];
1796 }
1797
1798 /**
1799  * Get the ABI restrictions for procedure calls.
1800  * @param self        The this pointer.
1801  * @param method_type The type of the method (procedure) in question.
1802  * @param abi         The abi object to be modified
1803  */
1804 static void ia32_get_call_abi(const void *self, ir_type *method_type,
1805                               be_abi_call_t *abi)
1806 {
1807         ir_type  *tp;
1808         ir_mode  *mode;
1809         unsigned  cc;
1810         int       n, i, regnum;
1811         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
1812         (void) self;
1813
1814         /* set abi flags for calls */
1815         call_flags.bits.left_to_right         = 0;  /* always last arg first on stack */
1816         call_flags.bits.store_args_sequential = 0;
1817         /* call_flags.bits.try_omit_fp                 not changed: can handle both settings */
1818         call_flags.bits.fp_free               = 0;  /* the frame pointer is fixed in IA32 */
1819         call_flags.bits.call_has_imm          = 1;  /* IA32 calls can have immediate address */
1820
1821         /* set parameter passing style */
1822         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
1823
1824         if (get_method_variadicity(method_type) == variadicity_variadic) {
1825                 /* pass all parameters of a variadic function on the stack */
1826                 cc = cc_cdecl_set;
1827         } else {
1828                 cc = get_method_calling_convention(method_type);
1829                 if (get_method_additional_properties(method_type) & mtp_property_private
1830                                 && (ia32_cg_config.optimize_cc)) {
1831                         /* set the calling conventions to register parameter */
1832                         cc = (cc & ~cc_bits) | cc_reg_param;
1833                 }
1834         }
1835
1836         /* we have to pop the shadow parameter ourself for compound calls */
1837         if( (get_method_calling_convention(method_type) & cc_compound_ret)
1838                         && !(cc & cc_reg_param)) {
1839                 be_abi_call_set_pop(abi, get_mode_size_bytes(mode_P_data));
1840         }
1841
1842         n = get_method_n_params(method_type);
1843         for (i = regnum = 0; i < n; i++) {
1844                 ir_mode               *mode;
1845                 const arch_register_t *reg = NULL;
1846
1847                 tp   = get_method_param_type(method_type, i);
1848                 mode = get_type_mode(tp);
1849                 if (mode != NULL) {
1850                         reg  = ia32_get_RegParam_reg(cc, regnum, mode);
1851                 }
1852                 if (reg != NULL) {
1853                         be_abi_call_param_reg(abi, i, reg);
1854                         ++regnum;
1855                 } else {
1856                         /* Micro optimisation: if the mode is shorter than 4 bytes, load 4 bytes.
1857                          * movl has a shorter opcode than mov[sz][bw]l */
1858                         ir_mode *load_mode = mode;
1859                         if (mode != NULL && get_mode_size_bytes(mode) < 4) load_mode = mode_Iu;
1860                         be_abi_call_param_stack(abi, i, load_mode, 4, 0, 0);
1861                 }
1862         }
1863
1864         /* set return registers */
1865         n = get_method_n_ress(method_type);
1866
1867         assert(n <= 2 && "more than two results not supported");
1868
1869         /* In case of 64bit returns, we will have two 32bit values */
1870         if (n == 2) {
1871                 tp   = get_method_res_type(method_type, 0);
1872                 mode = get_type_mode(tp);
1873
1874                 assert(!mode_is_float(mode) && "two FP results not supported");
1875
1876                 tp   = get_method_res_type(method_type, 1);
1877                 mode = get_type_mode(tp);
1878
1879                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
1880
1881                 be_abi_call_res_reg(abi, 0, &ia32_gp_regs[REG_EAX]);
1882                 be_abi_call_res_reg(abi, 1, &ia32_gp_regs[REG_EDX]);
1883         }
1884         else if (n == 1) {
1885                 const arch_register_t *reg;
1886
1887                 tp   = get_method_res_type(method_type, 0);
1888                 assert(is_atomic_type(tp));
1889                 mode = get_type_mode(tp);
1890
1891                 reg = mode_is_float(mode) ? &ia32_vfp_regs[REG_VF0] : &ia32_gp_regs[REG_EAX];
1892
1893                 be_abi_call_res_reg(abi, 0, reg);
1894         }
1895 }
1896
1897
1898 static const void *ia32_get_irn_ops(const arch_irn_handler_t *self,
1899                                     const ir_node *irn)
1900 {
1901         (void) self;
1902         (void) irn;
1903         return &ia32_irn_ops;
1904 }
1905
1906 const arch_irn_handler_t ia32_irn_handler = {
1907         ia32_get_irn_ops
1908 };
1909
1910 const arch_irn_handler_t *ia32_get_irn_handler(const void *self)
1911 {
1912         (void) self;
1913         return &ia32_irn_handler;
1914 }
1915
1916 int ia32_to_appear_in_schedule(void *block_env, const ir_node *irn)
1917 {
1918         (void) block_env;
1919
1920         if(!is_ia32_irn(irn)) {
1921                 return -1;
1922         }
1923
1924         if(is_ia32_NoReg_GP(irn) || is_ia32_NoReg_VFP(irn) || is_ia32_NoReg_XMM(irn)
1925                 || is_ia32_Unknown_GP(irn) || is_ia32_Unknown_XMM(irn)
1926                 || is_ia32_Unknown_VFP(irn) || is_ia32_ChangeCW(irn)
1927                 || is_ia32_Immediate(irn))
1928                 return 0;
1929
1930         return 1;
1931 }
1932
1933 /**
1934  * Initializes the code generator interface.
1935  */
1936 static const arch_code_generator_if_t *ia32_get_code_generator_if(void *self)
1937 {
1938         (void) self;
1939         return &ia32_code_gen_if;
1940 }
1941
1942 /**
1943  * Returns the estimated execution time of an ia32 irn.
1944  */
1945 static sched_timestep_t ia32_sched_exectime(void *env, const ir_node *irn) {
1946         const arch_env_t *arch_env = env;
1947         return is_ia32_irn(irn) ? ia32_get_op_estimated_cost(arch_get_irn_ops(arch_env, irn), irn) : 1;
1948 }
1949
1950 list_sched_selector_t ia32_sched_selector;
1951
1952 /**
1953  * Returns the reg_pressure scheduler with to_appear_in_schedule() overloaded
1954  */
1955 static const list_sched_selector_t *ia32_get_list_sched_selector(
1956                 const void *self, list_sched_selector_t *selector)
1957 {
1958         (void) self;
1959         memcpy(&ia32_sched_selector, selector, sizeof(ia32_sched_selector));
1960         ia32_sched_selector.exectime              = ia32_sched_exectime;
1961         ia32_sched_selector.to_appear_in_schedule = ia32_to_appear_in_schedule;
1962         return &ia32_sched_selector;
1963 }
1964
1965 static const ilp_sched_selector_t *ia32_get_ilp_sched_selector(const void *self)
1966 {
1967         (void) self;
1968         return NULL;
1969 }
1970
1971 /**
1972  * Returns the necessary byte alignment for storing a register of given class.
1973  */
1974 static int ia32_get_reg_class_alignment(const void *self,
1975                                         const arch_register_class_t *cls)
1976 {
1977         ir_mode *mode = arch_register_class_mode(cls);
1978         int bytes     = get_mode_size_bytes(mode);
1979         (void) self;
1980
1981         if (mode_is_float(mode) && bytes > 8)
1982                 return 16;
1983         return bytes;
1984 }
1985
1986 static const be_execution_unit_t ***ia32_get_allowed_execution_units(
1987                 const void *self, const ir_node *irn)
1988 {
1989         static const be_execution_unit_t *_allowed_units_BRANCH[] = {
1990                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH1],
1991                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH2],
1992                 NULL,
1993         };
1994         static const be_execution_unit_t *_allowed_units_GP[] = {
1995                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EAX],
1996                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EBX],
1997                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_ECX],
1998                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EDX],
1999                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_ESI],
2000                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EDI],
2001                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EBP],
2002                 NULL,
2003         };
2004         static const be_execution_unit_t *_allowed_units_DUMMY[] = {
2005                 &be_machine_execution_units_DUMMY[0],
2006                 NULL,
2007         };
2008         static const be_execution_unit_t **_units_callret[] = {
2009                 _allowed_units_BRANCH,
2010                 NULL
2011         };
2012         static const be_execution_unit_t **_units_other[] = {
2013                 _allowed_units_GP,
2014                 NULL
2015         };
2016         static const be_execution_unit_t **_units_dummy[] = {
2017                 _allowed_units_DUMMY,
2018                 NULL
2019         };
2020         const be_execution_unit_t ***ret;
2021         (void) self;
2022
2023         if (is_ia32_irn(irn)) {
2024                 ret = get_ia32_exec_units(irn);
2025         }
2026         else if (is_be_node(irn)) {
2027                 if (be_is_Call(irn) || be_is_Return(irn)) {
2028                         ret = _units_callret;
2029                 }
2030                 else if (be_is_Barrier(irn)) {
2031                         ret = _units_dummy;
2032                 }
2033                 else {
2034                          ret = _units_other;
2035                 }
2036         }
2037         else {
2038                 ret = _units_dummy;
2039         }
2040
2041         return ret;
2042 }
2043
2044 /**
2045  * Return the abstract ia32 machine.
2046  */
2047 static const be_machine_t *ia32_get_machine(const void *self) {
2048         const ia32_isa_t *isa = self;
2049         return isa->cpu;
2050 }
2051
2052 /**
2053  * Return irp irgs in the desired order.
2054  */
2055 static ir_graph **ia32_get_irg_list(const void *self, ir_graph ***irg_list)
2056 {
2057         (void) self;
2058         (void) irg_list;
2059         return NULL;
2060 }
2061
2062 /**
2063  * Allows or disallows the creation of Psi nodes for the given Phi nodes.
2064  * @return 1 if allowed, 0 otherwise
2065  */
2066 static int ia32_is_psi_allowed(ir_node *sel, ir_node *phi_list, int i, int j)
2067 {
2068         ir_node *phi;
2069
2070         (void)sel;
2071         (void)i;
2072         (void)j;
2073
2074         if(!ia32_cg_config.use_cmov) {
2075                 /* TODO: we could still handle abs(x)... */
2076                 return 0;
2077         }
2078
2079         /* we can't handle psis with 64bit compares yet */
2080         if(is_Proj(sel)) {
2081                 ir_node *pred = get_Proj_pred(sel);
2082                 if(is_Cmp(pred)) {
2083                         ir_node *left     = get_Cmp_left(pred);
2084                         ir_mode *cmp_mode = get_irn_mode(left);
2085                         if(!mode_is_float(cmp_mode) && get_mode_size_bits(cmp_mode) > 32)
2086                                 return 0;
2087                 }
2088         }
2089
2090         /* check the Phi nodes */
2091         for (phi = phi_list; phi; phi = get_irn_link(phi)) {
2092                 ir_mode *mode = get_irn_mode(phi);
2093
2094                 if (mode_is_float(mode) || get_mode_size_bits(mode) > 32)
2095                         return 0;
2096         }
2097
2098         return 1;
2099 }
2100
2101 /**
2102  * Returns the libFirm configuration parameter for this backend.
2103  */
2104 static const backend_params *ia32_get_libfirm_params(void) {
2105         static const ir_settings_if_conv_t ifconv = {
2106                 4,                    /* maxdepth, doesn't matter for Psi-conversion */
2107                 ia32_is_psi_allowed   /* allows or disallows Psi creation for given selector */
2108         };
2109         static const ir_settings_arch_dep_t ad = {
2110                 1,                   /* also use subs */
2111                 4,                   /* maximum shifts */
2112                 31,                  /* maximum shift amount */
2113                 ia32_evaluate_insn,  /* evaluate the instruction sequence */
2114
2115                 1,  /* allow Mulhs */
2116                 1,  /* allow Mulus */
2117                 32  /* Mulh allowed up to 32 bit */
2118         };
2119         static backend_params p = {
2120                 1,     /* need dword lowering */
2121                 1,     /* support inline assembly */
2122                 NULL,  /* no additional opcodes */
2123                 NULL,  /* will be set later */
2124                 ia32_create_intrinsic_fkt,
2125                 &intrinsic_env,  /* context for ia32_create_intrinsic_fkt */
2126                 NULL,  /* will be set below */
2127         };
2128
2129         ia32_setup_cg_config();
2130
2131         p.dep_param    = &ad;
2132         p.if_conv_info = &ifconv;
2133         return &p;
2134 }
2135
2136 static const lc_opt_enum_int_items_t gas_items[] = {
2137         { "elf",     GAS_FLAVOUR_ELF },
2138         { "mingw",   GAS_FLAVOUR_MINGW  },
2139         { "yasm",    GAS_FLAVOUR_YASM   },
2140         { "macho",   GAS_FLAVOUR_MACH_O },
2141         { NULL,      0 }
2142 };
2143
2144 static lc_opt_enum_int_var_t gas_var = {
2145         (int*) &be_gas_flavour, gas_items
2146 };
2147
2148 static const lc_opt_table_entry_t ia32_options[] = {
2149         LC_OPT_ENT_ENUM_INT("gasmode", "set the GAS compatibility mode", &gas_var),
2150         LC_OPT_ENT_INT("stackalign", "set stack alignment for calls",
2151                        &ia32_isa_template.arch_isa.stack_alignment),
2152         LC_OPT_LAST
2153 };
2154
2155 const arch_isa_if_t ia32_isa_if = {
2156         ia32_init,
2157         ia32_done,
2158         ia32_get_n_reg_class,
2159         ia32_get_reg_class,
2160         ia32_get_reg_class_for_mode,
2161         ia32_get_call_abi,
2162         ia32_get_irn_handler,
2163         ia32_get_code_generator_if,
2164         ia32_get_list_sched_selector,
2165         ia32_get_ilp_sched_selector,
2166         ia32_get_reg_class_alignment,
2167         ia32_get_libfirm_params,
2168         ia32_get_allowed_execution_units,
2169         ia32_get_machine,
2170         ia32_get_irg_list,
2171 };
2172
2173 void ia32_init_emitter(void);
2174 void ia32_init_finish(void);
2175 void ia32_init_optimize(void);
2176 void ia32_init_transform(void);
2177 void ia32_init_x87(void);
2178
2179 void be_init_arch_ia32(void)
2180 {
2181         lc_opt_entry_t *be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2182         lc_opt_entry_t *ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2183
2184         lc_opt_add_table(ia32_grp, ia32_options);
2185         be_register_isa_if("ia32", &ia32_isa_if);
2186
2187         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.cg");
2188
2189         ia32_init_emitter();
2190         ia32_init_finish();
2191         ia32_init_optimize();
2192         ia32_init_transform();
2193         ia32_init_x87();
2194         ia32_init_architecture();
2195 }
2196
2197 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_ia32);