fixed bug
[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.h"
25 #include "../benode_t.h"
26
27 #include "ia32_emitter.h"
28 #include "gen_ia32_emitter.h"
29 #include "ia32_nodes_attr.h"
30 #include "ia32_new_nodes.h"
31 #include "ia32_map_regs.h"
32
33 #ifdef obstack_chunk_alloc
34 # undef obstack_chunk_alloc
35 # define obstack_chunk_alloc xmalloc
36 #else
37 # define obstack_chunk_alloc xmalloc
38 # define obstack_chunk_free free
39 #endif
40
41 extern int obstack_printf(struct obstack *obst, char *fmt, ...);
42
43 #define SNPRINTF_BUF_LEN 128
44
45 static const arch_env_t *arch_env = NULL;
46
47 /*************************************************************
48  *             _       _    __   _          _
49  *            (_)     | |  / _| | |        | |
50  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
51  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
52  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
53  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
54  * | |                                       | |
55  * |_|                                       |_|
56  *************************************************************/
57
58 /* We always pass the ir_node which is a pointer. */
59 static int ia32_get_arg_type(const lc_arg_occ_t *occ) {
60         return lc_arg_type_ptr;
61 }
62
63
64 /**
65  * Returns the register at in position pos.
66  */
67 static const arch_register_t *get_in_reg(const ir_node *irn, int pos) {
68         ir_node                *op;
69         const arch_register_t  *reg = NULL;
70
71         assert(get_irn_arity(irn) > pos && "Invalid IN position");
72
73         /* The out register of the operator at position pos is the
74            in register we need. */
75         op = get_irn_n(irn, pos);
76
77         reg = arch_get_irn_register(arch_env, op);
78
79         assert(reg && "no in register found");
80         return reg;
81 }
82
83 /**
84  * Returns the register at out position pos.
85  */
86 static const arch_register_t *get_out_reg(const ir_node *irn, int pos) {
87         ir_node                *proj;
88         const arch_register_t  *reg = NULL;
89
90         /* 1st case: irn is not of mode_T, so it has only                 */
91         /*           one OUT register -> good                             */
92         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
93         /*           Proj with the corresponding projnum for the register */
94
95         if (get_irn_mode(irn) != mode_T) {
96                 reg = arch_get_irn_register(arch_env, irn);
97         }
98         else if (is_ia32_irn(irn)) {
99                 reg = get_ia32_out_reg(irn, pos);
100         }
101         else {
102                 const ir_edge_t *edge;
103
104                 foreach_out_edge(irn, edge) {
105                         proj = get_edge_src_irn(edge);
106                         assert(is_Proj(proj) && "non-Proj from mode_T node");
107                         if (get_Proj_proj(proj) == pos) {
108                                 reg = arch_get_irn_register(arch_env, proj);
109                                 break;
110                         }
111                 }
112         }
113
114         assert(reg && "no out register found");
115         return reg;
116 }
117
118 enum io_direction {
119   IN_REG,
120   OUT_REG
121 };
122
123 /**
124  * Returns the name of the in register at position pos.
125  */
126 static const char *get_ia32_reg_name(ir_node *irn, int pos, enum io_direction in_out) {
127         const arch_register_t *reg;
128
129         if (in_out == IN_REG) {
130                 reg = get_in_reg(irn, pos);
131         }
132         else {
133                 /* destination address mode nodes don't have outputs */
134                 if (is_ia32_irn(irn) && get_ia32_op_type(irn) == ia32_AddrModeD) {
135                         return "MEM";
136                 }
137
138                 reg = get_out_reg(irn, pos);
139         }
140
141         return arch_register_get_name(reg);
142 }
143
144 /**
145  * Get the register name for a node.
146  */
147 static int ia32_get_reg_name(lc_appendable_t *app,
148     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
149 {
150         const char *buf;
151         ir_node    *X  = arg->v_ptr;
152         int         nr = occ->width - 1;
153
154         if (!X)
155                 return lc_arg_append(app, occ, "(null)", 6);
156
157         buf = get_ia32_reg_name(X, nr, occ->conversion == 'S' ? IN_REG : OUT_REG);
158
159         return lc_arg_append(app, occ, buf, strlen(buf));
160 }
161
162 /**
163  * Returns the tarval, offset or scale of an ia32 as a string.
164  */
165 static int ia32_const_to_str(lc_appendable_t *app,
166     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
167 {
168         const char *buf;
169         ir_node    *X = arg->v_ptr;
170
171         if (!X)
172                 return lc_arg_append(app, occ, "(null)", 6);
173
174         if (occ->conversion == 'C') {
175                 buf = get_ia32_cnst(X);
176         }
177         else { /* 'O' */
178                 buf = get_ia32_am_offs(X);
179         }
180
181         return buf ? lc_arg_append(app, occ, buf, strlen(buf)) : 0;
182 }
183
184 /**
185  * Determines the SSE suffix depending on the mode.
186  */
187 static int ia32_get_mode_suffix(lc_appendable_t *app,
188     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
189 {
190         ir_node *X    = arg->v_ptr;
191         ir_mode *mode = get_irn_mode(X);
192
193         if (mode == mode_T) {
194                 mode = is_ia32_AddrModeS(X) || is_ia32_AddrModeD(X) ? get_ia32_ls_mode(X) : get_ia32_res_mode(X);
195         }
196
197         if (!X)
198                 return lc_arg_append(app, occ, "(null)", 6);
199
200         if (mode_is_float(mode)) {
201                 return lc_appendable_chadd(app, get_mode_size_bits(mode) == 32 ? 's' : 'd');
202         }
203         else {
204
205                 return lc_appendable_chadd(app, mode_is_signed(mode) ? 's' : 'z');
206         }
207 }
208
209 /**
210  * Return the ia32 printf arg environment.
211  * We use the firm environment with some additional handlers.
212  */
213 const lc_arg_env_t *ia32_get_arg_env(void) {
214         static lc_arg_env_t *env = NULL;
215
216         static const lc_arg_handler_t ia32_reg_handler   = { ia32_get_arg_type, ia32_get_reg_name };
217         static const lc_arg_handler_t ia32_const_handler = { ia32_get_arg_type, ia32_const_to_str };
218         static const lc_arg_handler_t ia32_mode_handler  = { ia32_get_arg_type, ia32_get_mode_suffix };
219
220         if(env == NULL) {
221                 /* extend the firm printer */
222                 env = firm_get_arg_env();
223
224                 lc_arg_register(env, "ia32:sreg", 'S', &ia32_reg_handler);
225                 lc_arg_register(env, "ia32:dreg", 'D', &ia32_reg_handler);
226                 lc_arg_register(env, "ia32:cnst", 'C', &ia32_const_handler);
227                 lc_arg_register(env, "ia32:offs", 'O', &ia32_const_handler);
228                 lc_arg_register(env, "ia32:mode", 'M', &ia32_mode_handler);
229         }
230
231         return env;
232 }
233
234 /**
235  * Emits registers and/or address mode of a binary operation.
236  */
237 char *ia32_emit_binop(const ir_node *n, ia32_emit_env_t *env) {
238         static char *buf = NULL;
239
240         /* verify that this function is never called on non-AM supporting operations */
241         assert(get_ia32_am_support(n) != ia32_am_None && "emit binop expects addressmode support");
242
243         if (! buf) {
244                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
245         }
246         else {
247                 memset(buf, 0, SNPRINTF_BUF_LEN);
248         }
249
250         switch(get_ia32_op_type(n)) {
251                 case ia32_Normal:
252                         if (get_ia32_cnst(n)) {
253                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%3S, %s", n, get_ia32_cnst(n));
254                         }
255                         else {
256                                 const arch_register_t *in1 = get_in_reg(n, 2);
257                                 const arch_register_t *in2 = get_in_reg(n, 3);
258                                 const arch_register_t *out = get_ia32_n_res(n) > 0 ? get_out_reg(n, 0) : NULL;
259                                 const arch_register_t *in;
260
261                                 in  = out ? (REGS_ARE_EQUAL(out, in2) ? in1 : in2) : in2;
262                                 out = out ? out : in1;
263
264                                 snprintf(buf, SNPRINTF_BUF_LEN, "%s, %s", \
265                                         arch_register_get_name(out), arch_register_get_name(in));
266                         }
267                         break;
268                 case ia32_AddrModeS:
269                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%4S, %s", n, ia32_emit_am(n, env));
270                         break;
271                 case ia32_AddrModeD:
272                         if (get_ia32_cnst(n)) {
273                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %s", ia32_emit_am(n, env), get_ia32_cnst(n));
274                         }
275                         else {
276                                 const arch_register_t *in1 = get_in_reg(n, 2);
277                                 const char *reg_name;
278                                 ir_mode *mode = get_ia32_res_mode(n);
279
280                                 mode = mode ? mode : get_ia32_ls_mode(n);
281
282                                 switch(get_mode_size_bits(mode)) {
283                                         case 8:
284                                                 reg_name = ia32_get_mapped_reg_name(env->isa->regs_8bit, in1);
285                                                 break;
286                                         case 16:
287                                                 reg_name = ia32_get_mapped_reg_name(env->isa->regs_16bit, in1);
288                                                 break;
289                                         case 32:
290                                                 reg_name = arch_register_get_name(in1);
291                                                 break;
292                                         default:
293                                                 assert(0 && "unsupported mode size");
294                                                 break;
295                                 }
296
297                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %s", ia32_emit_am(n, env), reg_name);
298                         }
299                         break;
300                 default:
301                         assert(0 && "unsupported op type");
302         }
303
304         return buf;
305 }
306
307 /**
308  * Emits registers and/or address mode of a unary operation.
309  */
310 char *ia32_emit_unop(const ir_node *n, ia32_emit_env_t *env) {
311         static char *buf = NULL;
312
313         if (! buf) {
314                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
315         }
316         else {
317                 memset(buf, 0, SNPRINTF_BUF_LEN);
318         }
319
320         switch(get_ia32_op_type(n)) {
321                 case ia32_Normal:
322                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
323                         break;
324                 case ia32_am_Dest:
325                         snprintf(buf, SNPRINTF_BUF_LEN, ia32_emit_am(n, env));
326                         break;
327                 default:
328                         assert(0 && "unsupported op type");
329         }
330
331         return buf;
332 }
333
334 /**
335  * Emits address mode.
336  */
337 char *ia32_emit_am(const ir_node *n, ia32_emit_env_t *env) {
338         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
339         int               had_output = 0;
340         char             *s;
341         int               size;
342         static struct obstack *obst  = NULL;
343         ir_mode *mode = get_ia32_ls_mode(n);
344
345         if (! is_ia32_Lea(n))
346                 assert(mode && "AM node must have ls_mode attribute set.");
347
348         if (! obst) {
349                 obst = xcalloc(1, sizeof(*obst));
350         }
351         else {
352                 obstack_free(obst, NULL);
353         }
354
355         /* obstack_free with NULL results in an uninitialized obstack */
356         obstack_init(obst);
357
358         if (mode) {
359                 switch (get_mode_size_bits(mode)) {
360                         case 8:
361                                 obstack_printf(obst, "BYTE PTR ");
362                                 break;
363                         case 16:
364                                 obstack_printf(obst, "WORD PTR ");
365                                 break;
366                         default:
367                                 break;
368                 }
369         }
370
371         obstack_printf(obst, "[");
372
373         if (am_flav & ia32_B) {
374                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
375                 had_output = 1;
376         }
377
378         if (am_flav & ia32_I) {
379                 if (had_output) {
380                         obstack_printf(obst, "+");
381                 }
382
383                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
384
385                 if (am_flav & ia32_S) {
386                         obstack_printf(obst, "*%d", 1 << get_ia32_am_scale(n));
387                 }
388
389                 had_output = 1;
390         }
391
392         if (am_flav & ia32_O) {
393                 obstack_printf(obst, get_ia32_am_offs(n));
394         }
395
396         obstack_printf(obst, "] ");
397
398         size        = obstack_object_size(obst);
399         s           = obstack_finish(obst);
400         s[size - 1] = '\0';
401
402         return s;
403 }
404
405
406
407 /**
408  * Formated print of commands and comments.
409  */
410 static void ia32_fprintf_format(FILE *F, char *cmd_buf, char *cmnt_buf) {
411         fprintf(F, "\t%-35s %-60s\n", cmd_buf, cmnt_buf);
412 }
413
414
415
416 /**
417  * Add a number to a prefix. This number will not be used a second time.
418  */
419 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
420         static unsigned long id = 0;
421         snprintf(buf, buflen, "%s%lu", prefix, ++id);
422         return buf;
423 }
424
425
426
427 /*************************************************
428  *                 _ _                         _
429  *                (_) |                       | |
430  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
431  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
432  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
433  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
434  *
435  *************************************************/
436
437 #undef IA32_DO_EMIT
438 #define IA32_DO_EMIT ia32_fprintf_format(F, cmd_buf, cmnt_buf)
439
440 /*
441  * coding of conditions
442  */
443 struct cmp2conditon_t {
444         const char *name;
445         pn_Cmp      num;
446 };
447
448 /*
449  * positive conditions for signed compares
450  */
451 static const struct cmp2conditon_t cmp2condition_s[] = {
452   { NULL,              pn_Cmp_False },  /* always false */
453   { "e",               pn_Cmp_Eq },     /* == */
454   { "l",               pn_Cmp_Lt },     /* < */
455   { "le",              pn_Cmp_Le },     /* <= */
456   { "g",               pn_Cmp_Gt },     /* > */
457   { "ge",              pn_Cmp_Ge },     /* >= */
458   { "ne",              pn_Cmp_Lg },     /* != */
459   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
460   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
461   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
462   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
463   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
464   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
465   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
466   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
467   { NULL,              pn_Cmp_True },   /* always true */
468 };
469
470 /*
471  * positive conditions for unsigned compares
472  */
473 static const struct cmp2conditon_t cmp2condition_u[] = {
474   { NULL,              pn_Cmp_False },  /* always false */
475   { "e",               pn_Cmp_Eq },     /* == */
476   { "b",               pn_Cmp_Lt },     /* < */
477   { "be",              pn_Cmp_Le },     /* <= */
478   { "a",               pn_Cmp_Gt },     /* > */
479   { "ae",              pn_Cmp_Ge },     /* >= */
480   { "ne",              pn_Cmp_Lg },     /* != */
481   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
482   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
483   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
484   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
485   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
486   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
487   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
488   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
489   { NULL,              pn_Cmp_True },   /* always true */
490 };
491
492 /*
493  * returns the condition code
494  */
495 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
496 {
497         assert(cmp2condition_s[cmp_code].num == cmp_code);
498         assert(cmp2condition_u[cmp_code].num == cmp_code);
499
500         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
501 }
502
503 /**
504  * Returns the target label for a control flow node.
505  */
506 static char *get_cfop_target(const ir_node *irn, char *buf) {
507         ir_node *bl = get_irn_link(irn);
508
509         snprintf(buf, SNPRINTF_BUF_LEN, "BLOCK_%ld", get_irn_node_nr(bl));
510         return buf;
511 }
512
513 /**
514  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
515  */
516 static void finish_CondJmp(FILE *F, const ir_node *irn) {
517         const ir_node   *proj;
518         const ir_edge_t *edge;
519         char buf[SNPRINTF_BUF_LEN];
520         char cmd_buf[SNPRINTF_BUF_LEN];
521         char cmnt_buf[SNPRINTF_BUF_LEN];
522
523         edge = get_irn_out_edge_first(irn);
524         proj = get_edge_src_irn(edge);
525         assert(is_Proj(proj) && "CondJmp with a non-Proj");
526
527         if (get_Proj_proj(proj) == 1) {
528                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
529                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
530                                         get_cfop_target(proj, buf));
531                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == TRUE */");
532         }
533         else  {
534                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jn%s %s",
535                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
536                                         get_cfop_target(proj, buf));
537                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == FALSE */");
538         }
539
540         IA32_DO_EMIT;
541
542         edge = get_irn_out_edge_next(irn, edge);
543         if (edge) {
544                 proj = get_edge_src_irn(edge);
545                 assert(is_Proj(proj) && "CondJmp with a non-Proj");
546                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(proj, buf));
547                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* otherwise */");
548
549                 IA32_DO_EMIT;
550         }
551 }
552
553 /**
554  * Emits code for conditional jump.
555  */
556 static void CondJmp_emitter(const ir_node *irn, ia32_emit_env_t *env) {
557         FILE *F = env->out;
558         char cmd_buf[SNPRINTF_BUF_LEN];
559         char cmnt_buf[SNPRINTF_BUF_LEN];
560
561         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cmp %s", ia32_emit_binop(irn, env));
562         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
563         IA32_DO_EMIT;
564         finish_CondJmp(F, irn);
565 }
566
567 /**
568  * Emits code for conditional jump with two variables.
569  */
570 static void emit_ia32_CondJmp(const ir_node *irn, ia32_emit_env_t *env) {
571         CondJmp_emitter(irn, env);
572 }
573
574 /**
575  * Emits code for conditional jump with immediate.
576  */
577 void emit_ia32_CondJmp_i(const ir_node *irn, ia32_emit_env_t *env) {
578         CondJmp_emitter(irn, env);
579 }
580
581
582
583 /*********************************************************
584  *                 _ _       _
585  *                (_) |     (_)
586  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
587  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
588  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
589  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
590  *                         _/ |               | |
591  *                        |__/                |_|
592  *********************************************************/
593
594 /* jump table entry (target and corresponding number) */
595 typedef struct _branch_t {
596         ir_node *target;
597         int      value;
598 } branch_t;
599
600 /* jump table for switch generation */
601 typedef struct _jmp_tbl_t {
602         ir_node  *defProj;         /**< default target */
603         int       min_value;       /**< smallest switch case */
604         int       max_value;       /**< largest switch case */
605         int       num_branches;    /**< number of jumps */
606         char     *label;           /**< label of the jump table */
607         branch_t *branches;        /**< jump array */
608 } jmp_tbl_t;
609
610 /**
611  * Compare two variables of type branch_t. Used to sort all switch cases
612  */
613 static int ia32_cmp_branch_t(const void *a, const void *b) {
614         branch_t *b1 = (branch_t *)a;
615         branch_t *b2 = (branch_t *)b;
616
617         if (b1->value <= b2->value)
618                 return -1;
619         else
620                 return 1;
621 }
622
623 /**
624  * Emits code for a SwitchJmp (creates a jump table if
625  * possible otherwise a cmp-jmp cascade). Port from
626  * cggg ia32 backend
627  */
628 void emit_ia32_SwitchJmp(const ir_node *irn, ia32_emit_env_t *emit_env) {
629         unsigned long       interval;
630         char                buf[SNPRINTF_BUF_LEN];
631         int                 last_value, i, pn, do_jmp_tbl = 1;
632         jmp_tbl_t           tbl;
633         ir_node            *proj;
634         const ir_edge_t    *edge;
635         const lc_arg_env_t *env = ia32_get_arg_env();
636         FILE               *F   = emit_env->out;
637         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
638
639         /* fill the table structure */
640         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
641         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
642         tbl.defProj      = NULL;
643         tbl.num_branches = get_irn_n_edges(irn);
644         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
645         tbl.min_value    = INT_MAX;
646         tbl.max_value    = INT_MIN;
647
648         i = 0;
649         /* go over all proj's and collect them */
650         foreach_out_edge(irn, edge) {
651                 proj = get_edge_src_irn(edge);
652                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
653
654                 pn = get_Proj_proj(proj);
655
656                 /* create branch entry */
657                 tbl.branches[i].target = proj;
658                 tbl.branches[i].value  = pn;
659
660                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
661                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
662
663                 /* check for default proj */
664                 if (pn == get_ia32_pncode(irn)) {
665                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
666                         tbl.defProj = proj;
667                 }
668
669                 i++;
670         }
671
672         /* sort the branches by their number */
673         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
674
675         /* two-complement's magic make this work without overflow */
676         interval = tbl.max_value - tbl.min_value;
677
678         /* check value interval */
679         if (interval > 16 * 1024) {
680                 do_jmp_tbl = 0;
681         }
682
683         /* check ratio of value interval to number of branches */
684         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
685                 do_jmp_tbl = 0;
686         }
687
688         if (do_jmp_tbl) {
689                 /* emit the table */
690                 if (tbl.min_value != 0) {
691                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %lu, -%d(%1S)",
692                                 interval, tbl.min_value, irn);
693                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* first switch value is not 0 */");
694
695                         IA32_DO_EMIT;
696                 }
697                 else {
698                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %lu, %1S", interval, irn);
699                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* compare for switch */");
700
701                         IA32_DO_EMIT;
702                 }
703
704                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "ja %s", get_cfop_target(tbl.defProj, buf));
705                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default jump if out of range  */");
706                 IA32_DO_EMIT;
707
708                 if (tbl.num_branches > 1) {
709                         /* create table */
710
711                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "jmp [%1S*4+%s]", irn, tbl.label);
712                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* get jump table entry as target */");
713                         IA32_DO_EMIT;
714
715                         fprintf(F, "\t.section\t.rodata\n");
716                         fprintf(F, "\t.align 4\n");
717
718                         fprintf(F, "%s:\n", tbl.label);
719
720                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[0].target, buf));
721                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */\n",  tbl.branches[0].value);
722                         IA32_DO_EMIT;
723
724                         last_value = tbl.branches[0].value;
725                         for (i = 1; i < tbl.num_branches; ++i) {
726                                 while (++last_value < tbl.branches[i].value) {
727                                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.defProj, buf));
728                                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
729                                         IA32_DO_EMIT;
730                                 }
731                                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[i].target, buf), last_value);
732                                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", last_value);
733                                 IA32_DO_EMIT;
734                         }
735
736                         fprintf(F, "\t.text");
737                 }
738                 else {
739                         /* one jump is enough */
740                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.branches[0].target, buf));
741                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* only one case given */");
742                         IA32_DO_EMIT;
743                 }
744         }
745         else { // no jump table
746                 for (i = 0; i < tbl.num_branches; ++i) {
747                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %d, %1S", tbl.branches[i].value, irn);
748                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", i);
749                         IA32_DO_EMIT;
750                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
751                 }
752
753                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.defProj, buf));
754                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
755                 IA32_DO_EMIT;
756         }
757
758         if (tbl.label)
759                 free(tbl.label);
760         if (tbl.branches)
761                 free(tbl.branches);
762 }
763
764 /**
765  * Emits code for a unconditional jump.
766  */
767 void emit_Jmp(const ir_node *irn, ia32_emit_env_t *env) {
768         FILE *F = env->out;
769         char buf[SNPRINTF_BUF_LEN], cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
770
771         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(irn, buf), get_irn_link(irn));
772         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F) */", irn, get_irn_link(irn));
773         IA32_DO_EMIT;
774 }
775
776
777
778 /****************************
779  *                  _
780  *                 (_)
781  *  _ __  _ __ ___  _  ___
782  * | '_ \| '__/ _ \| |/ __|
783  * | |_) | | | (_) | |\__ \
784  * | .__/|_|  \___/| ||___/
785  * | |            _/ |
786  * |_|           |__/
787  ****************************/
788
789 /**
790  * Emits code for a proj -> node
791  */
792 void emit_Proj(const ir_node *irn, ia32_emit_env_t *env) {
793         ir_node *pred = get_Proj_pred(irn);
794
795         if (get_irn_op(pred) == op_Start) {
796                 switch(get_Proj_proj(irn)) {
797                         case pn_Start_X_initial_exec:
798                                 emit_Jmp(irn, env);
799                                 break;
800                         default:
801                                 break;
802                 }
803         }
804 }
805
806 /**********************************
807  *   _____                  ____
808  *  / ____|                |  _ \
809  * | |     ___  _ __  _   _| |_) |
810  * | |    / _ \| '_ \| | | |  _ <
811  * | |___| (_) | |_) | |_| | |_) |
812  *  \_____\___/| .__/ \__, |____/
813  *             | |     __/ |
814  *             |_|    |___/
815  **********************************/
816
817 /**
818  * Emit movsb/w instructions to make mov count divideable by 4
819  */
820 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
821         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
822
823         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
824
825         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cld");
826         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* copy direction forward*/");
827         IA32_DO_EMIT;
828
829         switch(rem) {
830                 case 1:
831                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
832                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 1 */");
833                         break;
834                 case 2:
835                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
836                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 2 */");
837                         break;
838                 case 3:
839                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
840                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
841                         IA32_DO_EMIT;
842                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
843                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
844                         break;
845         }
846
847         IA32_DO_EMIT;
848 }
849
850 /**
851  * Emit rep movsd instruction for memcopy.
852  */
853 void emit_ia32_CopyB(const ir_node *irn, ia32_emit_env_t *emit_env) {
854         FILE   *F    = emit_env->out;
855         tarval *tv   = get_ia32_Immop_tarval(irn);
856         int     rem  = get_tarval_long(tv);
857         int     size = get_tarval_long(get_ia32_Immop_tarval(get_irn_n(irn, 2)));
858         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
859
860         emit_CopyB_prolog(F, rem, size);
861
862         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "rep movsd");
863         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy */");
864         IA32_DO_EMIT;
865 }
866
867 /**
868  * Emits unrolled memcopy.
869  */
870 void emit_ia32_CopyB_i(const ir_node *irn, ia32_emit_env_t *emit_env) {
871         tarval *tv   = get_ia32_Immop_tarval(irn);
872         int     size = get_tarval_long(tv);
873         FILE   *F    = emit_env->out;
874         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
875
876         emit_CopyB_prolog(F, size & 0x3, size);
877
878         size >>= 2;
879         while (size--) {
880                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsd");
881                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy unrolled */");
882                 IA32_DO_EMIT;
883         }
884 }
885
886
887
888 /***************************
889  *   _____
890  *  / ____|
891  * | |     ___  _ ____   __
892  * | |    / _ \| '_ \ \ / /
893  * | |___| (_) | | | \ V /
894  *  \_____\___/|_| |_|\_/
895  *
896  ***************************/
897
898 /**
899  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
900  */
901 static void emit_ia32_Conv(const ir_node *irn, ia32_emit_env_t *emit_env) {
902         FILE               *F    = emit_env->out;
903         const lc_arg_env_t *env  = ia32_get_arg_env();
904         char               *from, *to, buf[64];
905         ir_mode *src_mode, *tgt_mode;
906         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
907
908         src_mode = is_ia32_AddrModeS(irn) ? get_ia32_ls_mode(irn) : get_irn_mode(get_irn_n(irn, 2));
909         tgt_mode = get_ia32_res_mode(irn);
910
911         from = mode_is_float(src_mode) ? (get_mode_size_bits(src_mode) == 32 ? "ss" : "sd") : "si";
912         to   = mode_is_float(tgt_mode) ? (get_mode_size_bits(tgt_mode) == 32 ? "ss" : "sd") : "si";
913
914         switch(get_ia32_op_type(irn)) {
915                 case ia32_Normal:
916                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %3S", irn, irn);
917                         break;
918                 case ia32_AddrModeS:
919                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %s", irn, ia32_emit_am(irn, emit_env));
920                         break;
921                 default:
922                         assert(0 && "unsupported op type for Conv");
923         }
924
925         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cvt%s2%s %s", from, to, buf);
926         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F, %+F) */", irn, src_mode, tgt_mode);
927         IA32_DO_EMIT;
928 }
929
930 void emit_ia32_Conv_I2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
931         emit_ia32_Conv(irn, emit_env);
932 }
933
934 void emit_ia32_Conv_FP2I(const ir_node *irn, ia32_emit_env_t *emit_env) {
935         emit_ia32_Conv(irn, emit_env);
936 }
937
938 void emit_ia32_Conv_FP2FP(const ir_node *irn, ia32_emit_env_t *emit_env) {
939         emit_ia32_Conv(irn, emit_env);
940 }
941
942
943
944 /*******************************************
945  *  _                          _
946  * | |                        | |
947  * | |__   ___ _ __   ___   __| | ___  ___
948  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
949  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
950  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
951  *
952  *******************************************/
953
954 /**
955  * Emits a backend call
956  */
957 void emit_be_Call(const ir_node *irn, ia32_emit_env_t *emit_env) {
958         FILE *F = emit_env->out;
959         entity *ent = be_Call_get_entity(irn);
960         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
961
962         if (ent) {
963                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "call %s", get_entity_name(ent));
964         }
965         else {
966                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "%1D", get_irn_n(irn, be_pos_Call_ptr));
967         }
968
969         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (be_Call) */", irn);
970
971         IA32_DO_EMIT;
972 }
973
974 /**
975  * Emits code to increase stack pointer.
976  */
977 void emit_be_IncSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
978         FILE          *F    = emit_env->out;
979         unsigned       offs = be_get_IncSP_offset(irn);
980         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
981         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
982
983         if (offs) {
984                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "add %1S,%s%u", irn,
985                         (dir == be_stack_dir_along) ? " -" : " ", offs);
986                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (IncSP) */", irn);
987         }
988         else {
989                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
990                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* omitted %+F (IncSP) with 0 */", irn);
991         }
992
993         IA32_DO_EMIT;
994 }
995
996 /**
997  * Emits code to set stack pointer.
998  */
999 void emit_be_SetSP(const ir_node *irn, ia32_emit_env_t *emit_env) {
1000         FILE *F = emit_env->out;
1001         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1002
1003         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %3S", irn, irn);
1004         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (restore SP) */", irn);
1005         IA32_DO_EMIT;
1006 }
1007
1008 /**
1009  * Emits code for Copy.
1010  */
1011 void emit_be_Copy(const ir_node *irn, ia32_emit_env_t *emit_env) {
1012         FILE *F = emit_env->out;
1013         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1014
1015         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %1S", irn, irn);
1016         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
1017         IA32_DO_EMIT;
1018 }
1019
1020 /**
1021  * Emits code for exchange.
1022  */
1023 void emit_be_Perm(const ir_node *irn, ia32_emit_env_t *emit_env) {
1024         FILE *F = emit_env->out;
1025         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1026
1027         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "xchg %1S, %2S", irn, irn);
1028         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%1A, %2A) */", irn, irn, irn);
1029         IA32_DO_EMIT;
1030 }
1031
1032 /***********************************************************************************
1033  *                  _          __                                             _
1034  *                 (_)        / _|                                           | |
1035  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1036  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1037  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1038  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1039  *
1040  ***********************************************************************************/
1041
1042 /**
1043  * Enters the emitter functions for handled nodes into the generic
1044  * pointer of an opcode.
1045  */
1046 static void ia32_register_emitters(void) {
1047
1048 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
1049 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
1050 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
1051
1052         /* first clear the generic function pointer for all ops */
1053         clear_irp_opcodes_generic_func();
1054
1055         /* register all emitter functions defined in spec */
1056         ia32_register_spec_emitters();
1057
1058         /* other ia32 emitter functions */
1059         IA32_EMIT(CondJmp);
1060         IA32_EMIT(SwitchJmp);
1061         IA32_EMIT(CopyB);
1062         IA32_EMIT(CopyB_i);
1063         IA32_EMIT(Conv_I2FP);
1064         IA32_EMIT(Conv_FP2I);
1065         IA32_EMIT(Conv_FP2FP);
1066
1067         /* benode emitter */
1068         BE_EMIT(Call);
1069         BE_EMIT(IncSP);
1070         BE_EMIT(SetSP);
1071         BE_EMIT(Copy);
1072         BE_EMIT(Perm);
1073
1074         /* firm emitter */
1075         EMIT(Jmp);
1076         EMIT(Proj);
1077
1078 #undef IA32_EMIT
1079 #undef BE_EMIT
1080 #undef EMIT
1081 }
1082
1083 /**
1084  * Emits code for a node.
1085  */
1086 static void ia32_emit_node(const ir_node *irn, void *env) {
1087         ia32_emit_env_t        *emit_env = env;
1088         firm_dbg_module_t *mod      = emit_env->mod;
1089         FILE              *F        = emit_env->out;
1090         ir_op             *op       = get_irn_op(irn);
1091
1092         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
1093
1094         if (op->ops.generic) {
1095                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
1096                 (*emit)(irn, env);
1097         }
1098         else {
1099                 ir_fprintf(F, "\t%35s /* %+F */\n", " ", irn);
1100         }
1101 }
1102
1103 /**
1104  * Walks over the nodes in a block connected by scheduling edges
1105  * and emits code for each node.
1106  */
1107 static void ia32_gen_block(ir_node *block, void *env) {
1108         const ir_node *irn;
1109
1110         if (! is_Block(block))
1111                 return;
1112
1113         fprintf(((ia32_emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
1114         sched_foreach(block, irn) {
1115                 ia32_emit_node(irn, env);
1116         }
1117 }
1118
1119
1120 /**
1121  * Emits code for function start.
1122  */
1123 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
1124         const char *irg_name = get_entity_name(get_irg_entity(irg));
1125
1126         fprintf(F, "\t.text\n");
1127         fprintf(F, ".globl %s\n", irg_name);
1128         fprintf(F, "\t.type\t%s, @function\n", irg_name);
1129         fprintf(F, "%s:\n", irg_name);
1130 }
1131
1132 /**
1133  * Emits code for function end
1134  */
1135 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
1136         const char *irg_name = get_entity_name(get_irg_entity(irg));
1137
1138         fprintf(F, "\tret\n");
1139         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
1140 }
1141
1142 /**
1143  * Sets labels for control flow nodes (jump target)
1144  * TODO: Jump optimization
1145  */
1146 static void ia32_gen_labels(ir_node *block, void *env) {
1147         ir_node *pred;
1148         int n = get_Block_n_cfgpreds(block);
1149
1150         for (n--; n >= 0; n--) {
1151                 pred = get_Block_cfgpred(block, n);
1152                 set_irn_link(pred, block);
1153         }
1154 }
1155
1156 /**
1157  * Main driver. Emits the code for one routine.
1158  */
1159 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
1160         ia32_emit_env_t emit_env;
1161
1162         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
1163         emit_env.out      = F;
1164         emit_env.arch_env = cg->arch_env;
1165         emit_env.cg       = cg;
1166         emit_env.isa      = (ia32_isa_t *)cg->arch_env->isa;
1167
1168         /* set the global arch_env (needed by print hooks) */
1169         arch_env = cg->arch_env;
1170
1171         ia32_register_emitters();
1172
1173         ia32_emit_func_prolog(F, irg);
1174         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
1175         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
1176         ia32_emit_func_epilog(F, irg);
1177 }