removed dependency
[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) {
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));
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), get_ia32_cnst(n));
274                         }
275                         else {
276                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %3S", ia32_emit_am(n), n);
277                         }
278                         break;
279                 default:
280                         assert(0 && "unsupported op type");
281         }
282
283         return buf;
284 }
285
286 /**
287  * Emits registers and/or address mode of a unary operation.
288  */
289 char *ia32_emit_unop(const ir_node *n) {
290         static char *buf = NULL;
291
292         if (! buf) {
293                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
294         }
295         else {
296                 memset(buf, 0, SNPRINTF_BUF_LEN);
297         }
298
299         switch(get_ia32_op_type(n)) {
300                 case ia32_Normal:
301                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
302                         break;
303                 case ia32_am_Dest:
304                         snprintf(buf, SNPRINTF_BUF_LEN, ia32_emit_am(n));
305                         break;
306                 default:
307                         assert(0 && "unsupported op type");
308         }
309
310         return buf;
311 }
312
313 /**
314  * Emits adress mode.
315  */
316 char *ia32_emit_am(const ir_node *n) {
317         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
318         int               had_output = 0;
319         char             *s;
320         int               size;
321         static struct obstack *obst  = NULL;
322         ir_mode *mode = get_ia32_ls_mode(n);
323
324         if (! is_ia32_Lea(n))
325                 assert(mode && "AM node must have ls_mode attribute set.");
326
327         if (! obst) {
328                 obst = xcalloc(1, sizeof(*obst));
329         }
330         else {
331                 obstack_free(obst, NULL);
332         }
333
334         /* obstack_free with NULL results in an uninitialized obstack */
335         obstack_init(obst);
336
337         if (mode) {
338                 switch (get_mode_size_bits(mode)) {
339                         case 8:
340                                 obstack_printf(obst, "BYTE PTR ");
341                                 break;
342                         case 16:
343                                 obstack_printf(obst, "WORD PTR ");
344                                 break;
345                         default:
346                                 break;
347                 }
348         }
349
350         obstack_printf(obst, "[");
351
352         if (am_flav & ia32_B) {
353                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
354                 had_output = 1;
355         }
356
357         if (am_flav & ia32_I) {
358                 if (had_output) {
359                         obstack_printf(obst, "+");
360                 }
361
362                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
363
364                 if (am_flav & ia32_S) {
365                         obstack_printf(obst, "*%d", 1 << get_ia32_am_scale(n));
366                 }
367
368                 had_output = 1;
369         }
370
371         if (am_flav & ia32_O) {
372                 obstack_printf(obst, get_ia32_am_offs(n));
373         }
374
375         obstack_printf(obst, "] ");
376
377         size        = obstack_object_size(obst);
378         s           = obstack_finish(obst);
379         s[size - 1] = '\0';
380
381         return s;
382 }
383
384
385
386 /**
387  * Add a number to a prefix. This number will not be used a second time.
388  */
389 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
390         static unsigned long id = 0;
391         snprintf(buf, buflen, "%s%lu", prefix, ++id);
392         return buf;
393 }
394
395
396
397 /*************************************************
398  *                 _ _                         _
399  *                (_) |                       | |
400  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
401  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
402  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
403  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
404  *
405  *************************************************/
406
407 /*
408  * coding of conditions
409  */
410 struct cmp2conditon_t {
411         const char *name;
412         pn_Cmp      num;
413 };
414
415 /*
416  * positive conditions for signed compares
417  */
418 static const struct cmp2conditon_t cmp2condition_s[] = {
419   { NULL,              pn_Cmp_False },  /* always false */
420   { "e",               pn_Cmp_Eq },     /* == */
421   { "l",               pn_Cmp_Lt },     /* < */
422   { "le",              pn_Cmp_Le },     /* <= */
423   { "g",               pn_Cmp_Gt },     /* > */
424   { "ge",              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  * positive conditions for unsigned compares
439  */
440 static const struct cmp2conditon_t cmp2condition_u[] = {
441   { NULL,              pn_Cmp_False },  /* always false */
442   { "e",               pn_Cmp_Eq },     /* == */
443   { "b",               pn_Cmp_Lt },     /* < */
444   { "be",              pn_Cmp_Le },     /* <= */
445   { "a",               pn_Cmp_Gt },     /* > */
446   { "ae",              pn_Cmp_Ge },     /* >= */
447   { "ne",              pn_Cmp_Lg },     /* != */
448   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
449   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
450   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
451   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
452   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
453   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
454   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
455   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
456   { NULL,              pn_Cmp_True },   /* always true */
457 };
458
459 /*
460  * returns the condition code
461  */
462 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
463 {
464         assert(cmp2condition_s[cmp_code].num == cmp_code);
465         assert(cmp2condition_u[cmp_code].num == cmp_code);
466
467         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
468 }
469
470 /**
471  * Returns the target label for a control flow node.
472  */
473 static char *get_cfop_target(const ir_node *irn, char *buf) {
474         ir_node *bl = get_irn_link(irn);
475
476         snprintf(buf, SNPRINTF_BUF_LEN, "BLOCK_%ld", get_irn_node_nr(bl));
477         return buf;
478 }
479
480 /**
481  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
482  */
483 static void finish_CondJmp(FILE *F, const ir_node *irn) {
484         const ir_node   *proj;
485         const ir_edge_t *edge;
486         char buf[SNPRINTF_BUF_LEN];
487
488         edge = get_irn_out_edge_first(irn);
489         proj = get_edge_src_irn(edge);
490         assert(is_Proj(proj) && "CondJmp with a non-Proj");
491
492         if (get_Proj_proj(proj) == 1) {
493                 fprintf(F, "\tj%s %s\t\t\t/* cmp(a, b) == TRUE */\n",
494                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
495                                         get_cfop_target(proj, buf));
496         }
497         else  {
498                 fprintf(F, "\tjn%s %s\t\t\t/* cmp(a, b) == FALSE */\n",
499                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
500                                         get_cfop_target(proj, buf));
501         }
502
503         edge = get_irn_out_edge_next(irn, edge);
504         if (edge) {
505                 proj = get_edge_src_irn(edge);
506                 assert(is_Proj(proj) && "CondJmp with a non-Proj");
507                 fprintf(F, "\tjmp %s\t\t\t/* otherwise */\n", get_cfop_target(proj, buf));
508         }
509 }
510
511 /**
512  * Emits code for conditional jump with two variables.
513  */
514 static void emit_ia32_CondJmp(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(%+F, %+F) */\n",
518                 ia32_emit_binop(irn), get_irn_n(irn, 0), get_irn_n(irn, 1));
519         finish_CondJmp(F, irn);
520 }
521
522 /**
523  * Emits code for conditional jump with immediate.
524  */
525 void emit_ia32_CondJmp_i(const ir_node *irn, emit_env_t *env) {
526         FILE *F = env->out;
527
528         lc_efprintf(ia32_get_arg_env(), F, "\tcmp %s\t\t\t/* CondJmp_i(%+F) */\n",
529                 ia32_emit_binop(irn), get_irn_n(irn, 0));
530         finish_CondJmp(F, irn);
531 }
532
533
534
535 /*********************************************************
536  *                 _ _       _
537  *                (_) |     (_)
538  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
539  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
540  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
541  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
542  *                         _/ |               | |
543  *                        |__/                |_|
544  *********************************************************/
545
546 /* jump table entry (target and corresponding number) */
547 typedef struct _branch_t {
548         ir_node *target;
549         int      value;
550 } branch_t;
551
552 /* jump table for switch generation */
553 typedef struct _jmp_tbl_t {
554         ir_node  *defProj;         /**< default target */
555         int       min_value;       /**< smallest switch case */
556         int       max_value;       /**< largest switch case */
557         int       num_branches;    /**< number of jumps */
558         char     *label;           /**< label of the jump table */
559         branch_t *branches;        /**< jump array */
560 } jmp_tbl_t;
561
562 /**
563  * Compare two variables of type branch_t. Used to sort all switch cases
564  */
565 static int ia32_cmp_branch_t(const void *a, const void *b) {
566         branch_t *b1 = (branch_t *)a;
567         branch_t *b2 = (branch_t *)b;
568
569         if (b1->value <= b2->value)
570                 return -1;
571         else
572                 return 1;
573 }
574
575 /**
576  * Emits code for a SwitchJmp (creates a jump table if
577  * possible otherwise a cmp-jmp cascade). Port from
578  * cggg ia32 backend
579  */
580 void emit_ia32_SwitchJmp(const ir_node *irn, emit_env_t *emit_env) {
581         unsigned long       interval;
582         char                buf[SNPRINTF_BUF_LEN];
583         int                 last_value, i, pn, do_jmp_tbl = 1;
584         jmp_tbl_t           tbl;
585         ir_node            *proj;
586         const ir_edge_t    *edge;
587         const lc_arg_env_t *env = ia32_get_arg_env();
588         FILE               *F   = emit_env->out;
589
590         /* fill the table structure */
591         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
592         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
593         tbl.defProj      = NULL;
594         tbl.num_branches = get_irn_n_edges(irn);
595         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
596         tbl.min_value    = INT_MAX;
597         tbl.max_value    = INT_MIN;
598
599         i = 0;
600         /* go over all proj's and collect them */
601         foreach_out_edge(irn, edge) {
602                 proj = get_edge_src_irn(edge);
603                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
604
605                 pn = get_Proj_proj(proj);
606
607                 /* create branch entry */
608                 tbl.branches[i].target = proj;
609                 tbl.branches[i].value  = pn;
610
611                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
612                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
613
614                 /* check for default proj */
615                 if (pn == get_ia32_pncode(irn)) {
616                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
617                         tbl.defProj = proj;
618                 }
619
620                 i++;
621         }
622
623         /* sort the branches by their number */
624         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
625
626         /* two-complement's magic make this work without overflow */
627         interval = tbl.max_value - tbl.min_value;
628
629         /* check value interval */
630         if (interval > 16 * 1024) {
631                 do_jmp_tbl = 0;
632         }
633
634         /* check ratio of value interval to number of branches */
635         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
636                 do_jmp_tbl = 0;
637         }
638
639         if (do_jmp_tbl) {
640                 /* emit the table */
641                 if (tbl.min_value != 0) {
642                         lc_efprintf(env, F, "\tcmpl %lu, -%d(%1S)\t\t/* first switch value is not 0 */\n",
643                                 interval, tbl.min_value, irn);
644                 }
645                 else {
646                         lc_efprintf(env, F, "\tcmpl %lu, %1S\t\t\t/* compare for switch */\n", interval, irn);
647                 }
648
649                 fprintf(F, "\tja %s\t\t\t/* default jump if out of range  */\n", get_cfop_target(tbl.defProj, buf));
650
651                 if (tbl.num_branches > 1) {
652                         /* create table */
653
654                         lc_efprintf(env, F, "\tjmp [%1S*4+%s]\t\t/* get jump table entry as target */\n", irn, tbl.label);
655
656                         fprintf(F, "\t.section\t.rodata\t\t/* start jump table */\n");
657                         fprintf(F, "\t.align 4\n");
658
659                         fprintf(F, "%s:\n", tbl.label);
660                         fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[0].target, buf), tbl.branches[0].value);
661
662                         last_value = tbl.branches[0].value;
663                         for (i = 1; i < tbl.num_branches; ++i) {
664                                 while (++last_value < tbl.branches[i].value) {
665                                         fprintf(F, "\t.long %s\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
666                                 }
667                                 fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[i].target, buf), last_value);
668                         }
669
670                         fprintf(F, "\t.text\t\t\t\t/* end of jump table */\n");
671                 }
672                 else {
673                         /* one jump is enough */
674                         fprintf(F, "\tjmp %s\t\t/* only one case given */\n", get_cfop_target(tbl.branches[0].target, buf));
675                 }
676         }
677         else { // no jump table
678                 for (i = 0; i < tbl.num_branches; ++i) {
679                         lc_efprintf(env, F, "\tcmpl %d, %1S\t\t\t/* case %d */\n", tbl.branches[i].value, irn, i);
680                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
681                 }
682
683                 fprintf(F, "\tjmp %s\t\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
684         }
685
686         if (tbl.label)
687                 free(tbl.label);
688         if (tbl.branches)
689                 free(tbl.branches);
690 }
691
692 /**
693  * Emits code for a unconditional jump.
694  */
695 void emit_Jmp(const ir_node *irn, emit_env_t *env) {
696         FILE *F = env->out;
697
698         char buf[SNPRINTF_BUF_LEN];
699         ir_fprintf(F, "\tjmp %s\t\t\t/* Jmp(%+F) */\n", get_cfop_target(irn, buf), get_irn_link(irn));
700 }
701
702
703
704 /****************************
705  *                  _
706  *                 (_)
707  *  _ __  _ __ ___  _  ___
708  * | '_ \| '__/ _ \| |/ __|
709  * | |_) | | | (_) | |\__ \
710  * | .__/|_|  \___/| ||___/
711  * | |            _/ |
712  * |_|           |__/
713  ****************************/
714
715 /**
716  * Emits code for a proj -> node
717  */
718 void emit_Proj(const ir_node *irn, emit_env_t *env) {
719         ir_node *pred = get_Proj_pred(irn);
720
721         if (get_irn_op(pred) == op_Start) {
722                 switch(get_Proj_proj(irn)) {
723                         case pn_Start_X_initial_exec:
724                                 emit_Jmp(irn, env);
725                                 break;
726                         default:
727                                 break;
728                 }
729         }
730 }
731
732 /**********************************
733  *   _____                  ____
734  *  / ____|                |  _ \
735  * | |     ___  _ __  _   _| |_) |
736  * | |    / _ \| '_ \| | | |  _ <
737  * | |___| (_) | |_) | |_| | |_) |
738  *  \_____\___/| .__/ \__, |____/
739  *             | |     __/ |
740  *             |_|    |___/
741  **********************************/
742
743 /**
744  * Emit movsb/w instructions to make mov count divideable by 4
745  */
746 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
747         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
748         fprintf(F, "\tcld\t\t\t\t/* copy direction forward*/\n");
749
750         switch(rem) {
751                 case 1:
752                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 1 */\n");
753                         break;
754                 case 2:
755                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 2 */\n");
756                         break;
757                 case 3:
758                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 3 */\n");
759                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 3 */\n");
760                         break;
761         }
762 }
763
764 /**
765  * Emit rep movsd instruction for memcopy.
766  */
767 void emit_ia32_CopyB(const ir_node *irn, emit_env_t *emit_env) {
768         FILE   *F    = emit_env->out;
769         tarval *tv   = get_ia32_Immop_tarval(irn);
770         int     rem  = get_tarval_long(tv);
771         int     size = get_tarval_long(get_ia32_Immop_tarval(get_irn_n(irn, 2)));
772
773         emit_CopyB_prolog(F, rem, size);
774
775         fprintf(F, "\trep movsd\t\t\t\t/* memcopy */\n");
776 }
777
778 /**
779  * Emits unrolled memcopy.
780  */
781 void emit_ia32_CopyB_i(const ir_node *irn, emit_env_t *emit_env) {
782         tarval *tv   = get_ia32_Immop_tarval(irn);
783         int     size = get_tarval_long(tv);
784         FILE   *F    = emit_env->out;
785
786         emit_CopyB_prolog(F, size & 0x3, size);
787
788         size >>= 2;
789         while (size--) {
790                 fprintf(F, "\tmovsd\t\t\t\t/* memcopy unrolled */\n");
791         }
792 }
793
794
795
796 /***************************
797  *   _____
798  *  / ____|
799  * | |     ___  _ ____   __
800  * | |    / _ \| '_ \ \ / /
801  * | |___| (_) | | | \ V /
802  *  \_____\___/|_| |_|\_/
803  *
804  ***************************/
805
806 /**
807  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
808  */
809 static void emit_ia32_Conv(const ir_node *irn, emit_env_t *emit_env) {
810         FILE               *F    = emit_env->out;
811         const lc_arg_env_t *env  = ia32_get_arg_env();
812         char               *from, *to, buf[64];
813         ir_mode *src_mode, *tgt_mode;
814
815         src_mode = is_ia32_AddrModeS(irn) ? get_ia32_ls_mode(irn) : get_irn_mode(get_irn_n(irn, 2));
816         tgt_mode = get_ia32_res_mode(irn);
817
818         from = mode_is_float(src_mode) ? (get_mode_size_bits(src_mode) == 32 ? "ss" : "sd") : "si";
819         to   = mode_is_float(tgt_mode) ? (get_mode_size_bits(tgt_mode) == 32 ? "ss" : "sd") : "si";
820
821         switch(get_ia32_op_type(irn)) {
822                 case ia32_Normal:
823                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %3S", irn, irn);
824                         break;
825                 case ia32_AddrModeS:
826                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %s", irn, ia32_emit_am(irn));
827                         break;
828                 default:
829                         assert(0 && "unsupported op type for Conv");
830         }
831
832         lc_efprintf(env, F, "\tcvt%s2%s %s\t\t\t/* %+F(%+F, %+F) */\n", from, to, buf, irn, src_mode, tgt_mode);
833 }
834
835 void emit_ia32_Conv_I2FP(const ir_node *irn, emit_env_t *emit_env) {
836         emit_ia32_Conv(irn, emit_env);
837 }
838
839 void emit_ia32_Conv_FP2I(const ir_node *irn, emit_env_t *emit_env) {
840         emit_ia32_Conv(irn, emit_env);
841 }
842
843 void emit_ia32_Conv_FP2FP(const ir_node *irn, emit_env_t *emit_env) {
844         emit_ia32_Conv(irn, emit_env);
845 }
846
847
848
849 /*******************************************
850  *  _                          _
851  * | |                        | |
852  * | |__   ___ _ __   ___   __| | ___  ___
853  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
854  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
855  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
856  *
857  *******************************************/
858
859 /**
860  * Emits a backend call
861  */
862 void emit_be_Call(const ir_node *irn, emit_env_t *emit_env) {
863         FILE *F = emit_env->out;
864         entity *ent = be_Call_get_entity(irn);
865
866         fprintf(F, "\tcall ");
867
868         if (ent) {
869                 fprintf(F, "%s", get_entity_name(ent));
870         }
871         else {
872                 lc_efprintf(ia32_get_arg_env(), F, "%1D", get_irn_n(irn, be_pos_Call_ptr));
873         }
874
875         ir_fprintf(F, "\t\t\t/* %+F (be_Call) */\n", irn);
876 }
877
878 /**
879  * Emits code to increase stack pointer.
880  */
881 void emit_be_IncSP(const ir_node *irn, emit_env_t *emit_env) {
882         FILE          *F    = emit_env->out;
883         unsigned       offs = be_get_IncSP_offset(irn);
884         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
885
886         if (offs) {
887                 lc_efprintf(ia32_get_arg_env(), F, "\tadd %1S,%s%u\t\t\t/* %+F (IncSP) */\n", irn,
888                         (dir == be_stack_dir_along) ? " -" : " ", offs, irn);
889         }
890         else {
891                 fprintf(F, "\t\t\t\t\t/* omitted IncSP with 0 */\n");
892         }
893 }
894
895 /**
896  * Emits code to set stack pointer.
897  */
898 void emit_be_SetSP(const ir_node *irn, emit_env_t *emit_env) {
899         FILE *F = emit_env->out;
900
901         lc_efprintf(ia32_get_arg_env(), F, "\tmov %1D, %3S\t\t\t/* restore SP */\n", irn, irn);
902 }
903
904 /**
905  * Emits code for Copy.
906  */
907 void emit_be_Copy(const ir_node *irn, emit_env_t *emit_env) {
908         FILE *F = emit_env->out;
909
910         lc_efprintf(ia32_get_arg_env(), F, "\tmov %1D, %1S\t\t\t/* %+F */\n", irn, irn, irn);
911 }
912
913 /**
914  * Emits code for exchange.
915  */
916 void emit_be_Perm(const ir_node *irn, emit_env_t *emit_env) {
917         FILE *F = emit_env->out;
918
919         lc_efprintf(ia32_get_arg_env(), F, "\txchg %1S, %2S\t\t\t/* %+F(%1A, %2A) */\n", irn, irn, irn);
920 }
921
922 /***********************************************************************************
923  *                  _          __                                             _
924  *                 (_)        / _|                                           | |
925  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
926  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
927  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
928  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
929  *
930  ***********************************************************************************/
931
932 /**
933  * Enters the emitter functions for handled nodes into the generic
934  * pointer of an opcode.
935  */
936 static void ia32_register_emitters(void) {
937
938 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
939 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
940 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
941
942         /* first clear the generic function pointer for all ops */
943         clear_irp_opcodes_generic_func();
944
945         /* register all emitter functions defined in spec */
946         ia32_register_spec_emitters();
947
948         /* other ia32 emitter functions */
949         IA32_EMIT(CondJmp);
950         IA32_EMIT(SwitchJmp);
951         IA32_EMIT(CopyB);
952         IA32_EMIT(CopyB_i);
953         IA32_EMIT(Conv_I2FP);
954         IA32_EMIT(Conv_FP2I);
955         IA32_EMIT(Conv_FP2FP);
956
957         /* benode emitter */
958         BE_EMIT(Call);
959         BE_EMIT(IncSP);
960         BE_EMIT(SetSP);
961         BE_EMIT(Copy);
962         BE_EMIT(Perm);
963
964         /* firm emitter */
965         EMIT(Jmp);
966         EMIT(Proj);
967
968 #undef IA32_EMIT
969 #undef BE_EMIT
970 #undef EMIT
971 }
972
973 /**
974  * Emits code for a node.
975  */
976 static void ia32_emit_node(const ir_node *irn, void *env) {
977         emit_env_t        *emit_env = env;
978         firm_dbg_module_t *mod      = emit_env->mod;
979         FILE              *F        = emit_env->out;
980         ir_op             *op       = get_irn_op(irn);
981
982         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
983
984         if (op->ops.generic) {
985                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
986                 (*emit)(irn, env);
987         }
988
989         ir_fprintf(F, "\t\t\t\t\t/* %+F */\n", irn);
990 }
991
992 /**
993  * Walks over the nodes in a block connected by scheduling edges
994  * and emits code for each node.
995  */
996 static void ia32_gen_block(ir_node *block, void *env) {
997         const ir_node *irn;
998
999         if (! is_Block(block))
1000                 return;
1001
1002         fprintf(((emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
1003         sched_foreach(block, irn) {
1004                 ia32_emit_node(irn, env);
1005         }
1006 }
1007
1008
1009 /**
1010  * Emits code for function start.
1011  */
1012 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
1013         const char *irg_name = get_entity_name(get_irg_entity(irg));
1014
1015         fprintf(F, "\t.text\n");
1016         fprintf(F, ".globl %s\n", irg_name);
1017         fprintf(F, "\t.type\t%s, @function\n", irg_name);
1018         fprintf(F, "%s:\n", irg_name);
1019 }
1020
1021 /**
1022  * Emits code for function end
1023  */
1024 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
1025         const char *irg_name = get_entity_name(get_irg_entity(irg));
1026
1027         fprintf(F, "\tret\n");
1028         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
1029 }
1030
1031 /**
1032  * Sets labels for control flow nodes (jump target)
1033  * TODO: Jump optimization
1034  */
1035 static void ia32_gen_labels(ir_node *block, void *env) {
1036         ir_node *pred;
1037         int n = get_Block_n_cfgpreds(block);
1038
1039         for (n--; n >= 0; n--) {
1040                 pred = get_Block_cfgpred(block, n);
1041                 set_irn_link(pred, block);
1042         }
1043 }
1044
1045 /**
1046  * Main driver. Emits the code for one routine.
1047  */
1048 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
1049         emit_env_t emit_env;
1050
1051         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
1052         emit_env.out      = F;
1053         emit_env.arch_env = cg->arch_env;
1054         emit_env.cg       = cg;
1055
1056         /* set the global arch_env (needed by print hooks) */
1057         arch_env = cg->arch_env;
1058
1059         ia32_register_emitters();
1060
1061         ia32_emit_func_prolog(F, irg);
1062         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
1063         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
1064         ia32_emit_func_epilog(F, irg);
1065 }