fixed CopyB emitter
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 /**
2  * This file implements the node emitter.
3  * @author Christian Wuerdig
4  * $Id$
5  */
6
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include <limits.h>
12
13 #include "xmalloc.h"
14 #include "tv.h"
15 #include "iredges.h"
16 #include "debug.h"
17 #include "irgwalk.h"
18 #include "irprintf.h"
19 #include "irop_t.h"
20 #include "irargs_t.h"
21 #include "irprog_t.h"
22 #include "iredges_t.h"
23
24 #include "../besched_t.h"
25 #include "../benode_t.h"
26
27 #include "ia32_emitter.h"
28 #include "gen_ia32_emitter.h"
29 #include "gen_ia32_regalloc_if.h"
30 #include "ia32_nodes_attr.h"
31 #include "ia32_new_nodes.h"
32 #include "ia32_map_regs.h"
33 #include "bearch_ia32_t.h"
34
35 #define BLOCK_PREFIX(x) ".L" x
36
37 #define SNPRINTF_BUF_LEN 128
38
39 /* global arch_env for lc_printf functions */
40 static const arch_env_t *arch_env = NULL;
41
42 /** by default, we generate assembler code for the Linux gas */
43 asm_flavour_t asm_flavour = ASM_LINUX_GAS;
44
45 /**
46  * Switch to a new section
47  */
48 void ia32_switch_section(FILE *F, section_t sec) {
49         static section_t curr_sec = NO_SECTION;
50         static const char *text[ASM_MAX][SECTION_MAX] = {
51                 {
52                         ".section\t.text", ".section\t.data", ".section\t.rodata", ".section\t.text"
53                 },
54                 {
55                         ".section\t.text", ".section\t.data", ".section .rdata,\"dr\"", ".section\t.text"
56                 }
57         };
58
59         if (curr_sec == sec)
60                 return;
61
62         curr_sec = sec;
63         switch (sec) {
64
65         case NO_SECTION:
66                 break;
67
68         case SECTION_TEXT:
69         case SECTION_DATA:
70         case SECTION_RODATA:
71         case SECTION_COMMON:
72                 fprintf(F, "\t%s\n", text[asm_flavour][sec]);
73         }
74 }
75
76 static void ia32_dump_function_object(FILE *F, const char *name)
77 {
78         switch (asm_flavour) {
79         case ASM_LINUX_GAS:
80                 fprintf(F, "\t.type\t%s, @function\n", name);
81                 break;
82         case ASM_MINGW_GAS:
83                 fprintf(F, "\t.def\t%s;\t.scl\t2;\t.type\t32;\t.endef\n", name);
84                 break;
85         }
86 }
87
88 static void ia32_dump_function_size(FILE *F, const char *name)
89 {
90         switch (asm_flavour) {
91         case ASM_LINUX_GAS:
92                 fprintf(F, "\t.size\t%s, .-%s\n", name, name);
93                 break;
94         }
95 }
96
97 /*************************************************************
98  *             _       _    __   _          _
99  *            (_)     | |  / _| | |        | |
100  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
101  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
102  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
103  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
104  * | |                                       | |
105  * |_|                                       |_|
106  *************************************************************/
107
108 static INLINE int be_is_unknown_reg(const arch_register_t *reg) {
109         return \
110                 REGS_ARE_EQUAL(reg, &ia32_gp_regs[REG_GP_UKNWN])   || \
111                 REGS_ARE_EQUAL(reg, &ia32_xmm_regs[REG_XMM_UKNWN]) || \
112                 REGS_ARE_EQUAL(reg, &ia32_vfp_regs[REG_VFP_UKNWN]);
113 }
114
115 /**
116  * returns true if a node has x87 registers
117  */
118 static INLINE int has_x87_register(const ir_node *n) {
119         return is_irn_machine_user(n, 0);
120 }
121
122 /* We always pass the ir_node which is a pointer. */
123 static int ia32_get_arg_type(const lc_arg_occ_t *occ) {
124         return lc_arg_type_ptr;
125 }
126
127
128 /**
129  * Returns the register at in position pos.
130  */
131 static const arch_register_t *get_in_reg(const ir_node *irn, int pos) {
132         ir_node                *op;
133         const arch_register_t  *reg = NULL;
134
135         assert(get_irn_arity(irn) > pos && "Invalid IN position");
136
137         /* The out register of the operator at position pos is the
138            in register we need. */
139         op = get_irn_n(irn, pos);
140
141         reg = arch_get_irn_register(arch_env, op);
142
143         assert(reg && "no in register found");
144
145         /* in case of unknown: just return a register */
146         if (REGS_ARE_EQUAL(reg, &ia32_gp_regs[REG_GP_UKNWN]))
147                 reg = &ia32_gp_regs[REG_EAX];
148         else if (REGS_ARE_EQUAL(reg, &ia32_xmm_regs[REG_XMM_UKNWN]))
149                 reg = &ia32_xmm_regs[REG_XMM0];
150         else if (REGS_ARE_EQUAL(reg, &ia32_vfp_regs[REG_VFP_UKNWN]))
151                 reg = &ia32_vfp_regs[REG_VF0];
152
153         return reg;
154 }
155
156 /**
157  * Returns the register at out position pos.
158  */
159 static const arch_register_t *get_out_reg(const ir_node *irn, int pos) {
160         ir_node                *proj;
161         const arch_register_t  *reg = NULL;
162
163         /* 1st case: irn is not of mode_T, so it has only                 */
164         /*           one OUT register -> good                             */
165         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
166         /*           Proj with the corresponding projnum for the register */
167
168         if (get_irn_mode(irn) != mode_T) {
169                 reg = arch_get_irn_register(arch_env, irn);
170         }
171         else if (is_ia32_irn(irn)) {
172                 reg = get_ia32_out_reg(irn, pos);
173         }
174         else {
175                 const ir_edge_t *edge;
176
177                 foreach_out_edge(irn, edge) {
178                         proj = get_edge_src_irn(edge);
179                         assert(is_Proj(proj) && "non-Proj from mode_T node");
180                         if (get_Proj_proj(proj) == pos) {
181                                 reg = arch_get_irn_register(arch_env, proj);
182                                 break;
183                         }
184                 }
185         }
186
187         assert(reg && "no out register found");
188         return reg;
189 }
190
191 enum io_direction {
192   IN_REG,
193   OUT_REG
194 };
195
196 /**
197  * Returns the name of the in register at position pos.
198  */
199 static const char *get_ia32_reg_name(ir_node *irn, int pos, enum io_direction in_out) {
200         const arch_register_t *reg;
201
202         if (in_out == IN_REG) {
203                 reg = get_in_reg(irn, pos);
204
205                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]) {
206                         /* FIXME: works for binop only */
207                         assert(2 <= pos && pos <= 3);
208                         reg = get_ia32_attr(irn)->x87[pos - 2];
209                 }
210         }
211         else {
212                 /* destination address mode nodes don't have outputs */
213                 if (is_ia32_irn(irn) && get_ia32_op_type(irn) == ia32_AddrModeD) {
214                         return "MEM";
215                 }
216
217                 reg = get_out_reg(irn, pos);
218                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp])
219                         reg = get_ia32_attr(irn)->x87[pos + 2];
220         }
221         return arch_register_get_name(reg);
222 }
223
224 /**
225  * Get the register name for a node.
226  */
227 static int ia32_get_reg_name(lc_appendable_t *app,
228     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
229 {
230         const char *buf;
231         ir_node    *irn = arg->v_ptr;
232         int         nr = occ->width - 1;
233
234         if (! irn)
235                 return lc_appendable_snadd(app, "(null)", 6);
236
237         buf = get_ia32_reg_name(irn, nr, occ->conversion == 'S' ? IN_REG : OUT_REG);
238
239         /* append the stupid % to register names */
240         lc_appendable_chadd(app, '%');
241         return lc_appendable_snadd(app, buf, strlen(buf));
242 }
243
244 /**
245  * Get the x87 register name for a node.
246  */
247 static int ia32_get_x87_name(lc_appendable_t *app,
248     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
249 {
250         const char *buf;
251         ir_node     *irn = arg->v_ptr;
252         int         nr = occ->width - 1;
253         ia32_attr_t *attr;
254
255         if (! irn)
256                 return lc_appendable_snadd(app, "(null)", 6);
257
258         attr = get_ia32_attr(irn);
259         buf = attr->x87[nr]->name;
260         lc_appendable_chadd(app, '%');
261         return lc_appendable_snadd(app, buf, strlen(buf));
262 }
263
264 /**
265  * Returns the tarval, offset or scale of an ia32 as a string.
266  */
267 static int ia32_const_to_str(lc_appendable_t *app,
268     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
269 {
270         const char *buf;
271         ir_node    *irn = arg->v_ptr;
272
273         if (! irn)
274                 return lc_arg_append(app, occ, "(null)", 6);
275
276         if (occ->conversion == 'C') {
277                 buf = get_ia32_cnst(irn);
278         }
279         else { /* 'O' */
280                 buf = get_ia32_am_offs(irn);
281         }
282
283         return buf ? lc_appendable_snadd(app, buf, strlen(buf)) : 0;
284 }
285
286 /**
287  * Determines the SSE suffix depending on the mode.
288  */
289 static int ia32_get_mode_suffix(lc_appendable_t *app,
290     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
291 {
292         ir_node *irn  = arg->v_ptr;
293         ir_mode *mode = get_irn_mode(irn);
294
295         if (mode == mode_T) {
296                 mode = (is_ia32_Ld(irn) || is_ia32_St(irn)) ? get_ia32_ls_mode(irn) : get_ia32_res_mode(irn);
297         }
298
299         if (! irn)
300                 return lc_arg_append(app, occ, "(null)", 6);
301
302         if (mode_is_float(mode)) {
303                 return lc_appendable_chadd(app, get_mode_size_bits(mode) == 32 ? 's' : 'd');
304         }
305         else {
306                 return lc_appendable_chadd(app, mode_is_signed(mode) ? 's' : 'z');
307         }
308 }
309
310 /**
311  * Return the ia32 printf arg environment.
312  * We use the firm environment with some additional handlers.
313  */
314 const lc_arg_env_t *ia32_get_arg_env(void) {
315         static lc_arg_env_t *env = NULL;
316
317         static const lc_arg_handler_t ia32_reg_handler   = { ia32_get_arg_type, ia32_get_reg_name };
318         static const lc_arg_handler_t ia32_const_handler = { ia32_get_arg_type, ia32_const_to_str };
319         static const lc_arg_handler_t ia32_mode_handler  = { ia32_get_arg_type, ia32_get_mode_suffix };
320         static const lc_arg_handler_t ia32_x87_handler   = { ia32_get_arg_type, ia32_get_x87_name };
321
322         if(env == NULL) {
323                 /* extend the firm printer */
324                 env = firm_get_arg_env();
325
326                 lc_arg_register(env, "ia32:sreg", 'S', &ia32_reg_handler);
327                 lc_arg_register(env, "ia32:dreg", 'D', &ia32_reg_handler);
328                 lc_arg_register(env, "ia32:cnst", 'C', &ia32_const_handler);
329                 lc_arg_register(env, "ia32:offs", 'O', &ia32_const_handler);
330                 lc_arg_register(env, "ia32:mode", 'M', &ia32_mode_handler);
331                 lc_arg_register(env, "ia32:x87",  'X', &ia32_x87_handler);
332         }
333
334         return env;
335 }
336
337 static const char *ia32_get_reg_name_for_mode(ia32_emit_env_t *env, ir_mode *mode, const arch_register_t *reg) {
338         switch(get_mode_size_bits(mode)) {
339                 case 8:
340                         return ia32_get_mapped_reg_name(env->isa->regs_8bit, reg);
341                 case 16:
342                         return ia32_get_mapped_reg_name(env->isa->regs_16bit, reg);
343                 default:
344                         return (char *)arch_register_get_name(reg);
345         }
346 }
347
348 /**
349  * Emits registers and/or address mode of a binary operation.
350  */
351 const char *ia32_emit_binop(const ir_node *n, ia32_emit_env_t *env) {
352         static char *buf = NULL;
353
354         /* verify that this function is never called on non-AM supporting operations */
355         //assert(get_ia32_am_support(n) != ia32_am_None && "emit binop expects addressmode support");
356
357 #define PRODUCES_RESULT(n)   \
358         (!(is_ia32_St(n)      || \
359         is_ia32_Store8Bit(n)  || \
360         is_ia32_CondJmp(n)    || \
361         is_ia32_xCondJmp(n)   || \
362         is_ia32_CmpSet(n)     || \
363         is_ia32_xCmpSet(n)    || \
364         is_ia32_SwitchJmp(n)))
365
366         if (! buf) {
367                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
368         }
369         else {
370                 memset(buf, 0, SNPRINTF_BUF_LEN);
371         }
372
373         switch(get_ia32_op_type(n)) {
374                 case ia32_Normal:
375                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
376                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%3S, %s", n, get_ia32_cnst(n));
377                         }
378                         else {
379                                 const arch_register_t *in1 = get_in_reg(n, 2);
380                                 const arch_register_t *in2 = get_in_reg(n, 3);
381                                 const arch_register_t *out = PRODUCES_RESULT(n) ? get_out_reg(n, 0) : NULL;
382                                 const arch_register_t *in;
383                                 const char            *in_name;
384
385                                 in      = out ? (REGS_ARE_EQUAL(out, in2) ? in1 : in2) : in2;
386                                 out     = out ? out : in1;
387                                 in_name = arch_register_get_name(in);
388
389                                 if (is_ia32_emit_cl(n)) {
390                                         assert(REGS_ARE_EQUAL(&ia32_gp_regs[REG_ECX], in) && "shift operation needs ecx");
391                                         in_name = "cl";
392                                 }
393
394                                 snprintf(buf, SNPRINTF_BUF_LEN, "%%%s, %%%s", arch_register_get_name(out), in_name);
395                         }
396                         break;
397                 case ia32_AddrModeS:
398                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
399                                 assert(! PRODUCES_RESULT(n) && "Source AM with Const must not produce result");
400                                 snprintf(buf, SNPRINTF_BUF_LEN, "%s, %s", get_ia32_cnst(n), ia32_emit_am(n, env));
401                         }
402                         else {
403                                 if (PRODUCES_RESULT(n)) {
404                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, ia32_emit_am(n, env));
405                                 }
406                                 else {
407                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%3S, %s", n, ia32_emit_am(n, env));
408                                 }
409                         }
410                         break;
411                 case ia32_AddrModeD:
412                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
413                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s,%s%s",
414                                         ia32_emit_am(n, env),
415                                         is_ia32_ImmSymConst(n) ? " OFFSET FLAT:" : " ",  /* In case of a symconst we must add OFFSET to */
416                                         get_ia32_cnst(n));                               /* tell the assembler to store it's address.   */
417                         }
418                         else {
419                                 const arch_register_t *in1 = get_in_reg(n, 2);
420                                 ir_mode              *mode = get_ia32_res_mode(n);
421                                 const char           *in_name;
422
423                                 mode    = mode ? mode : get_ia32_ls_mode(n);
424                                 in_name = ia32_get_reg_name_for_mode(env, mode, in1);
425
426                                 if (is_ia32_emit_cl(n)) {
427                                         assert(REGS_ARE_EQUAL(&ia32_gp_regs[REG_ECX], in1) && "shift operation needs ecx");
428                                         in_name = "cl";
429                                 }
430
431                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %%%s", ia32_emit_am(n, env), in_name);
432                         }
433                         break;
434                 default:
435                         assert(0 && "unsupported op type");
436         }
437
438 #undef PRODUCES_RESULT
439
440         return buf;
441 }
442
443 /**
444  * Returns the xxx PTR string for a given mode
445  *
446  * @param mode      the mode
447  * @param x87_insn  if non-zero returns the string for a x87 instruction
448  *                  else for a SSE instruction
449  */
450 static const char *pointer_size(ir_mode *mode, int x87_insn)
451 {
452         if (mode) {
453                 switch (get_mode_size_bits(mode)) {
454                 case 8:  return "BYTE PTR";
455                 case 16: return "WORD PTR";
456                 case 32: return "DWORD PTR";
457                 case 64:
458                         if (x87_insn)
459                                 return "QWORD PTR";
460                         return NULL;
461                 case 80:
462                 case 96: return "XWORD PTR";
463                 default: return NULL;
464                 }
465         }
466         return NULL;
467 }
468
469 /**
470  * Emits registers and/or address mode of a binary operation.
471  */
472 const char *ia32_emit_x87_binop(const ir_node *n, ia32_emit_env_t *env) {
473         static char *buf = NULL;
474
475         /* verify that this function is never called on non-AM supporting operations */
476         //assert(get_ia32_am_support(n) != ia32_am_None && "emit binop expects addressmode support");
477
478         if (! buf) {
479                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
480         }
481         else {
482                 memset(buf, 0, SNPRINTF_BUF_LEN);
483         }
484
485         switch(get_ia32_op_type(n)) {
486                 case ia32_Normal:
487                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
488                                 ir_mode *mode = get_ia32_ls_mode(n);
489                                 const char *p = pointer_size(mode, 1);
490                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s %s", p, get_ia32_cnst(n));
491                         }
492                         else {
493                                 ia32_attr_t *attr = get_ia32_attr(n);
494                                 const arch_register_t *in1 = attr->x87[0];
495                                 const arch_register_t *in2 = attr->x87[1];
496                                 const arch_register_t *out = attr->x87[2];
497                                 const arch_register_t *in;
498                                 const char            *in_name;
499
500                                 in      = out ? (REGS_ARE_EQUAL(out, in2) ? in1 : in2) : in2;
501                                 out     = out ? out : in1;
502                                 in_name = arch_register_get_name(in);
503
504                                 snprintf(buf, SNPRINTF_BUF_LEN, "%%%s, %%%s", arch_register_get_name(out), in_name);
505                         }
506                         break;
507                 case ia32_AddrModeS:
508                 case ia32_AddrModeD:
509                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s", ia32_emit_am(n, env));
510                         break;
511                 default:
512                         assert(0 && "unsupported op type");
513         }
514
515         return buf;
516 }
517
518 /**
519  * Emits registers and/or address mode of a unary operation.
520  */
521 const char *ia32_emit_unop(const ir_node *n, ia32_emit_env_t *env) {
522         static char *buf = NULL;
523
524         if (! buf) {
525                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
526         }
527         else {
528                 memset(buf, 0, SNPRINTF_BUF_LEN);
529         }
530
531         switch(get_ia32_op_type(n)) {
532                 case ia32_Normal:
533                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
534                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%C", n);
535                         }
536                         else {
537                                 if (is_ia32_MulS(n) || is_ia32_Mulh(n)) {
538                                         /* MulS and Mulh implicitly multiply by EAX */
539                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%4S", n);
540                                 }
541                                 else
542                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
543                         }
544                         break;
545                 case ia32_AddrModeD:
546                         snprintf(buf, SNPRINTF_BUF_LEN, "%s", ia32_emit_am(n, env));
547                         break;
548                 default:
549                         assert(0 && "unsupported op type");
550         }
551
552         return buf;
553 }
554
555 /**
556  * Emits address mode.
557  */
558 const char *ia32_emit_am(const ir_node *n, ia32_emit_env_t *env) {
559         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
560         int               had_output = 0;
561         char              *s;
562         const char        *p;
563         int               size;
564         static struct obstack *obst  = NULL;
565         ir_mode *mode = get_ia32_ls_mode(n);
566
567         if (! is_ia32_Lea(n))
568                 assert(mode && "AM node must have ls_mode attribute set.");
569
570         if (! obst) {
571                 obst = xcalloc(1, sizeof(*obst));
572         }
573         else {
574                 obstack_free(obst, NULL);
575         }
576
577         /* obstack_free with NULL results in an uninitialized obstack */
578         obstack_init(obst);
579
580         p = pointer_size(mode, has_x87_register(n));
581         if (p)
582                 obstack_printf(obst, "%s ", p);
583
584         /* emit address mode symconst */
585         if (get_ia32_am_sc(n)) {
586                 if (is_ia32_am_sc_sign(n))
587                         obstack_printf(obst, "-");
588                 obstack_printf(obst, "%s", get_id_str(get_ia32_am_sc(n)));
589         }
590
591         if (am_flav & ia32_B) {
592                 obstack_printf(obst, "[");
593                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
594                 had_output = 1;
595         }
596
597         if (am_flav & ia32_I) {
598                 if (had_output) {
599                         obstack_printf(obst, "+");
600                 }
601                 else {
602                         obstack_printf(obst, "[");
603                 }
604
605                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
606
607                 if (am_flav & ia32_S) {
608                         obstack_printf(obst, "*%d", 1 << get_ia32_am_scale(n));
609                 }
610
611                 had_output = 1;
612         }
613
614         if (am_flav & ia32_O) {
615                 s = get_ia32_am_offs(n);
616
617                 if (s) {
618                         /* omit explicit + if there was no base or index */
619                         if (! had_output) {
620                                 obstack_printf(obst, "[");
621                                 if (s[0] == '+')
622                                         s++;
623                         }
624
625                         obstack_printf(obst, s);
626                         had_output = 1;
627                 }
628         }
629
630         if (had_output)
631                 obstack_printf(obst, "] ");
632
633         size        = obstack_object_size(obst);
634         s           = obstack_finish(obst);
635         s[size - 1] = '\0';
636
637         return s;
638 }
639
640 /**
641  * emit an address
642  */
643 const char *ia32_emit_adr(const ir_node *irn, ia32_emit_env_t *env)
644 {
645         static char buf[SNPRINTF_BUF_LEN];
646         ir_mode    *mode = get_ia32_ls_mode(irn);
647         const char *adr  = get_ia32_cnst(irn);
648         const char *pref = pointer_size(mode, has_x87_register(irn));
649
650         snprintf(buf, SNPRINTF_BUF_LEN, "%s %s", pref ? pref : "", adr);
651         return buf;
652 }
653
654 /**
655  * Formated print of commands and comments.
656  */
657 static void ia32_fprintf_format(FILE *F, const ir_node *irn, char *cmd_buf, char *cmnt_buf) {
658         unsigned lineno;
659         const char *name = irn ? be_retrieve_dbg_info(get_irn_dbg_info((ir_node *)irn), &lineno) : NULL;
660
661         if (name)
662                 fprintf(F, "\t%-35s %-60s /* %s:%u */\n", cmd_buf, cmnt_buf, name, lineno);
663         else
664                 fprintf(F, "\t%-35s %-60s\n", cmd_buf, cmnt_buf);
665 }
666
667
668
669 /**
670  * Add a number to a prefix. This number will not be used a second time.
671  */
672 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
673         static unsigned long id = 0;
674         snprintf(buf, buflen, "%s%lu", prefix, ++id);
675         return buf;
676 }
677
678
679
680 /*************************************************
681  *                 _ _                         _
682  *                (_) |                       | |
683  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
684  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
685  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
686  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
687  *
688  *************************************************/
689
690 #undef IA32_DO_EMIT
691 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
692
693 /*
694  * coding of conditions
695  */
696 struct cmp2conditon_t {
697         const char *name;
698         pn_Cmp      num;
699 };
700
701 /*
702  * positive conditions for signed compares
703  */
704 static const struct cmp2conditon_t cmp2condition_s[] = {
705   { NULL,              pn_Cmp_False },  /* always false */
706   { "e",               pn_Cmp_Eq },     /* == */
707   { "l",               pn_Cmp_Lt },     /* < */
708   { "le",              pn_Cmp_Le },     /* <= */
709   { "g",               pn_Cmp_Gt },     /* > */
710   { "ge",              pn_Cmp_Ge },     /* >= */
711   { "ne",              pn_Cmp_Lg },     /* != */
712   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
713   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
714   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
715   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
716   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
717   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
718   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
719   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
720   { NULL,              pn_Cmp_True },   /* always true */
721 };
722
723 /*
724  * positive conditions for unsigned compares
725  */
726 static const struct cmp2conditon_t cmp2condition_u[] = {
727         { NULL,              pn_Cmp_False },  /* always false */
728         { "e",               pn_Cmp_Eq },     /* == */
729         { "b",               pn_Cmp_Lt },     /* < */
730         { "be",              pn_Cmp_Le },     /* <= */
731         { "a",               pn_Cmp_Gt },     /* > */
732         { "ae",              pn_Cmp_Ge },     /* >= */
733         { "ne",              pn_Cmp_Lg },     /* != */
734         { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
735         { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
736         { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
737         { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
738         { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
739         { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
740         { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
741         { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
742         { NULL,              pn_Cmp_True },   /* always true */
743 };
744
745 /*
746  * returns the condition code
747  */
748 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
749 {
750         assert(cmp2condition_s[cmp_code].num == cmp_code);
751         assert(cmp2condition_u[cmp_code].num == cmp_code);
752
753         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
754 }
755
756 /**
757  * Returns the target block for a control flow node.
758  */
759 static ir_node *get_cfop_target_block(const ir_node *irn) {
760         return get_irn_link(irn);
761 }
762
763 /**
764  * Returns the target label for a control flow node.
765  */
766 static char *get_cfop_target(const ir_node *irn, char *buf) {
767         ir_node *bl = get_cfop_target_block(irn);
768
769         snprintf(buf, SNPRINTF_BUF_LEN, BLOCK_PREFIX("%ld"), get_irn_node_nr(bl));
770         return buf;
771 }
772
773 /** Return the next block in Block schedule */
774 static ir_node *next_blk_sched(const ir_node *block) {
775         return get_irn_link(block);
776 }
777
778 /**
779  * Returns the Proj with projection number proj and NOT mode_M
780  */
781 static ir_node *get_proj(const ir_node *irn, long proj) {
782         const ir_edge_t *edge;
783         ir_node         *src;
784
785         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
786
787         foreach_out_edge(irn, edge) {
788                 src = get_edge_src_irn(edge);
789
790                 assert(is_Proj(src) && "Proj expected");
791                 if (get_irn_mode(src) == mode_M)
792                         continue;
793
794                 if (get_Proj_proj(src) == proj)
795                         return src;
796         }
797         return NULL;
798 }
799
800 /**
801  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
802  */
803 static void finish_CondJmp(FILE *F, const ir_node *irn, ir_mode *mode) {
804         const ir_node   *proj1, *proj2 = NULL;
805         const ir_node   *block, *next_bl = NULL;
806         char buf[SNPRINTF_BUF_LEN];
807         char cmd_buf[SNPRINTF_BUF_LEN];
808         char cmnt_buf[SNPRINTF_BUF_LEN];
809
810         /* get both Proj's */
811         proj1 = get_proj(irn, pn_Cond_true);
812         assert(proj1 && "CondJmp without true Proj");
813
814         proj2 = get_proj(irn, pn_Cond_false);
815         assert(proj2 && "CondJmp without false Proj");
816
817         /* for now, the code works for scheduled and non-schedules blocks */
818         block = get_nodes_block(irn);
819
820         /* we have a block schedule */
821         next_bl = next_blk_sched(block);
822
823         if (get_cfop_target_block(proj1) == next_bl) {
824                 /* exchange both proj's so the second one can be omitted */
825                 const ir_node *t = proj1;
826                 proj1 = proj2;
827                 proj2 = t;
828         }
829
830         /* the first Proj must always be created */
831         if (get_Proj_proj(proj1) == pn_Cond_true) {
832                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
833                                         get_cmp_suffix(get_ia32_pncode(irn), ! mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
834                                         get_cfop_target(proj1, buf));
835                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == TRUE */");
836         }
837         else  {
838                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
839                                         get_cmp_suffix(get_negated_pnc(get_ia32_pncode(irn), mode),
840                                         ! mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
841                                         get_cfop_target(proj1, buf));
842                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == FALSE */");
843         }
844         IA32_DO_EMIT(irn);
845
846         /* the second Proj might be a fallthrough */
847         if (get_cfop_target_block(proj2) != next_bl) {
848                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(proj2, buf));
849                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* otherwise */");
850         }
851         else {
852                 cmd_buf[0] = '\0';
853                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* fallthrough %s */", get_cfop_target(proj2, buf));
854         }
855         IA32_DO_EMIT(irn);
856 }
857
858 /**
859  * Emits code for conditional jump.
860  */
861 static void CondJmp_emitter(const ir_node *irn, ia32_emit_env_t *env) {
862         FILE *F = env->out;
863         char cmd_buf[SNPRINTF_BUF_LEN];
864         char cmnt_buf[SNPRINTF_BUF_LEN];
865
866         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cmp %s", ia32_emit_binop(irn, env));
867         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
868         IA32_DO_EMIT(irn);
869         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
870 }
871
872 /**
873  * Emits code for conditional jump with two variables.
874  */
875 static void emit_ia32_CondJmp(const ir_node *irn, ia32_emit_env_t *env) {
876         CondJmp_emitter(irn, env);
877 }
878
879 /**
880  * Emits code for conditional test and jump.
881  */
882 static void TestJmp_emitter(const ir_node *irn, ia32_emit_env_t *env) {
883
884 #define IA32_IS_IMMOP (is_ia32_ImmConst(irn) || is_ia32_ImmSymConst(irn))
885
886         FILE       *F   = env->out;
887         const char *op1 = arch_register_get_name(get_in_reg(irn, 0));
888         const char *op2 = IA32_IS_IMMOP ? get_ia32_cnst(irn) : NULL;
889         char        cmd_buf[SNPRINTF_BUF_LEN];
890         char        cmnt_buf[SNPRINTF_BUF_LEN];
891
892         if (! op2)
893                 op2 = arch_register_get_name(get_in_reg(irn, 1));
894
895         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "test %%%s,%s%s ", op1, IA32_IS_IMMOP ? " " : " %", op2);
896         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
897
898         IA32_DO_EMIT(irn);
899         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
900
901 #undef IA32_IS_IMMOP
902 }
903
904 /**
905  * Emits code for conditional test and jump with two variables.
906  */
907 static void emit_ia32_TestJmp(const ir_node *irn, ia32_emit_env_t *env) {
908         TestJmp_emitter(irn, env);
909 }
910
911 static void emit_ia32_CJmp(const ir_node *irn, ia32_emit_env_t *env) {
912         FILE *F = env->out;
913         char cmd_buf[SNPRINTF_BUF_LEN];
914         char cmnt_buf[SNPRINTF_BUF_LEN];
915
916         snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
917         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F omitted redundant test */", irn);
918         IA32_DO_EMIT(irn);
919         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
920 }
921
922 static void emit_ia32_CJmpAM(const ir_node *irn, ia32_emit_env_t *env) {
923         FILE *F = env->out;
924         char cmd_buf[SNPRINTF_BUF_LEN];
925         char cmnt_buf[SNPRINTF_BUF_LEN];
926
927         snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
928         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F omitted redundant test/cmp */", irn);
929         IA32_DO_EMIT(irn);
930         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
931 }
932
933 /**
934  * Emits code for conditional SSE floating point jump with two variables.
935  */
936 static void emit_ia32_xCondJmp(ir_node *irn, ia32_emit_env_t *env) {
937         FILE *F = env->out;
938         char cmd_buf[SNPRINTF_BUF_LEN];
939         char cmnt_buf[SNPRINTF_BUF_LEN];
940
941         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "ucomis%M %s", irn, ia32_emit_binop(irn, env));
942         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
943         IA32_DO_EMIT(irn);
944         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
945
946 }
947
948 /**
949  * Emits code for conditional x87 floating point jump with two variables.
950  */
951 static void emit_ia32_x87CondJmp(ir_node *irn, ia32_emit_env_t *env) {
952         FILE *F = env->out;
953         char cmd_buf[SNPRINTF_BUF_LEN];
954         char cmnt_buf[SNPRINTF_BUF_LEN];
955         ia32_attr_t *attr = get_ia32_attr(irn);
956         const char *reg = attr->x87[1]->name;
957         const char *instr = "fcom";
958         int reverse = 0;
959
960         switch (get_ia32_pncode(irn)) {
961         case iro_ia32_fcomrJmp:
962                 reverse = 1;
963         case iro_ia32_fcomJmp:
964         default:
965                 instr = "fucom";
966                 break;
967         case iro_ia32_fcomrpJmp:
968                 reverse = 1;
969         case iro_ia32_fcompJmp:
970                 instr = "fucomp";
971                 break;
972         case iro_ia32_fcomrppJmp:
973                 reverse = 1;
974         case iro_ia32_fcomppJmp:
975                 instr = "fucompp";
976                 reg = "";
977                 break;
978         }
979
980         if (reverse)
981                 set_ia32_pncode(irn, (long)get_negated_pnc(get_ia32_pncode(irn), mode_Is));
982
983         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "%s %%%s", instr, reg);
984         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
985         IA32_DO_EMIT(irn);
986         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "fnstsw %%ax", irn);
987         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* Store x87 FPU Control Word */");
988         IA32_DO_EMIT(irn);
989         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "sahf");
990         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* Store ah into flags */");
991         IA32_DO_EMIT(irn);
992
993         finish_CondJmp(F, irn, mode_Is);
994 }
995
996 static void CMov_emitter(ir_node *irn, ia32_emit_env_t *env) {
997         FILE               *F       = env->out;
998         const lc_arg_env_t *arg_env = ia32_get_arg_env();
999         const char *cmp_suffix = get_cmp_suffix(get_ia32_pncode(irn), ! mode_is_signed(get_irn_mode(get_irn_n(irn, 0))));
1000         int is_PsiCondCMov     = is_ia32_PsiCondCMov(irn);
1001
1002         char cmd_buf[SNPRINTF_BUF_LEN];
1003         char cmnt_buf[SNPRINTF_BUF_LEN];
1004         const arch_register_t *in1, *in2, *out;
1005
1006         out = arch_get_irn_register(env->arch_env, irn);
1007         in1 = arch_get_irn_register(env->arch_env, get_irn_n(irn, 2 - is_PsiCondCMov));
1008         in2 = arch_get_irn_register(env->arch_env, get_irn_n(irn, 3 - is_PsiCondCMov));
1009
1010         /* we have to emit the cmp first, because the destination register */
1011         /* could be one of the compare registers                           */
1012         if (is_ia32_CmpCMov(irn)) {
1013                 lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "cmp %1S, %2S", irn, irn);
1014         }
1015         else if (is_ia32_xCmpCMov(irn)) {
1016                 lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "ucomis%M %1S, %2S", get_irn_n(irn, 0), irn, irn);
1017         }
1018         else if (is_PsiCondCMov) {
1019                 /* omit compare because flags are already set by And/Or */
1020                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
1021         }
1022         else {
1023                 assert(0 && "unsupported CMov");
1024         }
1025         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* Psi condition */" );
1026         IA32_DO_EMIT(irn);
1027
1028         if (REGS_ARE_EQUAL(out, in2)) {
1029                 /* best case: default in == out -> do nothing */
1030         }
1031         else if (REGS_ARE_EQUAL(out, in1)) {
1032                 /* true in == out -> need complement compare and exchange true and default in */
1033                 ir_node *t = get_irn_n(irn, 2);
1034                 set_irn_n(irn, 2, get_irn_n(irn, 3));
1035                 set_irn_n(irn, 3, t);
1036
1037                 cmp_suffix = get_cmp_suffix(get_inversed_pnc(get_ia32_pncode(irn)), ! mode_is_signed(get_irn_mode(get_irn_n(irn, 0))));
1038
1039         }
1040         else {
1041                 /* out is different from in: need copy default -> out */
1042                 lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %4S", irn, irn);
1043                 lc_esnprintf(arg_env, cmnt_buf, SNPRINTF_BUF_LEN, "/* copy default -> out */" );
1044                 IA32_DO_EMIT(irn);
1045         }
1046
1047         lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "cmov%s %1D, %3S", cmp_suffix, irn, irn);
1048         lc_esnprintf(arg_env, cmnt_buf, SNPRINTF_BUF_LEN, "/* condition is true case */" );
1049         IA32_DO_EMIT(irn);
1050 }
1051
1052 static void emit_ia32_CmpCMov(ir_node *irn, ia32_emit_env_t *env) {
1053         CMov_emitter(irn, env);
1054 }
1055
1056 static void emit_ia32_PsiCondCMov(ir_node *irn, ia32_emit_env_t *env) {
1057         CMov_emitter(irn, env);
1058 }
1059
1060 static void emit_ia32_xCmpCMov(ir_node *irn, ia32_emit_env_t *env) {
1061         CMov_emitter(irn, env);
1062 }
1063
1064 static void Set_emitter(ir_node *irn, ia32_emit_env_t *env) {
1065         FILE               *F       = env->out;
1066         const lc_arg_env_t *arg_env = ia32_get_arg_env();
1067         const char *cmp_suffix = get_cmp_suffix(get_ia32_pncode(irn), ! mode_is_signed(get_irn_mode(get_irn_n(irn, 0))));
1068         const char *instr      = "xor";
1069         const char *reg8bit;
1070
1071         char cmd_buf[SNPRINTF_BUF_LEN];
1072         char cmnt_buf[SNPRINTF_BUF_LEN];
1073         const arch_register_t *out;
1074
1075         out     = arch_get_irn_register(env->arch_env, irn);
1076         reg8bit = ia32_get_mapped_reg_name(env->isa->regs_8bit, out);
1077
1078         if (env->isa->opt_arch == arch_pentium_4) {
1079                 /* P4 prefers sub r, r, others xor r, r */
1080                 instr = "sub";
1081         }
1082
1083         /* in case of a PsiCondSet use mov because it doesn't affect the eflags */
1084         if (is_ia32_PsiCondSet(irn)) {
1085                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "mov %%%s, 0", arch_register_get_name(out));
1086         }
1087         else {
1088                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "%s %%%s, %%%s", instr, arch_register_get_name(out), arch_register_get_name(out));
1089         }
1090
1091         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* clear target as set modifies only lower 8 bit */");
1092         IA32_DO_EMIT(irn);
1093
1094         if (is_ia32_CmpSet(irn)) {
1095                 lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "cmp %s", ia32_emit_binop(irn, env));
1096         }
1097         else if (is_ia32_xCmpSet(irn)) {
1098                 lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "ucomis%M %s", get_irn_n(irn, 0), ia32_emit_binop(irn, env));
1099         }
1100         else if (is_ia32_PsiCondSet(irn)) {
1101                 /* omit compare because flags are already set by And/Or */
1102                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
1103         }
1104         else {
1105                 assert(0 && "unsupported Set");
1106         }
1107         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* calculate Psi condition */" );
1108         IA32_DO_EMIT(irn);
1109
1110         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "set%s %%%s", cmp_suffix, reg8bit);
1111         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* set 1 iff true, 0 otherweise */" );
1112         IA32_DO_EMIT(irn);
1113 }
1114
1115 static void emit_ia32_CmpSet(ir_node *irn, ia32_emit_env_t *env) {
1116         Set_emitter(irn, env);
1117 }
1118
1119 static void emit_ia32_PsiCondSet(ir_node *irn, ia32_emit_env_t *env) {
1120         Set_emitter(irn, env);
1121 }
1122
1123 static void emit_ia32_xCmpSet(ir_node *irn, ia32_emit_env_t *env) {
1124         Set_emitter(irn, env);
1125 }
1126
1127 static void emit_ia32_xCmp(ir_node *irn, ia32_emit_env_t *env) {
1128         FILE               *F       = env->out;
1129         const lc_arg_env_t *arg_env = ia32_get_arg_env();
1130         int                sse_pnc  = -1;
1131         char cmd_buf[SNPRINTF_BUF_LEN];
1132         char cmnt_buf[SNPRINTF_BUF_LEN];
1133
1134         switch (get_ia32_pncode(irn)) {
1135                 case pn_Cmp_Leg: /* odered */
1136                         sse_pnc = 7;
1137                         break;
1138                 case pn_Cmp_Uo:  /* unordered */
1139                         sse_pnc = 3;
1140                         break;
1141                 case pn_Cmp_Ue:  /* == */
1142                         sse_pnc = 0;
1143                         break;
1144                 case pn_Cmp_Ul:  /* < */
1145                         sse_pnc = 1;
1146                         break;
1147                 case pn_Cmp_Ule: /* <= */
1148                         sse_pnc = 2;
1149                         break;
1150                 case pn_Cmp_Ug:  /* > */
1151                         sse_pnc = 6;
1152                         break;
1153                 case pn_Cmp_Uge: /* >= */
1154                         sse_pnc = 5;
1155                         break;
1156                 case pn_Cmp_Ne:  /* != */
1157                         sse_pnc = 4;
1158                         break;
1159         }
1160
1161         assert(sse_pnc >= 0 && "unsupported floating point compare");
1162
1163         lc_esnprintf(arg_env, cmd_buf, SNPRINTF_BUF_LEN, "cmps%M %s, %d", irn, ia32_emit_binop(irn, env), sse_pnc);
1164         lc_esnprintf(arg_env, cmnt_buf, SNPRINTF_BUF_LEN, "/* SSE compare with result in %1D */", irn);
1165         IA32_DO_EMIT(irn);
1166 }
1167
1168 /*********************************************************
1169  *                 _ _       _
1170  *                (_) |     (_)
1171  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
1172  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
1173  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
1174  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
1175  *                         _/ |               | |
1176  *                        |__/                |_|
1177  *********************************************************/
1178
1179 /* jump table entry (target and corresponding number) */
1180 typedef struct _branch_t {
1181         ir_node *target;
1182         int      value;
1183 } branch_t;
1184
1185 /* jump table for switch generation */
1186 typedef struct _jmp_tbl_t {
1187         ir_node  *defProj;         /**< default target */
1188         int       min_value;       /**< smallest switch case */
1189         int       max_value;       /**< largest switch case */
1190         int       num_branches;    /**< number of jumps */
1191         char     *label;           /**< label of the jump table */
1192         branch_t *branches;        /**< jump array */
1193 } jmp_tbl_t;
1194
1195 /**
1196  * Compare two variables of type branch_t. Used to sort all switch cases
1197  */
1198 static int ia32_cmp_branch_t(const void *a, const void *b) {
1199         branch_t *b1 = (branch_t *)a;
1200         branch_t *b2 = (branch_t *)b;
1201
1202         if (b1->value <= b2->value)
1203                 return -1;
1204         else
1205                 return 1;
1206 }
1207
1208 /**
1209  * Emits code for a SwitchJmp (creates a jump table if
1210  * possible otherwise a cmp-jmp cascade). Port from
1211  * cggg ia32 backend
1212  */
1213 static void emit_ia32_SwitchJmp(const ir_node *irn, ia32_emit_env_t *emit_env) {
1214         unsigned long       interval;
1215         char                buf[SNPRINTF_BUF_LEN];
1216         int                 last_value, i, pn;
1217         jmp_tbl_t           tbl;
1218         ir_node            *proj;
1219         const ir_edge_t    *edge;
1220         const lc_arg_env_t *env = ia32_get_arg_env();
1221         FILE               *F   = emit_env->out;
1222         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1223
1224         /* fill the table structure */
1225         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
1226         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
1227         tbl.defProj      = NULL;
1228         tbl.num_branches = get_irn_n_edges(irn);
1229         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
1230         tbl.min_value    = INT_MAX;
1231         tbl.max_value    = INT_MIN;
1232
1233         i = 0;
1234         /* go over all proj's and collect them */
1235         foreach_out_edge(irn, edge) {
1236                 proj = get_edge_src_irn(edge);
1237                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1238
1239                 pn = get_Proj_proj(proj);
1240
1241                 /* create branch entry */
1242                 tbl.branches[i].target = proj;
1243                 tbl.branches[i].value  = pn;
1244
1245                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
1246                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
1247
1248                 /* check for default proj */
1249                 if (pn == get_ia32_pncode(irn)) {
1250                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
1251                         tbl.defProj = proj;
1252                 }
1253
1254                 i++;
1255         }
1256
1257         /* sort the branches by their number */
1258         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1259
1260         /* two-complement's magic make this work without overflow */
1261         interval = tbl.max_value - tbl.min_value;
1262
1263         /* emit the table */
1264         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmp %1S, %u", irn, interval);
1265         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* compare for switch */");
1266         IA32_DO_EMIT(irn);
1267
1268         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "ja %s", get_cfop_target(tbl.defProj, buf));
1269         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default jump if out of range  */");
1270         IA32_DO_EMIT(irn);
1271
1272         if (tbl.num_branches > 1) {
1273                 /* create table */
1274
1275                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "jmp %s[%1S*4]", tbl.label, irn);
1276                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* get jump table entry as target */");
1277                 IA32_DO_EMIT(irn);
1278
1279                 ia32_switch_section(F, SECTION_RODATA);
1280                 fprintf(F, "\t.align 4\n");
1281
1282                 fprintf(F, "%s:\n", tbl.label);
1283
1284                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[0].target, buf));
1285                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */",  tbl.branches[0].value);
1286                 IA32_DO_EMIT(irn);
1287
1288                 last_value = tbl.branches[0].value;
1289                 for (i = 1; i < tbl.num_branches; ++i) {
1290                         while (++last_value < tbl.branches[i].value) {
1291                                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.defProj, buf));
1292                                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
1293                                 IA32_DO_EMIT(irn);
1294                         }
1295                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[i].target, buf));
1296                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", last_value);
1297                         IA32_DO_EMIT(irn);
1298                 }
1299                 ia32_switch_section(F, SECTION_TEXT);
1300         }
1301         else {
1302                 /* one jump is enough */
1303                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.branches[0].target, buf));
1304                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* only one case given */");
1305                 IA32_DO_EMIT(irn);
1306         }
1307
1308         if (tbl.label)
1309                 free(tbl.label);
1310         if (tbl.branches)
1311                 free(tbl.branches);
1312 }
1313
1314 /**
1315  * Emits code for a unconditional jump.
1316  */
1317 static void emit_Jmp(const ir_node *irn, ia32_emit_env_t *env) {
1318         ir_node *block, *next_bl;
1319         FILE *F = env->out;
1320         char buf[SNPRINTF_BUF_LEN], cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1321
1322         /* for now, the code works for scheduled and non-schedules blocks */
1323         block = get_nodes_block(irn);
1324
1325         /* we have a block schedule */
1326         next_bl = next_blk_sched(block);
1327         if (get_cfop_target_block(irn) != next_bl) {
1328                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(irn, buf));
1329                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F) */", irn, get_cfop_target_block(irn));
1330         }
1331         else {
1332                 cmd_buf[0] = '\0';
1333                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* fallthrough %s */", get_cfop_target(irn, buf));
1334         }
1335         IA32_DO_EMIT(irn);
1336 }
1337
1338 /****************************
1339  *                  _
1340  *                 (_)
1341  *  _ __  _ __ ___  _  ___
1342  * | '_ \| '__/ _ \| |/ __|
1343  * | |_) | | | (_) | |\__ \
1344  * | .__/|_|  \___/| ||___/
1345  * | |            _/ |
1346  * |_|           |__/
1347  ****************************/
1348
1349 /**
1350  * Emits code for a proj -> node
1351  */
1352 static void emit_Proj(const ir_node *irn, ia32_emit_env_t *env) {
1353         ir_node *pred = get_Proj_pred(irn);
1354
1355         if (get_irn_op(pred) == op_Start) {
1356                 switch(get_Proj_proj(irn)) {
1357                         case pn_Start_X_initial_exec:
1358                                 emit_Jmp(irn, env);
1359                                 break;
1360                         default:
1361                                 break;
1362                 }
1363         }
1364 }
1365
1366 /**********************************
1367  *   _____                  ____
1368  *  / ____|                |  _ \
1369  * | |     ___  _ __  _   _| |_) |
1370  * | |    / _ \| '_ \| | | |  _ <
1371  * | |___| (_) | |_) | |_| | |_) |
1372  *  \_____\___/| .__/ \__, |____/
1373  *             | |     __/ |
1374  *             |_|    |___/
1375  **********************************/
1376
1377 /**
1378  * Emit movsb/w instructions to make mov count divideable by 4
1379  */
1380 static void emit_CopyB_prolog(FILE *F, ir_node *irn, int rem) {
1381         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1382
1383         ir_fprintf(F, "\t/* memcopy prolog %+F */\n", irn);
1384
1385         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cld");
1386         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* copy direction forward */");
1387
1388         switch(rem) {
1389                 case 1:
1390                         IA32_DO_EMIT(NULL);
1391                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
1392                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 1 */");
1393                         break;
1394                 case 2:
1395                         IA32_DO_EMIT(NULL);
1396                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
1397                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 2 */");
1398                         break;
1399                 case 3:
1400                         IA32_DO_EMIT(NULL);
1401                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
1402                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
1403                         IA32_DO_EMIT(NULL);
1404                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
1405                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
1406                         break;
1407         }
1408
1409         IA32_DO_EMIT(NULL);
1410 }
1411
1412 /**
1413  * Emit rep movsd instruction for memcopy.
1414  */
1415 static void emit_ia32_CopyB(const ir_node *irn, ia32_emit_env_t *emit_env) {
1416         FILE   *F  = emit_env->out;
1417         tarval *tv = get_ia32_Immop_tarval(irn);
1418         int    rem = get_tarval_long(tv);
1419         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1420
1421         emit_CopyB_prolog(F, irn, rem);
1422
1423         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "rep movsd");
1424         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy */");
1425         IA32_DO_EMIT(irn);
1426 }
1427
1428 /**
1429  * Emits unrolled memcopy.
1430  */
1431 static void emit_ia32_CopyB_i(const ir_node *irn, ia32_emit_env_t *emit_env) {
1432         tarval *tv   = get_ia32_Immop_tarval(irn);
1433         int     size = get_tarval_long(tv);
1434         FILE   *F    = emit_env->out;
1435         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1436
1437         emit_CopyB_prolog(F, irn, size & 0x3);
1438
1439         size >>= 2;
1440         while (size--) {
1441                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsd");
1442                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy unrolled */");
1443                 IA32_DO_EMIT(irn);
1444         }
1445 }
1446
1447
1448
1449 /***************************
1450  *   _____
1451  *  / ____|
1452  * | |     ___  _ ____   __
1453  * | |    / _ \| '_ \ \ / /
1454  * | |___| (_) | | | \ V /
1455  *  \_____\___/|_| |_|\_/
1456  *
1457  ***************************/
1458
1459 /**
1460  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1461  */
1462 static void emit_ia32_Conv_with_FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1463         FILE               *F        = emit_env->out;
1464         const lc_arg_env_t *env      = ia32_get_arg_env();
1465         ir_mode            *src_mode = get_ia32_src_mode(irn);
1466         ir_mode            *tgt_mode = get_ia32_tgt_mode(irn);
1467         char               *from, *to, buf[64];
1468         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1469
1470         from = mode_is_float(src_mode) ? (get_mode_size_bits(src_mode) == 32 ? "ss" : "sd") : "si";
1471         to   = mode_is_float(tgt_mode) ? (get_mode_size_bits(tgt_mode) == 32 ? "ss" : "sd") : "si";
1472
1473         switch(get_ia32_op_type(irn)) {
1474                 case ia32_Normal:
1475                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %3S", irn, irn);
1476                         break;
1477                 case ia32_AddrModeS:
1478                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %s", irn, ia32_emit_am(irn, emit_env));
1479                         break;
1480                 default:
1481                         assert(0 && "unsupported op type for Conv");
1482         }
1483
1484         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cvt%s2%s %s", from, to, buf);
1485         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F, %+F) */", irn, src_mode, tgt_mode);
1486         IA32_DO_EMIT(irn);
1487 }
1488
1489 static void emit_ia32_Conv_I2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1490         emit_ia32_Conv_with_FP(irn, emit_env);
1491 }
1492
1493 static void emit_ia32_Conv_FP2I(const ir_node *irn, ia32_emit_env_t *emit_env) {
1494         emit_ia32_Conv_with_FP(irn, emit_env);
1495 }
1496
1497 static void emit_ia32_Conv_FP2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1498         emit_ia32_Conv_with_FP(irn, emit_env);
1499 }
1500
1501 /**
1502  * Emits code for an Int conversion.
1503  */
1504 static void emit_ia32_Conv_I2I(const ir_node *irn, ia32_emit_env_t *emit_env) {
1505         FILE               *F        = emit_env->out;
1506         const lc_arg_env_t *env      = ia32_get_arg_env();
1507         char               *move_cmd = "movzx";
1508         char               *conv_cmd = NULL;
1509         ir_mode            *src_mode = get_ia32_src_mode(irn);
1510         ir_mode            *tgt_mode = get_ia32_tgt_mode(irn);
1511         int n, m;
1512         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1513         const arch_register_t *in_reg, *out_reg;
1514
1515         n = get_mode_size_bits(src_mode);
1516         m = get_mode_size_bits(tgt_mode);
1517
1518         if (mode_is_signed(n < m ? src_mode : tgt_mode)) {
1519                 move_cmd = "movsx";
1520                 if (n == 8 || m == 8)
1521                         conv_cmd = "cbw";
1522                 else if (n == 16 || m == 16)
1523                         conv_cmd = "cwde";
1524                 else
1525                         assert(0 && "unsupported Conv_I2I");
1526         }
1527
1528          switch(get_ia32_op_type(irn)) {
1529                 case ia32_Normal:
1530                         in_reg  = get_in_reg(irn, 2);
1531                         out_reg = get_out_reg(irn, 0);
1532
1533                         if (REGS_ARE_EQUAL(in_reg, &ia32_gp_regs[REG_EAX]) &&
1534                                 REGS_ARE_EQUAL(out_reg, in_reg)                &&
1535                                 mode_is_signed(n < m ? src_mode : tgt_mode))
1536                         {
1537                                 /* argument and result are both in EAX and */
1538                                 /* signedness is ok: -> use converts       */
1539                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s", conv_cmd);
1540                         }
1541                         else if (REGS_ARE_EQUAL(out_reg, in_reg) &&
1542                                 ! mode_is_signed(n < m ? src_mode : tgt_mode))
1543                         {
1544                                 /* argument and result are in the same register */
1545                                 /* and signedness is ok: -> use and with mask   */
1546                                 int mask = (1 << (n < m ? n : m)) - 1;
1547                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "and %1D, 0x%x", irn, mask);
1548                         }
1549                         else {
1550                                 /* use move w/o sign extension */
1551                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s %1D, %%%s",
1552                                         move_cmd, irn, ia32_get_reg_name_for_mode(emit_env, n < m ? src_mode : tgt_mode, in_reg));
1553                         }
1554
1555                         break;
1556                 case ia32_AddrModeS:
1557                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s %1D, %s",
1558                                 move_cmd, irn, ia32_emit_am(irn, emit_env));
1559                         break;
1560                 default:
1561                         assert(0 && "unsupported op type for Conv");
1562         }
1563
1564         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%d Bit mode_%F -> %d Bit mode_%F) */",
1565                 irn, n, src_mode, m, tgt_mode);
1566
1567         IA32_DO_EMIT(irn);
1568 }
1569
1570 /**
1571  * Emits code for an 8Bit Int conversion.
1572  */
1573 void emit_ia32_Conv_I2I8Bit(const ir_node *irn, ia32_emit_env_t *emit_env) {
1574         emit_ia32_Conv_I2I(irn, emit_env);
1575 }
1576
1577
1578 /*******************************************
1579  *  _                          _
1580  * | |                        | |
1581  * | |__   ___ _ __   ___   __| | ___  ___
1582  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1583  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1584  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1585  *
1586  *******************************************/
1587
1588 /**
1589  * Emits a backend call
1590  */
1591 static void emit_be_Call(const ir_node *irn, ia32_emit_env_t *emit_env) {
1592         FILE *F = emit_env->out;
1593         entity *ent = be_Call_get_entity(irn);
1594         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1595
1596         if (ent) {
1597                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "call %s", get_entity_ld_name(ent));
1598         }
1599         else {
1600                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "call %1D", get_irn_n(irn, be_pos_Call_ptr));
1601         }
1602
1603         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (be_Call) */", irn);
1604
1605         IA32_DO_EMIT(irn);
1606 }
1607
1608 /**
1609  * Emits code to increase stack pointer.
1610  */
1611 static void emit_be_IncSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1612         FILE          *F    = emit_env->out;
1613         unsigned       offs = be_get_IncSP_offset(irn);
1614         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
1615         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1616
1617         if (offs) {
1618                 if (dir == be_stack_dir_expand)
1619                         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "sub %1S, %u", irn, offs);
1620                 else
1621                         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "add %1S, %u", irn, offs);
1622                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (IncSP) */", irn);
1623         }
1624         else {
1625                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
1626                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* omitted %+F (IncSP) with 0 */", irn);
1627         }
1628
1629         IA32_DO_EMIT(irn);
1630 }
1631
1632 /**
1633  * Emits code to set stack pointer.
1634  */
1635 static void emit_be_SetSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1636         FILE *F = emit_env->out;
1637         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1638
1639         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %3S", irn, irn);
1640         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (restore SP) */", irn);
1641         IA32_DO_EMIT(irn);
1642 }
1643
1644 /**
1645  * Emits code for Copy/CopyKeep.
1646  */
1647 static void Copy_emitter(const ir_node *irn, ir_node *op, ia32_emit_env_t *emit_env) {
1648         FILE             *F    = emit_env->out;
1649         const arch_env_t *aenv = emit_env->arch_env;
1650         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1651
1652         if (REGS_ARE_EQUAL(arch_get_irn_register(aenv, irn), arch_get_irn_register(aenv, op)) ||
1653                 be_is_unknown_reg(arch_get_irn_register(aenv, op)))
1654                 return;
1655
1656         if (mode_is_float(get_irn_mode(irn)))
1657                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "movs%M %1D, %1S", irn, irn, irn);
1658         else
1659                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %1S", irn, irn);
1660         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
1661         IA32_DO_EMIT(irn);
1662 }
1663
1664 static void emit_be_Copy(const ir_node *irn, ia32_emit_env_t *emit_env) {
1665         Copy_emitter(irn, be_get_Copy_op(irn), emit_env);
1666 }
1667
1668 static void emit_be_CopyKeep(const ir_node *irn, ia32_emit_env_t *emit_env) {
1669         Copy_emitter(irn, be_get_CopyKeep_op(irn), emit_env);
1670 }
1671
1672 /**
1673  * Emits code for exchange.
1674  */
1675 static void emit_be_Perm(const ir_node *irn, ia32_emit_env_t *emit_env) {
1676         FILE *F = emit_env->out;
1677         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1678         const arch_register_t *in1, *in2;
1679         const arch_register_class_t *cls1, *cls2;
1680
1681         in1 = arch_get_irn_register(emit_env->arch_env, get_irn_n(irn, 0));
1682         in2 = arch_get_irn_register(emit_env->arch_env, get_irn_n(irn, 1));
1683
1684         cls1 = arch_register_get_class(in1);
1685         cls2 = arch_register_get_class(in2);
1686
1687         assert(cls1 == cls2 && "Register class mismatch at Perm");
1688
1689         if (cls1 == &ia32_reg_classes[CLASS_ia32_gp]) {
1690                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "xchg %1S, %2S", irn, irn);
1691         }
1692         else if (cls1 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1693                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN,
1694                         "pxor %1S, %2S\n\tpxor %2S, %1S\n\tpxor %1S, %2S", irn, irn, irn, irn, irn, irn);
1695         }
1696         else if (cls1 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1697                 assert(0 && "Perm with vfp should not happen");
1698         }
1699         else if (cls1 == &ia32_reg_classes[CLASS_ia32_st]) {
1700                 assert(0 && "Perm with st(X) should not happen");
1701         }
1702
1703         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%1A, %2A) */", irn, irn, irn);
1704         IA32_DO_EMIT(irn);
1705 }
1706
1707 /**
1708  * Emits code for Constant loading.
1709  */
1710 static void emit_ia32_Const(const ir_node *n, ia32_emit_env_t *env) {
1711   FILE *F = env->out;
1712   char cmd_buf[256], cmnt_buf[256];
1713   const lc_arg_env_t *arg_env = ia32_get_arg_env();
1714
1715   if (get_ia32_Immop_tarval(n) == get_tarval_null(get_irn_mode(n))) {
1716                 const char *instr = "xor";
1717                 if (env->isa->opt_arch == arch_pentium_4) {
1718                         /* P4 prefers sub r, r, others xor r, r */
1719                         instr = "sub";
1720                 }
1721     lc_esnprintf(arg_env, cmd_buf, 256, "%s %1D, %1D ", instr, n, n);
1722     lc_esnprintf(arg_env, cmnt_buf, 256, "/* optimized mov 0 to register */");
1723   }
1724   else {
1725     if (get_ia32_op_type(n) == ia32_SymConst) {
1726       lc_esnprintf(arg_env, cmd_buf, 256, "mov %1D, OFFSET FLAT:%C ", n, n);
1727       lc_esnprintf(arg_env, cmnt_buf, 256, "/* Move address of SymConst into register */");
1728     }
1729                 else {
1730                                 lc_esnprintf(arg_env, cmd_buf, 256, "mov %1D, %C ", n, n);
1731                                 lc_esnprintf(arg_env, cmnt_buf, 256, "/* Mov Const into register */");
1732                 }
1733   }
1734   lc_efprintf(arg_env, F, "\t%-35s %-60s /* %+F (%+G) */\n", cmd_buf, cmnt_buf, n, n);
1735 }
1736
1737 static void emit_be_Return(const ir_node *n, ia32_emit_env_t *env) {
1738   FILE *F = env->out;
1739   const lc_arg_env_t *arg_env = ia32_get_arg_env();
1740
1741   lc_efprintf(arg_env, F, "\t%-35s %-60s /* %+F (%+G) */\n", "ret", "/* be_Return */", n, n);
1742 }
1743
1744
1745
1746 /***********************************************************************************
1747  *                  _          __                                             _
1748  *                 (_)        / _|                                           | |
1749  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1750  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1751  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1752  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1753  *
1754  ***********************************************************************************/
1755
1756 /**
1757  * Enters the emitter functions for handled nodes into the generic
1758  * pointer of an opcode.
1759  */
1760 static void ia32_register_emitters(void) {
1761
1762 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1763 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1764 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1765 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1766
1767         /* first clear the generic function pointer for all ops */
1768         clear_irp_opcodes_generic_func();
1769
1770         /* register all emitter functions defined in spec */
1771         ia32_register_spec_emitters();
1772
1773         /* other ia32 emitter functions */
1774         IA32_EMIT(CondJmp);
1775         IA32_EMIT(TestJmp);
1776         IA32_EMIT(CJmp);
1777         IA32_EMIT(CJmpAM);
1778         IA32_EMIT(CmpCMov);
1779         IA32_EMIT(PsiCondCMov);
1780         IA32_EMIT(CmpSet);
1781         IA32_EMIT(PsiCondSet);
1782         IA32_EMIT(SwitchJmp);
1783         IA32_EMIT(CopyB);
1784         IA32_EMIT(CopyB_i);
1785         IA32_EMIT(Conv_I2FP);
1786         IA32_EMIT(Conv_FP2I);
1787         IA32_EMIT(Conv_FP2FP);
1788         IA32_EMIT(Conv_I2I);
1789         IA32_EMIT(Conv_I2I8Bit);
1790         IA32_EMIT(Const);
1791         IA32_EMIT(xCmp);
1792         IA32_EMIT(xCmpSet);
1793         IA32_EMIT(xCmpCMov);
1794         IA32_EMIT(xCondJmp);
1795         IA32_EMIT2(fcomJmp, x87CondJmp);
1796         IA32_EMIT2(fcompJmp, x87CondJmp);
1797         IA32_EMIT2(fcomppJmp, x87CondJmp);
1798         IA32_EMIT2(fcomrJmp, x87CondJmp);
1799         IA32_EMIT2(fcomrpJmp, x87CondJmp);
1800         IA32_EMIT2(fcomrppJmp, x87CondJmp);
1801
1802         /* benode emitter */
1803         BE_EMIT(Call);
1804         BE_EMIT(IncSP);
1805         BE_EMIT(SetSP);
1806         BE_EMIT(Copy);
1807         BE_EMIT(CopyKeep);
1808         BE_EMIT(Perm);
1809         BE_EMIT(Return);
1810
1811         /* firm emitter */
1812         EMIT(Jmp);
1813         EMIT(Proj);
1814
1815 #undef BE_EMIT
1816 #undef EMIT
1817 #undef IA32_EMIT2
1818 #undef IA32_EMIT
1819 }
1820
1821 /**
1822  * Emits code for a node.
1823  */
1824 static void ia32_emit_node(const ir_node *irn, void *env) {
1825         ia32_emit_env_t   *emit_env = env;
1826         FILE              *F        = emit_env->out;
1827         ir_op             *op       = get_irn_op(irn);
1828         DEBUG_ONLY(firm_dbg_module_t *mod = emit_env->mod;)
1829
1830         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
1831
1832         if (op->ops.generic) {
1833                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
1834                 (*emit)(irn, env);
1835         }
1836         else {
1837                 ir_fprintf(F, "\t%35s /* %+F (%+G) */\n", " ", irn, irn);
1838         }
1839 }
1840
1841 /**
1842  * Emits gas alignment directives
1843  */
1844 static void ia32_emit_alignment(FILE *F, unsigned align, unsigned skip) {
1845         fprintf(F, "\t.p2align %u,,%u\n", align, skip);
1846 }
1847
1848 /**
1849  * Emits gas alignment directives for Functions depended on cpu architecture.
1850  */
1851 static void ia32_emit_align_func(FILE *F, cpu_support cpu) {
1852         unsigned align; unsigned maximum_skip;
1853
1854         /* gcc doesn't emit alignment for p4 ?*/
1855     if (cpu == arch_pentium_4)
1856                 return;
1857
1858         switch (cpu) {
1859                 case arch_i386:
1860                         align = 2; maximum_skip = 3;
1861                         break;
1862                 case arch_i486:
1863                         align = 4; maximum_skip = 15;
1864                         break;
1865                 case arch_k6:
1866                         align = 5; maximum_skip = 31;
1867                         break;
1868                 default:
1869                         align = 4; maximum_skip = 15;
1870         }
1871         ia32_emit_alignment(F, align, maximum_skip);
1872 }
1873
1874 /**
1875  * Emits gas alignment directives for Labels depended on cpu architecture.
1876  */
1877 static void ia32_emit_align_label(FILE *F, cpu_support cpu) {
1878         unsigned align; unsigned maximum_skip;
1879
1880         /* gcc doesn't emit alignment for p4 ?*/
1881     if (cpu == arch_pentium_4)
1882                 return;
1883
1884         switch (cpu) {
1885                 case arch_i386:
1886                         align = 2; maximum_skip = 3;
1887                         break;
1888                 case arch_i486:
1889                         align = 4; maximum_skip = 15;
1890                         break;
1891                 case arch_k6:
1892                         align = 5; maximum_skip = 7;
1893                         break;
1894                 default:
1895                         align = 4; maximum_skip = 7;
1896         }
1897         ia32_emit_alignment(F, align, maximum_skip);
1898 }
1899
1900 /**
1901  * Walks over the nodes in a block connected by scheduling edges
1902  * and emits code for each node.
1903  */
1904 static void ia32_gen_block(ir_node *block, void *env) {
1905         ia32_emit_env_t *emit_env = env;
1906         const ir_node *irn;
1907         int need_label = block != get_irg_start_block(get_irn_irg(block));
1908
1909         if (! is_Block(block))
1910                 return;
1911
1912         if (need_label && (emit_env->cg->opt & IA32_OPT_EXTBB)) {
1913                 /* if the extended block scheduler is used, only leader blocks need
1914                    labels. */
1915                 need_label = (block == get_extbb_leader(get_nodes_extbb(block)));
1916         }
1917
1918         if (need_label) {
1919                 ia32_emit_align_label(emit_env->out, emit_env->isa->opt_arch);
1920                 fprintf(emit_env->out, BLOCK_PREFIX("%ld:\n"), get_irn_node_nr(block));
1921         }
1922
1923         sched_foreach(block, irn) {
1924                 ia32_emit_node(irn, env);
1925         }
1926 }
1927
1928 /**
1929  * Emits code for function start.
1930  */
1931 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg, cpu_support cpu) {
1932         entity     *irg_ent  = get_irg_entity(irg);
1933         const char *irg_name = get_entity_ld_name(irg_ent);
1934
1935         fprintf(F, "\n");
1936         ia32_switch_section(F, SECTION_TEXT);
1937         ia32_emit_align_func(F, cpu);
1938         if (get_entity_visibility(irg_ent) == visibility_external_visible) {
1939                 fprintf(F, ".globl %s\n", irg_name);
1940         }
1941         ia32_dump_function_object(F, irg_name);
1942         fprintf(F, "%s:\n", irg_name);
1943 }
1944
1945 /**
1946  * Emits code for function end
1947  */
1948 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
1949         const char *irg_name = get_entity_ld_name(get_irg_entity(irg));
1950
1951         ia32_dump_function_size(F, irg_name);
1952         fprintf(F, "\n");
1953 }
1954
1955 /**
1956  * Block-walker:
1957  * Sets labels for control flow nodes (jump target)
1958  * TODO: Jump optimization
1959  */
1960 static void ia32_gen_labels(ir_node *block, void *env) {
1961         ir_node *pred;
1962         int n = get_Block_n_cfgpreds(block);
1963
1964         for (n--; n >= 0; n--) {
1965                 pred = get_Block_cfgpred(block, n);
1966                 set_irn_link(pred, block);
1967         }
1968 }
1969
1970 /**
1971  * Main driver. Emits the code for one routine.
1972  */
1973 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
1974         ia32_emit_env_t emit_env;
1975         ir_node *block;
1976
1977         emit_env.out      = F;
1978         emit_env.arch_env = cg->arch_env;
1979         emit_env.cg       = cg;
1980         emit_env.isa      = (ia32_isa_t *)cg->arch_env->isa;
1981         FIRM_DBG_REGISTER(emit_env.mod, "firm.be.ia32.emitter");
1982
1983         /* set the global arch_env (needed by print hooks) */
1984         arch_env = cg->arch_env;
1985
1986         ia32_register_emitters();
1987
1988         ia32_emit_func_prolog(F, irg, emit_env.isa->opt_arch);
1989         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
1990
1991         if ((cg->opt & IA32_OPT_EXTBB) && cg->blk_sched) {
1992                 int i, n = ARR_LEN(cg->blk_sched);
1993
1994                 for (i = 0; i < n;) {
1995                         ir_node *next_bl;
1996
1997                         block   = cg->blk_sched[i];
1998                         ++i;
1999                         next_bl = i < n ? cg->blk_sched[i] : NULL;
2000
2001                         /* set here the link. the emitter expects to find the next block here */
2002                         set_irn_link(block, next_bl);
2003                         ia32_gen_block(block, &emit_env);
2004                 }
2005         }
2006         else {
2007                 /* "normal" block schedule: Note the get_next_block() returns the NUMBER of the block
2008                    in the block schedule. As this number should NEVER be equal the next block,
2009                    we does not need a clear block link here. */
2010                 irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
2011         }
2012
2013         ia32_emit_func_epilog(F, irg);
2014 }