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