Add some Processor specific instruction selections
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 /**
2  * This file implements the node emitter.
3  *
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
34 #define BLOCK_PREFIX(x) ".L" x
35
36 #define SNPRINTF_BUF_LEN 128
37
38 /* global arch_env for lc_printf functions */
39 static const arch_env_t *arch_env = NULL;
40
41 /** by default, we generate assembler code for the Linux gas */
42 asm_flavour_t asm_flavour = ASM_LINUX_GAS;
43
44 /**
45  * Switch to a new section
46  */
47 void ia32_switch_section(FILE *F, section_t sec) {
48         static section_t curr_sec = NO_SECTION;
49   static const char *text[ASM_MAX][SECTION_MAX] = {
50                 {
51                         ".section\t.text", ".section\t.data", ".section\t.rodata", ".section\t.text"
52                 },
53                 {
54                         ".section\t.text", ".section\t.data", ".section .rdata,\"dr\"", ".section\t.text"
55                 }
56         };
57
58         if (curr_sec == sec)
59                 return;
60
61         curr_sec = sec;
62         switch (sec) {
63
64         case NO_SECTION:
65                 break;
66
67         case SECTION_TEXT:
68         case SECTION_DATA:
69         case SECTION_RODATA:
70         case SECTION_COMMON:
71                 fprintf(F, "\t%s\n", text[asm_flavour][sec]);
72         }
73 }
74
75 static void ia32_dump_function_object(FILE *F, const char *name)
76 {
77         switch (asm_flavour) {
78         case ASM_LINUX_GAS:
79                 fprintf(F, "\t.type\t%s, @function\n", name);
80                 break;
81         case ASM_MINGW_GAS:
82                 fprintf(F, "\t.def\t%s;\t.scl\t2;\t.type\t32;\t.endef\n", name);
83                 break;
84         }
85 }
86
87 static void ia32_dump_function_size(FILE *F, const char *name)
88 {
89         switch (asm_flavour) {
90         case ASM_LINUX_GAS:
91                 fprintf(F, "\t.size\t%s, .-%s\n", name, name);
92                 break;
93         }
94 }
95
96 /*************************************************************
97  *             _       _    __   _          _
98  *            (_)     | |  / _| | |        | |
99  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
100  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
101  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
102  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
103  * | |                                       | |
104  * |_|                                       |_|
105  *************************************************************/
106
107 /**
108  * returns true if a node has x87 registers
109  */
110 static int has_x87_register(const ir_node *n) {
111         return is_irn_machine_user(n, 0);
112 }
113
114 /* We always pass the ir_node which is a pointer. */
115 static int ia32_get_arg_type(const lc_arg_occ_t *occ) {
116         return lc_arg_type_ptr;
117 }
118
119
120 /**
121  * Returns the register at in position pos.
122  */
123 static const arch_register_t *get_in_reg(const ir_node *irn, int pos) {
124         ir_node                *op;
125         const arch_register_t  *reg = NULL;
126
127         assert(get_irn_arity(irn) > pos && "Invalid IN position");
128
129         /* The out register of the operator at position pos is the
130            in register we need. */
131         op = get_irn_n(irn, pos);
132
133         reg = arch_get_irn_register(arch_env, op);
134
135         assert(reg && "no in register found");
136
137         /* in case of unknown: just return a register */
138         if (REGS_ARE_EQUAL(reg, &ia32_gp_regs[REG_GP_UKNWN]))
139                 reg = &ia32_gp_regs[REG_EAX];
140         else if (REGS_ARE_EQUAL(reg, &ia32_xmm_regs[REG_XMM_UKNWN]))
141                 reg = &ia32_xmm_regs[REG_XMM0];
142         else if (REGS_ARE_EQUAL(reg, &ia32_vfp_regs[REG_VFP_UKNWN]))
143                 reg = &ia32_vfp_regs[REG_VF0];
144         else if (REGS_ARE_EQUAL(reg, &ia32_st_regs[REG_ST_UKNWN]))
145                 reg = &ia32_st_regs[REG_ST0];
146
147         return reg;
148 }
149
150 /**
151  * Returns the register at out position pos.
152  */
153 static const arch_register_t *get_out_reg(const ir_node *irn, int pos) {
154         ir_node                *proj;
155         const arch_register_t  *reg = NULL;
156
157         /* 1st case: irn is not of mode_T, so it has only                 */
158         /*           one OUT register -> good                             */
159         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
160         /*           Proj with the corresponding projnum for the register */
161
162         if (get_irn_mode(irn) != mode_T) {
163                 reg = arch_get_irn_register(arch_env, irn);
164         }
165         else if (is_ia32_irn(irn)) {
166                 reg = get_ia32_out_reg(irn, pos);
167         }
168         else {
169                 const ir_edge_t *edge;
170
171                 foreach_out_edge(irn, edge) {
172                         proj = get_edge_src_irn(edge);
173                         assert(is_Proj(proj) && "non-Proj from mode_T node");
174                         if (get_Proj_proj(proj) == pos) {
175                                 reg = arch_get_irn_register(arch_env, proj);
176                                 break;
177                         }
178                 }
179         }
180
181         assert(reg && "no out register found");
182         return reg;
183 }
184
185 enum io_direction {
186   IN_REG,
187   OUT_REG
188 };
189
190 /**
191  * Returns the name of the in register at position pos.
192  */
193 static const char *get_ia32_reg_name(ir_node *irn, int pos, enum io_direction in_out) {
194         const arch_register_t *reg;
195
196         if (in_out == IN_REG) {
197                 reg = get_in_reg(irn, pos);
198
199                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]) {
200                         /* FIXME: works for binop only */
201                         assert(2 <= pos && pos <= 3);
202                         reg = get_ia32_attr(irn)->x87[pos - 2];
203                 }
204         }
205         else {
206                 /* destination address mode nodes don't have outputs */
207                 if (is_ia32_irn(irn) && get_ia32_op_type(irn) == ia32_AddrModeD) {
208                         return "MEM";
209                 }
210
211                 reg = get_out_reg(irn, pos);
212                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp])
213                         reg = get_ia32_attr(irn)->x87[pos + 2];
214         }
215         return arch_register_get_name(reg);
216 }
217
218 /**
219  * Get the register name for a node.
220  */
221 static int ia32_get_reg_name(lc_appendable_t *app,
222     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
223 {
224         const char *buf;
225         ir_node    *X  = arg->v_ptr;
226         int         nr = occ->width - 1;
227
228         if (!X)
229                 return lc_appendable_snadd(app, "(null)", 6);
230
231         buf = get_ia32_reg_name(X, nr, occ->conversion == 'S' ? IN_REG : OUT_REG);
232
233         /* append the stupid % to register names */
234         lc_appendable_chadd(app, '%');
235         return lc_appendable_snadd(app, buf, strlen(buf));
236 }
237
238 /**
239  * Get the x87 register name for a node.
240  */
241 static int ia32_get_x87_name(lc_appendable_t *app,
242     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
243 {
244         const char *buf;
245         ir_node     *X  = arg->v_ptr;
246         int         nr = occ->width - 1;
247         ia32_attr_t *attr;
248
249         if (!X)
250                 return lc_appendable_snadd(app, "(null)", 6);
251
252         attr = get_ia32_attr(X);
253         buf = attr->x87[nr]->name;
254         lc_appendable_chadd(app, '%');
255         return lc_appendable_snadd(app, buf, strlen(buf));
256 }
257
258 /**
259  * Returns the tarval, offset or scale of an ia32 as a string.
260  */
261 static int ia32_const_to_str(lc_appendable_t *app,
262     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
263 {
264         const char *buf;
265         ir_node    *X = arg->v_ptr;
266
267         if (!X)
268                 return lc_arg_append(app, occ, "(null)", 6);
269
270         if (occ->conversion == 'C') {
271                 buf = get_ia32_cnst(X);
272         }
273         else { /* 'O' */
274                 buf = get_ia32_am_offs(X);
275         }
276
277         return buf ? lc_appendable_snadd(app, buf, strlen(buf)) : 0;
278 }
279
280 /**
281  * Determines the SSE suffix depending on the mode.
282  */
283 static int ia32_get_mode_suffix(lc_appendable_t *app,
284     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
285 {
286         ir_node *X    = arg->v_ptr;
287         ir_mode *mode = get_irn_mode(X);
288
289         if (mode == mode_T) {
290                 mode = is_ia32_AddrModeS(X) || is_ia32_AddrModeD(X) ? get_ia32_ls_mode(X) : get_ia32_res_mode(X);
291         }
292
293         if (!X)
294                 return lc_arg_append(app, occ, "(null)", 6);
295
296         if (mode_is_float(mode)) {
297                 return lc_appendable_chadd(app, get_mode_size_bits(mode) == 32 ? 's' : 'd');
298         }
299         else {
300                 return lc_appendable_chadd(app, mode_is_signed(mode) ? 's' : 'z');
301         }
302 }
303
304 /**
305  * Return the ia32 printf arg environment.
306  * We use the firm environment with some additional handlers.
307  */
308 const lc_arg_env_t *ia32_get_arg_env(void) {
309         static lc_arg_env_t *env = NULL;
310
311         static const lc_arg_handler_t ia32_reg_handler   = { ia32_get_arg_type, ia32_get_reg_name };
312         static const lc_arg_handler_t ia32_const_handler = { ia32_get_arg_type, ia32_const_to_str };
313         static const lc_arg_handler_t ia32_mode_handler  = { ia32_get_arg_type, ia32_get_mode_suffix };
314         static const lc_arg_handler_t ia32_x87_handler   = { ia32_get_arg_type, ia32_get_x87_name };
315
316         if(env == NULL) {
317                 /* extend the firm printer */
318                 env = firm_get_arg_env();
319
320                 lc_arg_register(env, "ia32:sreg", 'S', &ia32_reg_handler);
321                 lc_arg_register(env, "ia32:dreg", 'D', &ia32_reg_handler);
322                 lc_arg_register(env, "ia32:cnst", 'C', &ia32_const_handler);
323                 lc_arg_register(env, "ia32:offs", 'O', &ia32_const_handler);
324                 lc_arg_register(env, "ia32:mode", 'M', &ia32_mode_handler);
325                 lc_arg_register(env, "ia32:x87",  'X', &ia32_x87_handler);
326         }
327
328         return env;
329 }
330
331 static char *ia32_get_reg_name_for_mode(ia32_emit_env_t *env, ir_mode *mode, const arch_register_t *reg) {
332         switch(get_mode_size_bits(mode)) {
333                 case 8:
334                         return ia32_get_mapped_reg_name(env->isa->regs_8bit, reg);
335                 case 16:
336                         return ia32_get_mapped_reg_name(env->isa->regs_16bit, reg);
337                 default:
338                         return (char *)arch_register_get_name(reg);
339         }
340 }
341
342 /**
343  * Emits registers and/or address mode of a binary operation.
344  */
345 char *ia32_emit_binop(const ir_node *n, ia32_emit_env_t *env) {
346         static char *buf = NULL;
347
348         /* verify that this function is never called on non-AM supporting operations */
349         //assert(get_ia32_am_support(n) != ia32_am_None && "emit binop expects addressmode support");
350
351 #define PRODUCES_RESULT(n)   \
352         (!(is_ia32_St(n)      || \
353         is_ia32_Store8Bit(n)  || \
354         is_ia32_CondJmp(n)    || \
355         is_ia32_fCondJmp(n)   || \
356         is_ia32_SwitchJmp(n)))
357
358         if (! buf) {
359                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
360         }
361         else {
362                 memset(buf, 0, SNPRINTF_BUF_LEN);
363         }
364
365         switch(get_ia32_op_type(n)) {
366                 case ia32_Normal:
367                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
368                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%3S, %s", n, get_ia32_cnst(n));
369                         }
370                         else {
371                                 const arch_register_t *in1 = get_in_reg(n, 2);
372                                 const arch_register_t *in2 = get_in_reg(n, 3);
373                                 const arch_register_t *out = PRODUCES_RESULT(n) ? get_out_reg(n, 0) : NULL;
374                                 const arch_register_t *in;
375                                 const char            *in_name;
376
377                                 in      = out ? (REGS_ARE_EQUAL(out, in2) ? in1 : in2) : in2;
378                                 out     = out ? out : in1;
379                                 in_name = arch_register_get_name(in);
380
381                                 if (is_ia32_emit_cl(n)) {
382                                         assert(REGS_ARE_EQUAL(&ia32_gp_regs[REG_ECX], in) && "shift operation needs ecx");
383                                         in_name = "cl";
384                                 }
385
386                                 snprintf(buf, SNPRINTF_BUF_LEN, "%%%s, %%%s", arch_register_get_name(out), in_name);
387                         }
388                         break;
389                 case ia32_AddrModeS:
390                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
391                                 assert(! PRODUCES_RESULT(n) && "Source AM with Const must not produce result");
392                                 snprintf(buf, SNPRINTF_BUF_LEN, "%s, %s", get_ia32_cnst(n), ia32_emit_am(n, env));
393                         }
394                         else {
395                                 if (PRODUCES_RESULT(n)) {
396                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, ia32_emit_am(n, env));
397                                 }
398                                 else {
399                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%4S, %s", n, ia32_emit_am(n, env));
400                                 }
401                         }
402                         break;
403                 case ia32_AddrModeD:
404                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
405                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s,%s%s",
406                                         ia32_emit_am(n, env),
407                                         is_ia32_ImmSymConst(n) ? " OFFSET FLAT:" : " ",  /* In case of a symconst we must add OFFSET to */
408                                         get_ia32_cnst(n));                               /* tell the assembler to store it's address.   */
409                         }
410                         else {
411                                 const arch_register_t *in1 = get_in_reg(n, 2);
412                                 ir_mode              *mode = get_ia32_res_mode(n);
413                                 const char           *in_name;
414
415                                 mode    = mode ? mode : get_ia32_ls_mode(n);
416                                 in_name = ia32_get_reg_name_for_mode(env, mode, in1);
417
418                                 if (is_ia32_emit_cl(n)) {
419                                         assert(REGS_ARE_EQUAL(&ia32_gp_regs[REG_ECX], in1) && "shift operation needs ecx");
420                                         in_name = "cl";
421                                 }
422
423                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %%%s", ia32_emit_am(n, env), in_name);
424                         }
425                         break;
426                 default:
427                         assert(0 && "unsupported op type");
428         }
429
430 #undef PRODUCES_RESULT
431
432         return buf;
433 }
434
435 /**
436  * Emits registers and/or address mode of a binary operation.
437  */
438 char *ia32_emit_x87_binop(const ir_node *n, ia32_emit_env_t *env) {
439         static char *buf = NULL;
440
441         /* verify that this function is never called on non-AM supporting operations */
442         //assert(get_ia32_am_support(n) != ia32_am_None && "emit binop expects addressmode support");
443
444         if (! buf) {
445                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
446         }
447         else {
448                 memset(buf, 0, SNPRINTF_BUF_LEN);
449         }
450
451         switch(get_ia32_op_type(n)) {
452                 case ia32_Normal:
453                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
454                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%3S, %s", n, get_ia32_cnst(n));
455                         }
456                         else {
457                                 ia32_attr_t *attr = get_ia32_attr(n);
458                                 const arch_register_t *in1 = attr->x87[0];
459                                 const arch_register_t *in2 = attr->x87[1];
460                                 const arch_register_t *out = attr->x87[2];
461                                 const arch_register_t *in;
462                                 const char            *in_name;
463
464                                 in      = out ? (REGS_ARE_EQUAL(out, in2) ? in1 : in2) : in2;
465                                 out     = out ? out : in1;
466                                 in_name = arch_register_get_name(in);
467
468                                 snprintf(buf, SNPRINTF_BUF_LEN, "%%%s, %%%s", arch_register_get_name(out), in_name);
469                         }
470                         break;
471                 case ia32_AddrModeS:
472                 case ia32_AddrModeD:
473                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s", ia32_emit_am(n, env));
474                         break;
475                 default:
476                         assert(0 && "unsupported op type");
477         }
478
479 #undef PRODUCES_RESULT
480
481         return buf;
482 }
483
484 /**
485  * Emits registers and/or address mode of a unary operation.
486  */
487 char *ia32_emit_unop(const ir_node *n, ia32_emit_env_t *env) {
488         static char *buf = NULL;
489
490         if (! buf) {
491                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
492         }
493         else {
494                 memset(buf, 0, SNPRINTF_BUF_LEN);
495         }
496
497         switch(get_ia32_op_type(n)) {
498                 case ia32_Normal:
499                         if (is_ia32_ImmConst(n) || is_ia32_ImmSymConst(n)) {
500                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%C", n);
501                         }
502                         else {
503                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
504                         }
505                         break;
506                 case ia32_am_Dest:
507                         snprintf(buf, SNPRINTF_BUF_LEN, ia32_emit_am(n, env));
508                         break;
509                 default:
510                         assert(0 && "unsupported op type");
511         }
512
513         return buf;
514 }
515
516 /**
517  * Emits address mode.
518  */
519 char *ia32_emit_am(const ir_node *n, ia32_emit_env_t *env) {
520         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
521         int               had_output = 0;
522         char             *s;
523         int               size;
524         static struct obstack *obst  = NULL;
525         ir_mode *mode = get_ia32_ls_mode(n);
526
527         if (! is_ia32_Lea(n))
528                 assert(mode && "AM node must have ls_mode attribute set.");
529
530         if (! obst) {
531                 obst = xcalloc(1, sizeof(*obst));
532         }
533         else {
534                 obstack_free(obst, NULL);
535         }
536
537         /* obstack_free with NULL results in an uninitialized obstack */
538         obstack_init(obst);
539
540         if (mode) {
541                 switch (get_mode_size_bits(mode)) {
542                         case 8:
543                                 obstack_printf(obst, "BYTE PTR ");
544                                 break;
545                         case 16:
546                                 obstack_printf(obst, "WORD PTR ");
547                                 break;
548                         case 32:
549                                 obstack_printf(obst, "DWORD PTR ");
550                                 break;
551                         case 64:
552                                 if (has_x87_register(n))
553                                         /* ARGHHH: stupid gas x87 wants QWORD PTR but SSE must be WITHOUT */
554                                         obstack_printf(obst, "QWORD PTR ");
555                                 break;
556                         case 80:
557                         case 96:
558                                 obstack_printf(obst, "XWORD PTR ");
559                                 break;
560                         default:
561                                 break;
562                 }
563         }
564
565         /* emit address mode symconst */
566         if (get_ia32_am_sc(n)) {
567                 if (is_ia32_am_sc_sign(n))
568                         obstack_printf(obst, "-");
569                 obstack_printf(obst, "%s", get_id_str(get_ia32_am_sc(n)));
570         }
571
572         if (am_flav & ia32_B) {
573                 obstack_printf(obst, "[");
574                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
575                 had_output = 1;
576         }
577
578         if (am_flav & ia32_I) {
579                 if (had_output) {
580                         obstack_printf(obst, "+");
581                 }
582                 else {
583                         obstack_printf(obst, "[");
584                 }
585
586                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
587
588                 if (am_flav & ia32_S) {
589                         obstack_printf(obst, "*%d", 1 << get_ia32_am_scale(n));
590                 }
591
592                 had_output = 1;
593         }
594
595         if (am_flav & ia32_O) {
596                 s = get_ia32_am_offs(n);
597
598                 if (s) {
599                         /* omit explicit + if there was no base or index */
600                         if (! had_output) {
601                                 obstack_printf(obst, "[");
602                                 if (s[0] == '+')
603                                         s++;
604                         }
605
606                         obstack_printf(obst, s);
607                         had_output = 1;
608                 }
609         }
610
611         if (had_output)
612                 obstack_printf(obst, "] ");
613
614         size        = obstack_object_size(obst);
615         s           = obstack_finish(obst);
616         s[size - 1] = '\0';
617
618         return s;
619 }
620
621
622
623 /**
624  * Formated print of commands and comments.
625  */
626 static void ia32_fprintf_format(FILE *F, const ir_node *irn, char *cmd_buf, char *cmnt_buf) {
627         unsigned lineno;
628         const char *name = irn ? be_retrieve_dbg_info(get_irn_dbg_info((ir_node *)irn), &lineno) : NULL;
629
630         if (name)
631                 fprintf(F, "\t%-35s %-60s /* %s:%u */\n", cmd_buf, cmnt_buf, name, lineno);
632         else
633                 fprintf(F, "\t%-35s %-60s\n", cmd_buf, cmnt_buf);
634 }
635
636
637
638 /**
639  * Add a number to a prefix. This number will not be used a second time.
640  */
641 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
642         static unsigned long id = 0;
643         snprintf(buf, buflen, "%s%lu", prefix, ++id);
644         return buf;
645 }
646
647
648
649 /*************************************************
650  *                 _ _                         _
651  *                (_) |                       | |
652  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
653  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
654  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
655  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
656  *
657  *************************************************/
658
659 #undef IA32_DO_EMIT
660 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
661
662 /*
663  * coding of conditions
664  */
665 struct cmp2conditon_t {
666         const char *name;
667         pn_Cmp      num;
668 };
669
670 /*
671  * positive conditions for signed compares
672  */
673 static const struct cmp2conditon_t cmp2condition_s[] = {
674   { NULL,              pn_Cmp_False },  /* always false */
675   { "e",               pn_Cmp_Eq },     /* == */
676   { "l",               pn_Cmp_Lt },     /* < */
677   { "le",              pn_Cmp_Le },     /* <= */
678   { "g",               pn_Cmp_Gt },     /* > */
679   { "ge",              pn_Cmp_Ge },     /* >= */
680   { "ne",              pn_Cmp_Lg },     /* != */
681   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
682   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
683   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
684   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
685   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
686   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
687   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
688   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
689   { NULL,              pn_Cmp_True },   /* always true */
690 };
691
692 /*
693  * positive conditions for unsigned compares
694  */
695 static const struct cmp2conditon_t cmp2condition_u[] = {
696         { NULL,              pn_Cmp_False },  /* always false */
697         { "e",               pn_Cmp_Eq },     /* == */
698         { "b",               pn_Cmp_Lt },     /* < */
699         { "be",              pn_Cmp_Le },     /* <= */
700         { "a",               pn_Cmp_Gt },     /* > */
701         { "ae",              pn_Cmp_Ge },     /* >= */
702         { "ne",              pn_Cmp_Lg },     /* != */
703         { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
704         { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
705         { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
706         { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
707         { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
708         { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
709         { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
710         { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
711         { NULL,              pn_Cmp_True },   /* always true */
712 };
713
714 /*
715  * returns the condition code
716  */
717 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
718 {
719         assert(cmp2condition_s[cmp_code].num == cmp_code);
720         assert(cmp2condition_u[cmp_code].num == cmp_code);
721
722         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
723 }
724
725 /**
726  * Returns the target block for a control flow node.
727  */
728 static ir_node *get_cfop_target_block(const ir_node *irn) {
729         return get_irn_link(irn);
730 }
731
732 /**
733  * Returns the target label for a control flow node.
734  */
735 static char *get_cfop_target(const ir_node *irn, char *buf) {
736         ir_node *bl = get_cfop_target_block(irn);
737
738         snprintf(buf, SNPRINTF_BUF_LEN, BLOCK_PREFIX("%ld"), get_irn_node_nr(bl));
739         return buf;
740 }
741
742 /** Return the next block in Block schedule */
743 static ir_node *next_blk_sched(const ir_node *block) {
744         return get_irn_link(block);
745 }
746
747 /**
748  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
749  */
750 static void finish_CondJmp(FILE *F, const ir_node *irn, ir_mode *mode) {
751         const ir_node   *proj1, *proj2 = NULL;
752         const ir_node   *block, *next_bl = NULL;
753         const ir_edge_t *edge;
754         char buf[SNPRINTF_BUF_LEN];
755         char cmd_buf[SNPRINTF_BUF_LEN];
756         char cmnt_buf[SNPRINTF_BUF_LEN];
757
758         /* get both Proj's */
759         edge = get_irn_out_edge_first(irn);
760         proj1 = get_edge_src_irn(edge);
761         assert(is_Proj(proj1) && "CondJmp with a non-Proj");
762
763         edge = get_irn_out_edge_next(irn, edge);
764         if (edge) {
765                 proj2 = get_edge_src_irn(edge);
766                 assert(is_Proj(proj2) && "CondJmp with a non-Proj");
767         }
768
769         /* for now, the code works for scheduled and non-schedules blocks */
770         block = get_nodes_block(irn);
771         if (proj2) {
772                 /* we have a block schedule */
773                 next_bl = next_blk_sched(block);
774
775                 if (get_cfop_target_block(proj1) == next_bl) {
776                         /* exchange both proj's so the second one can be omitted */
777                         const ir_node *t = proj1;
778                         proj1 = proj2;
779                         proj2 = t;
780                 }
781         }
782
783         /* the first Proj must always be created */
784         if (get_Proj_proj(proj1) == pn_Cond_true) {
785                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
786                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
787                                         get_cfop_target(proj1, buf));
788                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == TRUE */");
789         }
790         else  {
791                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
792                                         get_cmp_suffix(get_negated_pnc(get_ia32_pncode(irn), mode),
793                                         !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
794                                         get_cfop_target(proj1, buf));
795                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == FALSE */");
796         }
797         IA32_DO_EMIT(irn);
798
799         /* the second Proj might be a fallthrough */
800         if (proj2) {
801                 if (get_cfop_target_block(proj2) != next_bl) {
802                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(proj2, buf));
803                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* otherwise */");
804                 }
805                 else {
806                         cmd_buf[0] = '\0';
807                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* fallthrogh %s */", get_cfop_target(proj2, buf));
808                 }
809                 IA32_DO_EMIT(irn);
810         }
811 }
812
813 /**
814  * Emits code for conditional jump.
815  */
816 static void CondJmp_emitter(const ir_node *irn, ia32_emit_env_t *env) {
817         FILE *F = env->out;
818         char cmd_buf[SNPRINTF_BUF_LEN];
819         char cmnt_buf[SNPRINTF_BUF_LEN];
820
821         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cmp %s", ia32_emit_binop(irn, env));
822         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
823         IA32_DO_EMIT(irn);
824         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
825 }
826
827 /**
828  * Emits code for conditional jump with two variables.
829  */
830 static void emit_ia32_CondJmp(const ir_node *irn, ia32_emit_env_t *env) {
831         CondJmp_emitter(irn, env);
832 }
833
834 /**
835  * Emits code for conditional test and jump.
836  */
837 static void TestJmp_emitter(const ir_node *irn, ia32_emit_env_t *env) {
838
839 #define IA32_IS_IMMOP (is_ia32_ImmConst(irn) || is_ia32_ImmSymConst(irn))
840
841         FILE       *F   = env->out;
842         const char *op1 = arch_register_get_name(get_in_reg(irn, 0));
843         const char *op2 = IA32_IS_IMMOP ? get_ia32_cnst(irn) : NULL;
844         char        cmd_buf[SNPRINTF_BUF_LEN];
845         char        cmnt_buf[SNPRINTF_BUF_LEN];
846
847         if (! op2)
848                 op2 = arch_register_get_name(get_in_reg(irn, 1));
849
850         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "test %%%s,%s%s ", op1, IA32_IS_IMMOP ? " " : " %", op2);
851         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
852
853         IA32_DO_EMIT(irn);
854         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
855
856 #undef IA32_IS_IMMOP
857 }
858
859 /**
860  * Emits code for conditional test and jump with two variables.
861  */
862 static void emit_ia32_TestJmp(const ir_node *irn, ia32_emit_env_t *env) {
863         TestJmp_emitter(irn, env);
864 }
865
866 static void emit_ia32_CJmp(const ir_node *irn, ia32_emit_env_t *env) {
867         FILE *F = env->out;
868         char cmd_buf[SNPRINTF_BUF_LEN];
869         char cmnt_buf[SNPRINTF_BUF_LEN];
870
871         snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
872         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F omitted redundant test */", irn);
873         IA32_DO_EMIT(irn);
874         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
875 }
876
877 static void emit_ia32_CJmpAM(const ir_node *irn, ia32_emit_env_t *env) {
878         FILE *F = env->out;
879         char cmd_buf[SNPRINTF_BUF_LEN];
880         char cmnt_buf[SNPRINTF_BUF_LEN];
881
882         snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
883         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F omitted redundant test/cmp */", irn);
884         IA32_DO_EMIT(irn);
885         finish_CondJmp(F, irn, get_ia32_res_mode(irn));
886 }
887
888 /*********************************************************
889  *                 _ _       _
890  *                (_) |     (_)
891  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
892  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
893  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
894  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
895  *                         _/ |               | |
896  *                        |__/                |_|
897  *********************************************************/
898
899 /* jump table entry (target and corresponding number) */
900 typedef struct _branch_t {
901         ir_node *target;
902         int      value;
903 } branch_t;
904
905 /* jump table for switch generation */
906 typedef struct _jmp_tbl_t {
907         ir_node  *defProj;         /**< default target */
908         int       min_value;       /**< smallest switch case */
909         int       max_value;       /**< largest switch case */
910         int       num_branches;    /**< number of jumps */
911         char     *label;           /**< label of the jump table */
912         branch_t *branches;        /**< jump array */
913 } jmp_tbl_t;
914
915 /**
916  * Compare two variables of type branch_t. Used to sort all switch cases
917  */
918 static int ia32_cmp_branch_t(const void *a, const void *b) {
919         branch_t *b1 = (branch_t *)a;
920         branch_t *b2 = (branch_t *)b;
921
922         if (b1->value <= b2->value)
923                 return -1;
924         else
925                 return 1;
926 }
927
928 /**
929  * Emits code for a SwitchJmp (creates a jump table if
930  * possible otherwise a cmp-jmp cascade). Port from
931  * cggg ia32 backend
932  */
933 static void emit_ia32_SwitchJmp(const ir_node *irn, ia32_emit_env_t *emit_env) {
934         unsigned long       interval;
935         char                buf[SNPRINTF_BUF_LEN];
936         int                 last_value, i, pn;
937         jmp_tbl_t           tbl;
938         ir_node            *proj;
939         const ir_edge_t    *edge;
940         const lc_arg_env_t *env = ia32_get_arg_env();
941         FILE               *F   = emit_env->out;
942         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
943
944         /* fill the table structure */
945         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
946         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
947         tbl.defProj      = NULL;
948         tbl.num_branches = get_irn_n_edges(irn);
949         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
950         tbl.min_value    = INT_MAX;
951         tbl.max_value    = INT_MIN;
952
953         i = 0;
954         /* go over all proj's and collect them */
955         foreach_out_edge(irn, edge) {
956                 proj = get_edge_src_irn(edge);
957                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
958
959                 pn = get_Proj_proj(proj);
960
961                 /* create branch entry */
962                 tbl.branches[i].target = proj;
963                 tbl.branches[i].value  = pn;
964
965                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
966                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
967
968                 /* check for default proj */
969                 if (pn == get_ia32_pncode(irn)) {
970                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
971                         tbl.defProj = proj;
972                 }
973
974                 i++;
975         }
976
977         /* sort the branches by their number */
978         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
979
980         /* two-complement's magic make this work without overflow */
981         interval = tbl.max_value - tbl.min_value;
982
983         /* emit the table */
984         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmp %1S, %u", irn, interval);
985         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* compare for switch */");
986         IA32_DO_EMIT(irn);
987
988         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "ja %s", get_cfop_target(tbl.defProj, buf));
989         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default jump if out of range  */");
990         IA32_DO_EMIT(irn);
991
992         if (tbl.num_branches > 1) {
993                 /* create table */
994
995                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "jmp %s[%1S*4]", tbl.label, irn);
996                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* get jump table entry as target */");
997                 IA32_DO_EMIT(irn);
998
999                 ia32_switch_section(F, SECTION_RODATA);
1000                 fprintf(F, "\t.align 4\n");
1001
1002                 fprintf(F, "%s:\n", tbl.label);
1003
1004                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[0].target, buf));
1005                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */",  tbl.branches[0].value);
1006                 IA32_DO_EMIT(irn);
1007
1008                 last_value = tbl.branches[0].value;
1009                 for (i = 1; i < tbl.num_branches; ++i) {
1010                         while (++last_value < tbl.branches[i].value) {
1011                                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.defProj, buf));
1012                                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
1013                                 IA32_DO_EMIT(irn);
1014                         }
1015                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[i].target, buf));
1016                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", last_value);
1017                         IA32_DO_EMIT(irn);
1018                 }
1019                 ia32_switch_section(F, SECTION_TEXT);
1020         }
1021         else {
1022                 /* one jump is enough */
1023                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.branches[0].target, buf));
1024                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* only one case given */");
1025                 IA32_DO_EMIT(irn);
1026         }
1027
1028         if (tbl.label)
1029                 free(tbl.label);
1030         if (tbl.branches)
1031                 free(tbl.branches);
1032 }
1033
1034 /**
1035  * Emits code for a unconditional jump.
1036  */
1037 static void emit_Jmp(const ir_node *irn, ia32_emit_env_t *env) {
1038         ir_node *block, *next_bl;
1039         FILE *F = env->out;
1040         char buf[SNPRINTF_BUF_LEN], cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1041
1042         /* for now, the code works for scheduled and non-schedules blocks */
1043         block = get_nodes_block(irn);
1044
1045         /* we have a block schedule */
1046         next_bl = next_blk_sched(block);
1047         if (get_cfop_target_block(irn) != next_bl) {
1048                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(irn, buf));
1049                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F) */", irn, get_cfop_target_block(irn));
1050         }
1051         else {
1052                 cmd_buf[0] = '\0';
1053                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* fallthrough %s */", get_cfop_target(irn, buf));
1054         }
1055         IA32_DO_EMIT(irn);
1056 }
1057
1058 /****************************
1059  *                  _
1060  *                 (_)
1061  *  _ __  _ __ ___  _  ___
1062  * | '_ \| '__/ _ \| |/ __|
1063  * | |_) | | | (_) | |\__ \
1064  * | .__/|_|  \___/| ||___/
1065  * | |            _/ |
1066  * |_|           |__/
1067  ****************************/
1068
1069 /**
1070  * Emits code for a proj -> node
1071  */
1072 static void emit_Proj(const ir_node *irn, ia32_emit_env_t *env) {
1073         ir_node *pred = get_Proj_pred(irn);
1074
1075         if (get_irn_op(pred) == op_Start) {
1076                 switch(get_Proj_proj(irn)) {
1077                         case pn_Start_X_initial_exec:
1078                                 emit_Jmp(irn, env);
1079                                 break;
1080                         default:
1081                                 break;
1082                 }
1083         }
1084 }
1085
1086 /**********************************
1087  *   _____                  ____
1088  *  / ____|                |  _ \
1089  * | |     ___  _ __  _   _| |_) |
1090  * | |    / _ \| '_ \| | | |  _ <
1091  * | |___| (_) | |_) | |_| | |_) |
1092  *  \_____\___/| .__/ \__, |____/
1093  *             | |     __/ |
1094  *             |_|    |___/
1095  **********************************/
1096
1097 /**
1098  * Emit movsb/w instructions to make mov count divideable by 4
1099  */
1100 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
1101         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1102
1103         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
1104
1105         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cld");
1106         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* copy direction forward*/");
1107         IA32_DO_EMIT(NULL);
1108
1109         switch(rem) {
1110                 case 1:
1111                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
1112                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 1 */");
1113                         break;
1114                 case 2:
1115                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
1116                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 2 */");
1117                         break;
1118                 case 3:
1119                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
1120                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
1121                         IA32_DO_EMIT(NULL);
1122                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
1123                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
1124                         break;
1125         }
1126
1127         IA32_DO_EMIT(NULL);
1128 }
1129
1130 /**
1131  * Emit rep movsd instruction for memcopy.
1132  */
1133 static void emit_ia32_CopyB(const ir_node *irn, ia32_emit_env_t *emit_env) {
1134         FILE    *F         = emit_env->out;
1135         tarval  *tv        = get_ia32_Immop_tarval(irn);
1136         int      rem       = get_tarval_long(tv);
1137         ir_node *size_node = get_irn_n(irn, 2);
1138         int      size;
1139         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1140
1141         /* beware: size_node could be a be_Copy to fulfill constraints for ecx */
1142         size_node = be_is_Copy(size_node) ? be_get_Copy_op(size_node) : size_node;
1143         size      = get_tarval_long(get_ia32_Immop_tarval(size_node));
1144
1145         emit_CopyB_prolog(F, rem, size);
1146
1147         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "rep movsd");
1148         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy */");
1149         IA32_DO_EMIT(irn);
1150 }
1151
1152 /**
1153  * Emits unrolled memcopy.
1154  */
1155 static void emit_ia32_CopyB_i(const ir_node *irn, ia32_emit_env_t *emit_env) {
1156         tarval *tv   = get_ia32_Immop_tarval(irn);
1157         int     size = get_tarval_long(tv);
1158         FILE   *F    = emit_env->out;
1159         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1160
1161         emit_CopyB_prolog(F, size & 0x3, size);
1162
1163         size >>= 2;
1164         while (size--) {
1165                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsd");
1166                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy unrolled */");
1167                 IA32_DO_EMIT(irn);
1168         }
1169 }
1170
1171
1172
1173 /***************************
1174  *   _____
1175  *  / ____|
1176  * | |     ___  _ ____   __
1177  * | |    / _ \| '_ \ \ / /
1178  * | |___| (_) | | | \ V /
1179  *  \_____\___/|_| |_|\_/
1180  *
1181  ***************************/
1182
1183 /**
1184  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1185  */
1186 static void emit_ia32_Conv_with_FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1187         FILE               *F        = emit_env->out;
1188         const lc_arg_env_t *env      = ia32_get_arg_env();
1189         ir_mode            *src_mode = get_ia32_src_mode(irn);
1190         ir_mode            *tgt_mode = get_ia32_tgt_mode(irn);
1191         char               *from, *to, buf[64];
1192         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1193
1194         from = mode_is_float(src_mode) ? (get_mode_size_bits(src_mode) == 32 ? "ss" : "sd") : "si";
1195         to   = mode_is_float(tgt_mode) ? (get_mode_size_bits(tgt_mode) == 32 ? "ss" : "sd") : "si";
1196
1197         switch(get_ia32_op_type(irn)) {
1198                 case ia32_Normal:
1199                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %3S", irn, irn);
1200                         break;
1201                 case ia32_AddrModeS:
1202                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %s", irn, ia32_emit_am(irn, emit_env));
1203                         break;
1204                 default:
1205                         assert(0 && "unsupported op type for Conv");
1206         }
1207
1208         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cvt%s2%s %s", from, to, buf);
1209         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F, %+F) */", irn, src_mode, tgt_mode);
1210         IA32_DO_EMIT(irn);
1211 }
1212
1213 static void emit_ia32_Conv_I2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1214         emit_ia32_Conv_with_FP(irn, emit_env);
1215 }
1216
1217 static void emit_ia32_Conv_FP2I(const ir_node *irn, ia32_emit_env_t *emit_env) {
1218         emit_ia32_Conv_with_FP(irn, emit_env);
1219 }
1220
1221 static void emit_ia32_Conv_FP2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1222         emit_ia32_Conv_with_FP(irn, emit_env);
1223 }
1224
1225 /**
1226  * Emits code for an Int conversion.
1227  */
1228 static void emit_ia32_Conv_I2I(const ir_node *irn, ia32_emit_env_t *emit_env) {
1229         FILE               *F        = emit_env->out;
1230         const lc_arg_env_t *env      = ia32_get_arg_env();
1231         char               *move_cmd = "movzx";
1232         char               *conv_cmd = NULL;
1233         ir_mode            *src_mode = get_ia32_src_mode(irn);
1234         ir_mode            *tgt_mode = get_ia32_tgt_mode(irn);
1235         int n, m;
1236         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1237         const arch_register_t *in_reg, *out_reg;
1238
1239         n = get_mode_size_bits(src_mode);
1240         m = get_mode_size_bits(tgt_mode);
1241
1242         if (mode_is_signed(n < m ? src_mode : tgt_mode)) {
1243                 move_cmd = "movsx";
1244                 if (n == 8 || m == 8)
1245                         conv_cmd = "cbw";
1246                 else if (n == 16 || m == 16)
1247                         conv_cmd = "cwde";
1248                 else
1249                         assert(0 && "unsupported Conv_I2I");
1250         }
1251
1252         switch(get_ia32_op_type(irn)) {
1253                 case ia32_Normal:
1254                         in_reg  = get_in_reg(irn, 2);
1255                         out_reg = get_out_reg(irn, 0);
1256
1257                         if (REGS_ARE_EQUAL(in_reg, &ia32_gp_regs[REG_EAX]) &&
1258                                 REGS_ARE_EQUAL(out_reg, in_reg)                &&
1259                                 mode_is_signed(n < m ? src_mode : tgt_mode))
1260                         {
1261                                 /* argument and result are both in EAX and */
1262                                 /* signedness is ok: -> use converts       */
1263                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s", conv_cmd);
1264                         }
1265                         else if (REGS_ARE_EQUAL(out_reg, in_reg) &&
1266                                 ! mode_is_signed(n < m ? src_mode : tgt_mode))
1267                         {
1268                                 /* argument and result are in the same register */
1269                                 /* and signedness is ok: -> use and with mask   */
1270                                 int mask = (1 << (n < m ? n : m)) - 1;
1271                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "and %1D, 0x%x", irn, mask);
1272                         }
1273                         else {
1274                                 /* use move w/o sign extension */
1275                                 lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s %1D, %%%s",
1276                                         move_cmd, irn, ia32_get_reg_name_for_mode(emit_env, n < m ? src_mode : tgt_mode, in_reg));
1277                         }
1278
1279                         break;
1280                 case ia32_AddrModeS:
1281                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "%s %1D, %s",
1282                                 move_cmd, irn, ia32_emit_am(irn, emit_env));
1283                         break;
1284                 default:
1285                         assert(0 && "unsupported op type for Conv");
1286         }
1287
1288         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%d Bit mode_%F -> %d Bit mode_%F) */",
1289                 irn, n, src_mode, m, tgt_mode);
1290
1291         IA32_DO_EMIT(irn);
1292 }
1293
1294 /**
1295  * Emits code for an 8Bit Int conversion.
1296  */
1297 void emit_ia32_Conv_I2I8Bit(const ir_node *irn, ia32_emit_env_t *emit_env) {
1298         emit_ia32_Conv_I2I(irn, emit_env);
1299 }
1300
1301
1302 /*******************************************
1303  *  _                          _
1304  * | |                        | |
1305  * | |__   ___ _ __   ___   __| | ___  ___
1306  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1307  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1308  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1309  *
1310  *******************************************/
1311
1312 /**
1313  * Emits a backend call
1314  */
1315 static void emit_be_Call(const ir_node *irn, ia32_emit_env_t *emit_env) {
1316         FILE *F = emit_env->out;
1317         entity *ent = be_Call_get_entity(irn);
1318         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1319
1320         if (ent) {
1321                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "call %s", get_entity_ld_name(ent));
1322         }
1323         else {
1324                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "%1D", get_irn_n(irn, be_pos_Call_ptr));
1325         }
1326
1327         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (be_Call) */", irn);
1328
1329         IA32_DO_EMIT(irn);
1330 }
1331
1332 /**
1333  * Emits code to increase stack pointer.
1334  */
1335 static void emit_be_IncSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1336         FILE          *F    = emit_env->out;
1337         unsigned       offs = be_get_IncSP_offset(irn);
1338         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
1339         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1340
1341         if (offs) {
1342                 if (dir == be_stack_dir_expand)
1343                         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "sub %1S, %u", irn, offs);
1344                 else
1345                         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "add %1S, %u", irn, offs);
1346                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (IncSP) */", irn);
1347         }
1348         else {
1349                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
1350                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* omitted %+F (IncSP) with 0 */", irn);
1351         }
1352
1353         IA32_DO_EMIT(irn);
1354 }
1355
1356 /**
1357  * Emits code to set stack pointer.
1358  */
1359 static void emit_be_SetSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1360         FILE *F = emit_env->out;
1361         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1362
1363         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %3S", irn, irn);
1364         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (restore SP) */", irn);
1365         IA32_DO_EMIT(irn);
1366 }
1367
1368 /**
1369  * Emits code for Copy.
1370  */
1371 static void emit_be_Copy(const ir_node *irn, ia32_emit_env_t *emit_env) {
1372         FILE *F = emit_env->out;
1373         const arch_env_t *aenv = emit_env->arch_env;
1374         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1375
1376         if (REGS_ARE_EQUAL(arch_get_irn_register(aenv, irn), arch_get_irn_register(aenv, be_get_Copy_op(irn))))
1377                 return;
1378
1379         if (mode_is_float(get_irn_mode(irn)))
1380                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "movs%M %1D, %1S", irn, irn, irn);
1381         else
1382                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %1S", irn, irn);
1383         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
1384         IA32_DO_EMIT(irn);
1385 }
1386
1387 /**
1388  * Emits code for exchange.
1389  */
1390 static void emit_be_Perm(const ir_node *irn, ia32_emit_env_t *emit_env) {
1391         FILE *F = emit_env->out;
1392         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1393
1394         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "xchg %1S, %2S", irn, irn);
1395         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%1A, %2A) */", irn, irn, irn);
1396         IA32_DO_EMIT(irn);
1397 }
1398
1399 /**
1400  * Emits code for Constant loading.
1401  */
1402 static void emit_ia32_Const(const ir_node *n, ia32_emit_env_t *env) {
1403   FILE *F = env->out;
1404   char cmd_buf[256], cmnt_buf[256];
1405   const lc_arg_env_t *arg_env = ia32_get_arg_env();
1406
1407   if (get_ia32_Immop_tarval(n) == get_tarval_null(get_irn_mode(n))) {
1408                 const char *instr = "xor";
1409                 if (env->isa->opt_arch == arch_pentium_4) {
1410                         /* P4 prefers sub r, r, others xor r, r */
1411                         instr = "sub";
1412                 }
1413     lc_esnprintf(arg_env, cmd_buf, 256, "%s %1D, %1D ", instr, n, n);
1414     lc_esnprintf(arg_env, cmnt_buf, 256, "/* optimized mov 0 to register */");
1415   }
1416   else {
1417     if (get_ia32_op_type(n) == ia32_SymConst) {
1418       lc_esnprintf(arg_env, cmd_buf, 256, "mov %1D, OFFSET FLAT:%C ", n, n);
1419       lc_esnprintf(arg_env, cmnt_buf, 256, "/* Move address of SymConst into register */");
1420     }
1421                 else {
1422                                 lc_esnprintf(arg_env, cmd_buf, 256, "mov %1D, %C ", n, n);
1423                                 lc_esnprintf(arg_env, cmnt_buf, 256, "/* Mov Const into register */");
1424                 }
1425   }
1426   lc_efprintf(arg_env, F, "\t%-35s %-60s /* %+F (%+G) */\n", cmd_buf, cmnt_buf, n, n);
1427 }
1428
1429
1430
1431 /***********************************************************************************
1432  *                  _          __                                             _
1433  *                 (_)        / _|                                           | |
1434  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1435  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1436  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1437  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1438  *
1439  ***********************************************************************************/
1440
1441 /**
1442  * Enters the emitter functions for handled nodes into the generic
1443  * pointer of an opcode.
1444  */
1445 static void ia32_register_emitters(void) {
1446
1447 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
1448 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
1449 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
1450
1451         /* first clear the generic function pointer for all ops */
1452         clear_irp_opcodes_generic_func();
1453
1454         /* register all emitter functions defined in spec */
1455         ia32_register_spec_emitters();
1456
1457         /* other ia32 emitter functions */
1458         IA32_EMIT(CondJmp);
1459         IA32_EMIT(TestJmp);
1460         IA32_EMIT(CJmp);
1461         IA32_EMIT(CJmpAM);
1462         IA32_EMIT(SwitchJmp);
1463         IA32_EMIT(CopyB);
1464         IA32_EMIT(CopyB_i);
1465         IA32_EMIT(Conv_I2FP);
1466         IA32_EMIT(Conv_FP2I);
1467         IA32_EMIT(Conv_FP2FP);
1468         IA32_EMIT(Conv_I2I);
1469         IA32_EMIT(Conv_I2I8Bit);
1470         IA32_EMIT(Const);
1471
1472         /* benode emitter */
1473         BE_EMIT(Call);
1474         BE_EMIT(IncSP);
1475         BE_EMIT(SetSP);
1476         BE_EMIT(Copy);
1477         BE_EMIT(Perm);
1478
1479         /* firm emitter */
1480         EMIT(Jmp);
1481         EMIT(Proj);
1482
1483 #undef IA32_EMIT
1484 #undef BE_EMIT
1485 #undef EMIT
1486 }
1487
1488 /**
1489  * Emits code for a node.
1490  */
1491 static void ia32_emit_node(const ir_node *irn, void *env) {
1492         ia32_emit_env_t   *emit_env = env;
1493         FILE              *F        = emit_env->out;
1494         ir_op             *op       = get_irn_op(irn);
1495         DEBUG_ONLY(firm_dbg_module_t *mod = emit_env->mod;)
1496
1497         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
1498
1499         if (op->ops.generic) {
1500                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
1501                 (*emit)(irn, env);
1502         }
1503         else {
1504                 ir_fprintf(F, "\t%35s /* %+F (%+G) */\n", " ", irn, irn);
1505         }
1506 }
1507
1508 /**
1509  * Walks over the nodes in a block connected by scheduling edges
1510  * and emits code for each node.
1511  */
1512 static void ia32_gen_block(ir_node *block, void *env) {
1513         const ir_node *irn;
1514
1515         if (! is_Block(block))
1516                 return;
1517
1518         fprintf(((ia32_emit_env_t *)env)->out, BLOCK_PREFIX("%ld:\n"), get_irn_node_nr(block));
1519         sched_foreach(block, irn) {
1520                 ia32_emit_node(irn, env);
1521         }
1522 }
1523
1524 /**
1525  * Emits code for function start.
1526  */
1527 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
1528         entity     *irg_ent  = get_irg_entity(irg);
1529         const char *irg_name = get_entity_ld_name(irg_ent);
1530
1531         fprintf(F, "\n");
1532         ia32_switch_section(F, SECTION_TEXT);
1533         if (get_entity_visibility(irg_ent) == visibility_external_visible) {
1534                 fprintf(F, ".globl %s\n", irg_name);
1535         }
1536         ia32_dump_function_object(F, irg_name);
1537         fprintf(F, "%s:\n", irg_name);
1538 }
1539
1540 /**
1541  * Emits code for function end
1542  */
1543 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
1544         const char *irg_name = get_entity_ld_name(get_irg_entity(irg));
1545
1546         fprintf(F, "\tret\n");
1547         ia32_dump_function_size(F, irg_name);
1548         fprintf(F, "\n");
1549 }
1550
1551 /**
1552  * Block-walker:
1553  * Sets labels for control flow nodes (jump target)
1554  * TODO: Jump optimization
1555  */
1556 static void ia32_gen_labels(ir_node *block, void *env) {
1557         ir_node *pred;
1558         int n = get_Block_n_cfgpreds(block);
1559
1560         for (n--; n >= 0; n--) {
1561                 pred = get_Block_cfgpred(block, n);
1562                 set_irn_link(pred, block);
1563         }
1564 }
1565
1566 /**
1567  * Main driver. Emits the code for one routine.
1568  */
1569 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
1570         ia32_emit_env_t emit_env;
1571         ir_node *block;
1572
1573         emit_env.out      = F;
1574         emit_env.arch_env = cg->arch_env;
1575         emit_env.cg       = cg;
1576         emit_env.isa      = (ia32_isa_t *)cg->arch_env->isa;
1577         FIRM_DBG_REGISTER(emit_env.mod, "firm.be.ia32.emitter");
1578
1579         /* set the global arch_env (needed by print hooks) */
1580         arch_env = cg->arch_env;
1581
1582         ia32_register_emitters();
1583
1584         ia32_emit_func_prolog(F, irg);
1585         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
1586
1587         if ((cg->opt & IA32_OPT_EXTBB) && cg->blk_sched) {
1588                 int i, n = ARR_LEN(cg->blk_sched);
1589
1590                 for (i = 0; i < n;) {
1591                         ir_node *next_bl;
1592
1593                         block   = cg->blk_sched[i];
1594                         ++i;
1595                         next_bl = i < n ? cg->blk_sched[i] : NULL;
1596
1597                         /* set here the link. the emitter expects to find the next block here */
1598                         set_irn_link(block, next_bl);
1599                         ia32_gen_block(block, &emit_env);
1600                 }
1601         }
1602         else {
1603                 /* "normal" block schedule: Note the get_next_block() returns the NUMBER of the block
1604                    in the block schedule. As this number should NEVER be equal the next block,
1605                    we does not need a clear block link here. */
1606                 irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
1607         }
1608
1609         ia32_emit_func_epilog(F, irg);
1610 }