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