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