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