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