remove #ifdef HAVE_CONFIG_Hs
[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 = arch_irn_class_normal;
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 & ~arch_irn_class_normal;
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->arch_env  = birg->main_env->arch_env;
1599         cg->birg      = birg;
1600         cg->blk_sched = NULL;
1601         cg->dump      = (birg->main_env->options->dump_flags & DUMP_BE) ? 1 : 0;
1602         cg->gprof     = (birg->main_env->options->gprof) ? 1 : 0;
1603
1604         if (cg->gprof) {
1605                 /* Linux gprof implementation needs base pointer */
1606                 birg->main_env->options->omit_fp = 0;
1607         }
1608
1609         /* enter it */
1610         isa->cg = cg;
1611
1612 #ifndef NDEBUG
1613         if (isa->name_obst) {
1614                 obstack_free(isa->name_obst, NULL);
1615                 obstack_init(isa->name_obst);
1616         }
1617 #endif /* NDEBUG */
1618
1619         cur_reg_set = cg->reg_set;
1620
1621         assert(ia32_current_cg == NULL);
1622         ia32_current_cg = cg;
1623
1624         return (arch_code_generator_t *)cg;
1625 }
1626
1627
1628
1629 /*****************************************************************
1630  *  ____             _                  _   _____  _____
1631  * |  _ \           | |                | | |_   _|/ ____|  /\
1632  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
1633  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
1634  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
1635  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
1636  *
1637  *****************************************************************/
1638
1639 /**
1640  * Set output modes for GCC
1641  */
1642 static const tarval_mode_info mo_integer = {
1643         TVO_HEX,
1644         "0x",
1645         NULL,
1646 };
1647
1648 /*
1649  * set the tarval output mode of all integer modes to decimal
1650  */
1651 static void set_tarval_output_modes(void)
1652 {
1653         int i;
1654
1655         for (i = get_irp_n_modes() - 1; i >= 0; --i) {
1656                 ir_mode *mode = get_irp_mode(i);
1657
1658                 if (mode_is_int(mode))
1659                         set_tarval_mode_output_option(mode, &mo_integer);
1660         }
1661 }
1662
1663 const arch_isa_if_t ia32_isa_if;
1664
1665 /**
1666  * The template that generates a new ISA object.
1667  * Note that this template can be changed by command line
1668  * arguments.
1669  */
1670 static ia32_isa_t ia32_isa_template = {
1671         {
1672                 &ia32_isa_if,            /* isa interface implementation */
1673                 &ia32_gp_regs[REG_ESP],  /* stack pointer register */
1674                 &ia32_gp_regs[REG_EBP],  /* base pointer register */
1675                 -1,                      /* stack direction */
1676                 2,                       /* power of two stack alignment, 2^2 == 4 */
1677                 NULL,                    /* main environment */
1678                 7,                       /* costs for a spill instruction */
1679                 5,                       /* costs for a reload instruction */
1680         },
1681         NULL,                    /* 16bit register names */
1682         NULL,                    /* 8bit register names */
1683         NULL,                    /* 8bit register names high */
1684         NULL,                    /* types */
1685         NULL,                    /* tv_ents */
1686         NULL,                    /* current code generator */
1687         NULL,                    /* abstract machine */
1688 #ifndef NDEBUG
1689         NULL,                    /* name obstack */
1690 #endif
1691 };
1692
1693 static void init_asm_constraints(void)
1694 {
1695         be_init_default_asm_constraint_flags();
1696
1697         asm_constraint_flags['a'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1698         asm_constraint_flags['b'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1699         asm_constraint_flags['c'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1700         asm_constraint_flags['d'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1701         asm_constraint_flags['D'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1702         asm_constraint_flags['S'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1703         asm_constraint_flags['Q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1704         asm_constraint_flags['q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1705         asm_constraint_flags['A'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1706         asm_constraint_flags['l'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1707         asm_constraint_flags['R'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1708         asm_constraint_flags['r'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1709         asm_constraint_flags['p'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1710         asm_constraint_flags['f'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1711         asm_constraint_flags['t'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1712         asm_constraint_flags['u'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1713         asm_constraint_flags['Y'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1714         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1715         asm_constraint_flags['n'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1716         asm_constraint_flags['g'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1717
1718         /* no support for autodecrement/autoincrement */
1719         asm_constraint_flags['<'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1720         asm_constraint_flags['>'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1721         /* no float consts */
1722         asm_constraint_flags['E'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1723         asm_constraint_flags['F'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1724         /* makes no sense on x86 */
1725         asm_constraint_flags['s'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1726         /* no support for sse consts yet */
1727         asm_constraint_flags['C'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1728         /* no support for x87 consts yet */
1729         asm_constraint_flags['G'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1730         /* no support for mmx registers yet */
1731         asm_constraint_flags['y'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1732         /* not available in 32bit mode */
1733         asm_constraint_flags['Z'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1734         asm_constraint_flags['e'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1735
1736         /* no code yet to determine register class needed... */
1737         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1738 }
1739
1740 /**
1741  * Initializes the backend ISA.
1742  */
1743 static arch_env_t *ia32_init(FILE *file_handle) {
1744         static int inited = 0;
1745         ia32_isa_t *isa;
1746         int        i, n;
1747
1748         if (inited)
1749                 return NULL;
1750         inited = 1;
1751
1752         set_tarval_output_modes();
1753
1754         isa = XMALLOC(ia32_isa_t);
1755         memcpy(isa, &ia32_isa_template, sizeof(*isa));
1756
1757         if(mode_fpcw == NULL) {
1758                 mode_fpcw = new_ir_mode("Fpcw", irms_int_number, 16, 0, irma_none, 0);
1759         }
1760
1761         ia32_register_init();
1762         ia32_create_opcodes(&ia32_irn_ops);
1763
1764         be_emit_init(file_handle);
1765         isa->regs_16bit     = pmap_create();
1766         isa->regs_8bit      = pmap_create();
1767         isa->regs_8bit_high = pmap_create();
1768         isa->types          = pmap_create();
1769         isa->tv_ent         = pmap_create();
1770         isa->cpu            = ia32_init_machine_description();
1771
1772         ia32_build_16bit_reg_map(isa->regs_16bit);
1773         ia32_build_8bit_reg_map(isa->regs_8bit);
1774         ia32_build_8bit_reg_map_high(isa->regs_8bit_high);
1775
1776 #ifndef NDEBUG
1777         isa->name_obst = XMALLOC(struct obstack);
1778         obstack_init(isa->name_obst);
1779 #endif /* NDEBUG */
1780
1781         /* enter the ISA object into the intrinsic environment */
1782         intrinsic_env.isa = isa;
1783         ia32_handle_intrinsics();
1784
1785         /* emit asm includes */
1786         n = get_irp_n_asms();
1787         for (i = 0; i < n; ++i) {
1788                 be_emit_cstring("#APP\n");
1789                 be_emit_ident(get_irp_asm(i));
1790                 be_emit_cstring("\n#NO_APP\n");
1791         }
1792
1793         /* needed for the debug support */
1794         be_gas_emit_switch_section(GAS_SECTION_TEXT);
1795         be_emit_cstring(".Ltext0:\n");
1796         be_emit_write_line();
1797
1798         /* we mark referenced global entities, so we can only emit those which
1799          * are actually referenced. (Note: you mustn't use the type visited flag
1800          * elsewhere in the backend)
1801          */
1802         inc_master_type_visited();
1803
1804         return &isa->arch_env;
1805 }
1806
1807
1808
1809 /**
1810  * Closes the output file and frees the ISA structure.
1811  */
1812 static void ia32_done(void *self) {
1813         ia32_isa_t *isa = self;
1814
1815         /* emit now all global declarations */
1816         be_gas_emit_decls(isa->arch_env.main_env, 1);
1817
1818         pmap_destroy(isa->regs_16bit);
1819         pmap_destroy(isa->regs_8bit);
1820         pmap_destroy(isa->regs_8bit_high);
1821         pmap_destroy(isa->tv_ent);
1822         pmap_destroy(isa->types);
1823
1824 #ifndef NDEBUG
1825         obstack_free(isa->name_obst, NULL);
1826 #endif /* NDEBUG */
1827
1828         be_emit_exit();
1829
1830         free(self);
1831 }
1832
1833
1834 /**
1835  * Return the number of register classes for this architecture.
1836  * We report always these:
1837  *  - the general purpose registers
1838  *  - the SSE floating point register set
1839  *  - the virtual floating point registers
1840  *  - the SSE vector register set
1841  */
1842 static unsigned ia32_get_n_reg_class(const void *self) {
1843         (void) self;
1844         return N_CLASSES;
1845 }
1846
1847 /**
1848  * Return the register class for index i.
1849  */
1850 static const arch_register_class_t *ia32_get_reg_class(const void *self,
1851                                                        unsigned i)
1852 {
1853         (void) self;
1854         assert(i < N_CLASSES);
1855         return &ia32_reg_classes[i];
1856 }
1857
1858 /**
1859  * Get the register class which shall be used to store a value of a given mode.
1860  * @param self The this pointer.
1861  * @param mode The mode in question.
1862  * @return A register class which can hold values of the given mode.
1863  */
1864 const arch_register_class_t *ia32_get_reg_class_for_mode(const void *self,
1865                 const ir_mode *mode)
1866 {
1867         (void) self;
1868
1869         if (mode_is_float(mode)) {
1870                 return ia32_cg_config.use_sse2 ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
1871         }
1872         else
1873                 return &ia32_reg_classes[CLASS_ia32_gp];
1874 }
1875
1876 /**
1877  * Get the ABI restrictions for procedure calls.
1878  * @param self        The this pointer.
1879  * @param method_type The type of the method (procedure) in question.
1880  * @param abi         The abi object to be modified
1881  */
1882 static void ia32_get_call_abi(const void *self, ir_type *method_type,
1883                               be_abi_call_t *abi)
1884 {
1885         ir_type  *tp;
1886         ir_mode  *mode;
1887         unsigned  cc;
1888         int       n, i, regnum;
1889         int                 pop_amount = 0;
1890         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
1891
1892         (void) self;
1893
1894         /* set abi flags for calls */
1895         call_flags.bits.left_to_right         = 0;  /* always last arg first on stack */
1896         call_flags.bits.store_args_sequential = 0;
1897         /* call_flags.bits.try_omit_fp                 not changed: can handle both settings */
1898         call_flags.bits.fp_free               = 0;  /* the frame pointer is fixed in IA32 */
1899         call_flags.bits.call_has_imm          = 0;  /* No call immediates, we handle this by ourselves */
1900
1901         /* set parameter passing style */
1902         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
1903
1904         if (get_method_variadicity(method_type) == variadicity_variadic) {
1905                 /* pass all parameters of a variadic function on the stack */
1906                 cc = cc_cdecl_set;
1907         } else {
1908                 cc = get_method_calling_convention(method_type);
1909                 if (get_method_additional_properties(method_type) & mtp_property_private &&
1910                     ia32_cg_config.optimize_cc) {
1911                         /* set the calling conventions to register parameter */
1912                         cc = (cc & ~cc_bits) | cc_reg_param;
1913                 }
1914         }
1915
1916         /* we have to pop the shadow parameter ourself for compound calls */
1917         if( (get_method_calling_convention(method_type) & cc_compound_ret)
1918                         && !(cc & cc_reg_param)) {
1919                 pop_amount += get_mode_size_bytes(mode_P_data);
1920         }
1921
1922         n = get_method_n_params(method_type);
1923         for (i = regnum = 0; i < n; i++) {
1924                 ir_mode               *mode;
1925                 const arch_register_t *reg = NULL;
1926
1927                 tp   = get_method_param_type(method_type, i);
1928                 mode = get_type_mode(tp);
1929                 if (mode != NULL) {
1930                         reg  = ia32_get_RegParam_reg(cc, regnum, mode);
1931                 }
1932                 if (reg != NULL) {
1933                         be_abi_call_param_reg(abi, i, reg);
1934                         ++regnum;
1935                 } else {
1936                         /* Micro optimisation: if the mode is shorter than 4 bytes, load 4 bytes.
1937                          * movl has a shorter opcode than mov[sz][bw]l */
1938                         ir_mode *load_mode = mode;
1939
1940                         if (mode != NULL) {
1941                                 unsigned size = get_mode_size_bytes(mode);
1942
1943                                 if (cc & cc_callee_clear_stk) {
1944                                         pop_amount += (size + 3U) & ~3U;
1945                                 }
1946
1947                                 if (size < 4) load_mode = mode_Iu;
1948                         }
1949
1950                         be_abi_call_param_stack(abi, i, load_mode, 4, 0, 0);
1951                 }
1952         }
1953
1954         be_abi_call_set_pop(abi, pop_amount);
1955
1956         /* set return registers */
1957         n = get_method_n_ress(method_type);
1958
1959         assert(n <= 2 && "more than two results not supported");
1960
1961         /* In case of 64bit returns, we will have two 32bit values */
1962         if (n == 2) {
1963                 tp   = get_method_res_type(method_type, 0);
1964                 mode = get_type_mode(tp);
1965
1966                 assert(!mode_is_float(mode) && "two FP results not supported");
1967
1968                 tp   = get_method_res_type(method_type, 1);
1969                 mode = get_type_mode(tp);
1970
1971                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
1972
1973                 be_abi_call_res_reg(abi, 0, &ia32_gp_regs[REG_EAX]);
1974                 be_abi_call_res_reg(abi, 1, &ia32_gp_regs[REG_EDX]);
1975         }
1976         else if (n == 1) {
1977                 const arch_register_t *reg;
1978
1979                 tp   = get_method_res_type(method_type, 0);
1980                 assert(is_atomic_type(tp));
1981                 mode = get_type_mode(tp);
1982
1983                 reg = mode_is_float(mode) ? &ia32_vfp_regs[REG_VF0] : &ia32_gp_regs[REG_EAX];
1984
1985                 be_abi_call_res_reg(abi, 0, reg);
1986         }
1987 }
1988
1989 int ia32_to_appear_in_schedule(void *block_env, const ir_node *irn)
1990 {
1991         (void) block_env;
1992
1993         if(!is_ia32_irn(irn)) {
1994                 return -1;
1995         }
1996
1997         if(is_ia32_NoReg_GP(irn) || is_ia32_NoReg_VFP(irn) || is_ia32_NoReg_XMM(irn)
1998                 || is_ia32_Unknown_GP(irn) || is_ia32_Unknown_XMM(irn)
1999                 || is_ia32_Unknown_VFP(irn) || is_ia32_ChangeCW(irn)
2000                 || is_ia32_Immediate(irn))
2001                 return 0;
2002
2003         return 1;
2004 }
2005
2006 /**
2007  * Initializes the code generator interface.
2008  */
2009 static const arch_code_generator_if_t *ia32_get_code_generator_if(void *self)
2010 {
2011         (void) self;
2012         return &ia32_code_gen_if;
2013 }
2014
2015 /**
2016  * Returns the estimated execution time of an ia32 irn.
2017  */
2018 static sched_timestep_t ia32_sched_exectime(void *env, const ir_node *irn) {
2019         (void) env;
2020         return is_ia32_irn(irn) ? ia32_get_op_estimated_cost(irn) : 1;
2021 }
2022
2023 list_sched_selector_t ia32_sched_selector;
2024
2025 /**
2026  * Returns the reg_pressure scheduler with to_appear_in_schedule() overloaded
2027  */
2028 static const list_sched_selector_t *ia32_get_list_sched_selector(
2029                 const void *self, list_sched_selector_t *selector)
2030 {
2031         (void) self;
2032         memcpy(&ia32_sched_selector, selector, sizeof(ia32_sched_selector));
2033         ia32_sched_selector.exectime              = ia32_sched_exectime;
2034         ia32_sched_selector.to_appear_in_schedule = ia32_to_appear_in_schedule;
2035         return &ia32_sched_selector;
2036 }
2037
2038 static const ilp_sched_selector_t *ia32_get_ilp_sched_selector(const void *self)
2039 {
2040         (void) self;
2041         return NULL;
2042 }
2043
2044 /**
2045  * Returns the necessary byte alignment for storing a register of given class.
2046  */
2047 static int ia32_get_reg_class_alignment(const void *self,
2048                                         const arch_register_class_t *cls)
2049 {
2050         ir_mode *mode = arch_register_class_mode(cls);
2051         int bytes     = get_mode_size_bytes(mode);
2052         (void) self;
2053
2054         if (mode_is_float(mode) && bytes > 8)
2055                 return 16;
2056         return bytes;
2057 }
2058
2059 static const be_execution_unit_t ***ia32_get_allowed_execution_units(
2060                 const void *self, const ir_node *irn)
2061 {
2062         static const be_execution_unit_t *_allowed_units_BRANCH[] = {
2063                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH1],
2064                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH2],
2065                 NULL,
2066         };
2067         static const be_execution_unit_t *_allowed_units_GP[] = {
2068                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EAX],
2069                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EBX],
2070                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_ECX],
2071                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EDX],
2072                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_ESI],
2073                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EDI],
2074                 &ia32_execution_units_GP[IA32_EXECUNIT_TP_GP_GP_EBP],
2075                 NULL,
2076         };
2077         static const be_execution_unit_t *_allowed_units_DUMMY[] = {
2078                 &be_machine_execution_units_DUMMY[0],
2079                 NULL,
2080         };
2081         static const be_execution_unit_t **_units_callret[] = {
2082                 _allowed_units_BRANCH,
2083                 NULL
2084         };
2085         static const be_execution_unit_t **_units_other[] = {
2086                 _allowed_units_GP,
2087                 NULL
2088         };
2089         static const be_execution_unit_t **_units_dummy[] = {
2090                 _allowed_units_DUMMY,
2091                 NULL
2092         };
2093         const be_execution_unit_t ***ret;
2094         (void) self;
2095
2096         if (is_ia32_irn(irn)) {
2097                 ret = get_ia32_exec_units(irn);
2098         } else if (is_be_node(irn)) {
2099                 if (be_is_Return(irn)) {
2100                         ret = _units_callret;
2101                 } else if (be_is_Barrier(irn)) {
2102                         ret = _units_dummy;
2103                 } else {
2104                         ret = _units_other;
2105                 }
2106         }
2107         else {
2108                 ret = _units_dummy;
2109         }
2110
2111         return ret;
2112 }
2113
2114 /**
2115  * Return the abstract ia32 machine.
2116  */
2117 static const be_machine_t *ia32_get_machine(const void *self) {
2118         const ia32_isa_t *isa = self;
2119         return isa->cpu;
2120 }
2121
2122 /**
2123  * Return irp irgs in the desired order.
2124  */
2125 static ir_graph **ia32_get_irg_list(const void *self, ir_graph ***irg_list)
2126 {
2127         (void) self;
2128         (void) irg_list;
2129         return NULL;
2130 }
2131
2132 static void ia32_mark_remat(const void *self, ir_node *node) {
2133         (void) self;
2134         if (is_ia32_irn(node)) {
2135                 set_ia32_is_remat(node);
2136         }
2137 }
2138
2139 /**
2140  * Allows or disallows the creation of Psi nodes for the given Phi nodes.
2141  * @return 1 if allowed, 0 otherwise
2142  */
2143 static int ia32_is_psi_allowed(ir_node *sel, ir_node *phi_list, int i, int j)
2144 {
2145         ir_node *phi;
2146         ir_node *cmp = NULL;
2147
2148         /* we can't handle psis with 64bit compares yet */
2149         if (is_Proj(sel)) {
2150                 cmp = get_Proj_pred(sel);
2151                 if (is_Cmp(cmp)) {
2152                         ir_node *left     = get_Cmp_left(cmp);
2153                         ir_mode *cmp_mode = get_irn_mode(left);
2154                         if (!mode_is_float(cmp_mode) && get_mode_size_bits(cmp_mode) > 32)
2155                                 return 0;
2156                 } else {
2157                         cmp = NULL;
2158                 }
2159         }
2160
2161         if (ia32_cg_config.use_cmov) {
2162                 if (ia32_cg_config.use_sse2 && cmp != NULL) {
2163                         pn_Cmp pn   = get_Proj_proj(sel);
2164                         ir_node *cl = get_Cmp_left(cmp);
2165                         ir_node *cr = get_Cmp_right(cmp);
2166
2167                         /* check the Phi nodes: no 64bit and no floating point cmov */
2168                         for (phi = phi_list; phi; phi = get_Phi_next(phi)) {
2169                                 ir_mode *mode = get_irn_mode(phi);
2170
2171                                 if (mode_is_float(mode)) {
2172                                         /* check for Min, Max */
2173                                         ir_node *t = get_Phi_pred(phi, i);
2174                                         ir_node *f = get_Phi_pred(phi, j);
2175                                         int res    = 0;
2176
2177                                         /* SSE2 supports Min & Max */
2178                                         if (pn == pn_Cmp_Lt || pn == pn_Cmp_Le || pn == pn_Cmp_Ge || pn == pn_Cmp_Gt) {
2179                                                 if (cl == t && cr == f) {
2180                                                         /* Psi(a <=/>= b, a, b) => MIN, MAX */
2181                                                         res = 1;
2182                                                 } else if (cl == f && cr == t) {
2183                                                         /* Psi(a <=/>= b, b, a) => MAX, MIN */
2184                                                         res = 1;
2185                                                 }
2186                                         }
2187                                         if (! res)
2188                                                 return 0;
2189
2190                                 } else if (get_mode_size_bits(mode) > 32)
2191                                         return 0;
2192                         }
2193                 } else {
2194                         /* check the Phi nodes: no 64bit and no floating point cmov */
2195                         for (phi = phi_list; phi; phi = get_Phi_next(phi)) {
2196                                 ir_mode *mode = get_irn_mode(phi);
2197
2198                                 if (mode_is_float(mode) || get_mode_size_bits(mode) > 32)
2199                                         return 0;
2200                         }
2201                 }
2202
2203                 return 1;
2204         } else {
2205                 ir_node *cl, *cr;
2206                 pn_Cmp  pn;
2207
2208                 /* No cmov, only some special cases */
2209                 if (cmp == NULL)
2210                         return 0;
2211
2212                 /* Now some supported cases here */
2213                 pn = get_Proj_proj(sel);
2214                 cl = get_Cmp_left(cmp);
2215                 cr = get_Cmp_right(cmp);
2216
2217                 for (phi = phi_list; phi; phi = get_Phi_next(phi)) {
2218                         ir_mode *mode = get_irn_mode(phi);
2219                         int res = 0;
2220                         ir_node *t, *f;
2221
2222                         t = get_Phi_pred(phi, i);
2223                         f = get_Phi_pred(phi, j);
2224
2225                         /* no floating point and no 64bit yet */
2226                         if (mode_is_float(mode) || get_mode_size_bits(mode) > 32)
2227                                 return 0;
2228
2229                         if (is_Const(t) && is_Const(f)) {
2230                                 if ((is_Const_null(t) && is_Const_one(f)) || (is_Const_one(t) && is_Const_null(f))) {
2231                                         /* always support Psi(x, C1, C2) */
2232                                         res = 1;
2233                                 }
2234                         } else if (pn == pn_Cmp_Lt || pn == pn_Cmp_Le || pn == pn_Cmp_Ge || pn == pn_Cmp_Gt) {
2235                                 if (0) {
2236 #if 0
2237                                 } else if (cl == t && cr == f) {
2238                                         /* Psi(a <=/>= b, a, b) => Min, Max */
2239                                         res = 1;
2240                                 } else if (cl == f && cr == t) {
2241                                         /* Psi(a <=/>= b, b, a) => Max, Min */
2242                                         res = 1;
2243 #endif
2244                                 } else if ((pn & pn_Cmp_Gt) && !mode_is_signed(mode) &&
2245                                            is_Const(f) && is_Const_null(f) && is_Sub(t) &&
2246                                            get_Sub_left(t) == cl && get_Sub_right(t) == cr) {
2247                                         /* Psi(a >=u b, a - b, 0) unsigned Doz */
2248                                         res = 1;
2249                                 } else if ((pn & pn_Cmp_Lt) && !mode_is_signed(mode) &&
2250                                            is_Const(t) && is_Const_null(t) && is_Sub(f) &&
2251                                            get_Sub_left(f) == cl && get_Sub_right(f) == cr) {
2252                                         /* Psi(a <=u b, 0, a - b) unsigned Doz */
2253                                         res = 1;
2254                                 } else if (is_Const(cr) && is_Const_null(cr)) {
2255                                         if (cl == t && is_Minus(f) && get_Minus_op(f) == cl) {
2256                                                 /* Psi(a <=/>= 0 ? a : -a) Nabs/Abs */
2257                                                 res = 1;
2258                                         } else if (cl == f && is_Minus(t) && get_Minus_op(t) == cl) {
2259                                                 /* Psi(a <=/>= 0 ? -a : a) Abs/Nabs */
2260                                                 res = 1;
2261                                         }
2262                                 }
2263                         }
2264                         if (! res)
2265                                 return 0;
2266                 }
2267                 /* all checks passed */
2268                 return 1;
2269         }
2270         return 0;
2271 }
2272
2273 static asm_constraint_flags_t ia32_parse_asm_constraint(const void *self, const char **c)
2274 {
2275         (void) self;
2276         (void) c;
2277
2278         /* we already added all our simple flags to the flags modifier list in
2279          * init, so this flag we don't know. */
2280         return ASM_CONSTRAINT_FLAG_INVALID;
2281 }
2282
2283 static int ia32_is_valid_clobber(const void *self, const char *clobber)
2284 {
2285         (void) self;
2286
2287         return ia32_get_clobber_register(clobber) != NULL;
2288 }
2289
2290 /**
2291  * Returns the libFirm configuration parameter for this backend.
2292  */
2293 static const backend_params *ia32_get_libfirm_params(void) {
2294         static const ir_settings_if_conv_t ifconv = {
2295                 4,                    /* maxdepth, doesn't matter for Psi-conversion */
2296                 ia32_is_psi_allowed   /* allows or disallows Psi creation for given selector */
2297         };
2298         static const ir_settings_arch_dep_t ad = {
2299                 1,                   /* also use subs */
2300                 4,                   /* maximum shifts */
2301                 31,                  /* maximum shift amount */
2302                 ia32_evaluate_insn,  /* evaluate the instruction sequence */
2303
2304                 1,  /* allow Mulhs */
2305                 1,  /* allow Mulus */
2306                 32  /* Mulh allowed up to 32 bit */
2307         };
2308         static backend_params p = {
2309                 1,     /* need dword lowering */
2310                 1,     /* support inline assembly */
2311                 0,     /* no immediate floating point mode. */
2312                 NULL,  /* no additional opcodes */
2313                 NULL,  /* will be set later */
2314                 ia32_create_intrinsic_fkt,
2315                 &intrinsic_env,  /* context for ia32_create_intrinsic_fkt */
2316                 NULL,  /* will be set below */
2317                 NULL   /* will be set below */
2318         };
2319
2320         ia32_setup_cg_config();
2321
2322         /* doesn't really belong here, but this is the earliest place the backend
2323          * is called... */
2324         init_asm_constraints();
2325
2326         p.dep_param    = &ad;
2327         p.if_conv_info = &ifconv;
2328         return &p;
2329 }
2330
2331 static const lc_opt_enum_int_items_t gas_items[] = {
2332         { "elf",     GAS_FLAVOUR_ELF },
2333         { "mingw",   GAS_FLAVOUR_MINGW  },
2334         { "yasm",    GAS_FLAVOUR_YASM   },
2335         { "macho",   GAS_FLAVOUR_MACH_O },
2336         { NULL,      0 }
2337 };
2338
2339 static lc_opt_enum_int_var_t gas_var = {
2340         (int*) &be_gas_flavour, gas_items
2341 };
2342
2343 static const lc_opt_enum_int_items_t transformer_items[] = {
2344         { "default", TRANSFORMER_DEFAULT },
2345 #ifdef FIRM_GRGEN_BE
2346         { "pbqp",    TRANSFORMER_PBQP    },
2347         { "random",  TRANSFORMER_RAND    },
2348 #endif
2349         { NULL,      0                   }
2350 };
2351
2352 static lc_opt_enum_int_var_t transformer_var = {
2353         (int*)&be_transformer, transformer_items
2354 };
2355
2356 static const lc_opt_table_entry_t ia32_options[] = {
2357         LC_OPT_ENT_ENUM_INT("gasmode", "set the GAS compatibility mode", &gas_var),
2358         LC_OPT_ENT_ENUM_INT("transformer", "the transformer used for code selection", &transformer_var),
2359         LC_OPT_ENT_INT("stackalign", "set power of two stack alignment for calls",
2360                        &ia32_isa_template.arch_env.stack_alignment),
2361         LC_OPT_LAST
2362 };
2363
2364 const arch_isa_if_t ia32_isa_if = {
2365         ia32_init,
2366         ia32_done,
2367         ia32_get_n_reg_class,
2368         ia32_get_reg_class,
2369         ia32_get_reg_class_for_mode,
2370         ia32_get_call_abi,
2371         ia32_get_code_generator_if,
2372         ia32_get_list_sched_selector,
2373         ia32_get_ilp_sched_selector,
2374         ia32_get_reg_class_alignment,
2375         ia32_get_libfirm_params,
2376         ia32_get_allowed_execution_units,
2377         ia32_get_machine,
2378         ia32_get_irg_list,
2379         ia32_mark_remat,
2380         ia32_parse_asm_constraint,
2381         ia32_is_valid_clobber
2382 };
2383
2384 void ia32_init_emitter(void);
2385 void ia32_init_finish(void);
2386 void ia32_init_optimize(void);
2387 void ia32_init_transform(void);
2388 void ia32_init_x87(void);
2389
2390 void be_init_arch_ia32(void)
2391 {
2392         lc_opt_entry_t *be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2393         lc_opt_entry_t *ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2394
2395         lc_opt_add_table(ia32_grp, ia32_options);
2396         be_register_isa_if("ia32", &ia32_isa_if);
2397
2398         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.cg");
2399
2400         ia32_init_emitter();
2401         ia32_init_finish();
2402         ia32_init_optimize();
2403         ia32_init_transform();
2404         ia32_init_x87();
2405         ia32_init_architecture();
2406 }
2407
2408 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_ia32);