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