added new dump wrapper
[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  * Formated print of commands and comments.
388  */
389 static void ia32_fprintf_format(FILE *F, char *cmd_buf, char *cmnt_buf) {
390         fprintf(F, "\t%-35s %-60s\n", cmd_buf, cmnt_buf);
391 }
392
393
394
395 /**
396  * Add a number to a prefix. This number will not be used a second time.
397  */
398 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
399         static unsigned long id = 0;
400         snprintf(buf, buflen, "%s%lu", prefix, ++id);
401         return buf;
402 }
403
404
405
406 /*************************************************
407  *                 _ _                         _
408  *                (_) |                       | |
409  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
410  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
411  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
412  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
413  *
414  *************************************************/
415
416 #undef IA32_DO_EMIT
417 #define IA32_DO_EMIT ia32_fprintf_format(F, cmd_buf, cmnt_buf)
418
419 /*
420  * coding of conditions
421  */
422 struct cmp2conditon_t {
423         const char *name;
424         pn_Cmp      num;
425 };
426
427 /*
428  * positive conditions for signed compares
429  */
430 static const struct cmp2conditon_t cmp2condition_s[] = {
431   { NULL,              pn_Cmp_False },  /* always false */
432   { "e",               pn_Cmp_Eq },     /* == */
433   { "l",               pn_Cmp_Lt },     /* < */
434   { "le",              pn_Cmp_Le },     /* <= */
435   { "g",               pn_Cmp_Gt },     /* > */
436   { "ge",              pn_Cmp_Ge },     /* >= */
437   { "ne",              pn_Cmp_Lg },     /* != */
438   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
439   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
440   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
441   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
442   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
443   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
444   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
445   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
446   { NULL,              pn_Cmp_True },   /* always true */
447 };
448
449 /*
450  * positive conditions for unsigned compares
451  */
452 static const struct cmp2conditon_t cmp2condition_u[] = {
453   { NULL,              pn_Cmp_False },  /* always false */
454   { "e",               pn_Cmp_Eq },     /* == */
455   { "b",               pn_Cmp_Lt },     /* < */
456   { "be",              pn_Cmp_Le },     /* <= */
457   { "a",               pn_Cmp_Gt },     /* > */
458   { "ae",              pn_Cmp_Ge },     /* >= */
459   { "ne",              pn_Cmp_Lg },     /* != */
460   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
461   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
462   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
463   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
464   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
465   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
466   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
467   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
468   { NULL,              pn_Cmp_True },   /* always true */
469 };
470
471 /*
472  * returns the condition code
473  */
474 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
475 {
476         assert(cmp2condition_s[cmp_code].num == cmp_code);
477         assert(cmp2condition_u[cmp_code].num == cmp_code);
478
479         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
480 }
481
482 /**
483  * Returns the target label for a control flow node.
484  */
485 static char *get_cfop_target(const ir_node *irn, char *buf) {
486         ir_node *bl = get_irn_link(irn);
487
488         snprintf(buf, SNPRINTF_BUF_LEN, "BLOCK_%ld", get_irn_node_nr(bl));
489         return buf;
490 }
491
492 /**
493  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
494  */
495 static void finish_CondJmp(FILE *F, const ir_node *irn) {
496         const ir_node   *proj;
497         const ir_edge_t *edge;
498         char buf[SNPRINTF_BUF_LEN];
499         char cmd_buf[SNPRINTF_BUF_LEN];
500         char cmnt_buf[SNPRINTF_BUF_LEN];
501
502         edge = get_irn_out_edge_first(irn);
503         proj = get_edge_src_irn(edge);
504         assert(is_Proj(proj) && "CondJmp with a non-Proj");
505
506         if (get_Proj_proj(proj) == 1) {
507                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "j%s %s",
508                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
509                                         get_cfop_target(proj, buf));
510                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == TRUE */");
511         }
512         else  {
513                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jn%s %s",
514                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
515                                         get_cfop_target(proj, buf));
516                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* cmp(a, b) == FALSE */");
517         }
518
519         IA32_DO_EMIT;
520
521         edge = get_irn_out_edge_next(irn, edge);
522         if (edge) {
523                 proj = get_edge_src_irn(edge);
524                 assert(is_Proj(proj) && "CondJmp with a non-Proj");
525                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(proj, buf));
526                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* otherwise */");
527
528                 IA32_DO_EMIT;
529         }
530 }
531
532 /**
533  * Emits code for conditional jump.
534  */
535 static void CondJmp_emitter(const ir_node *irn, emit_env_t *env) {
536         FILE *F = env->out;
537         char cmd_buf[SNPRINTF_BUF_LEN];
538         char cmnt_buf[SNPRINTF_BUF_LEN];
539
540         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cmp %s", ia32_emit_binop(irn));
541         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
542         IA32_DO_EMIT;
543         finish_CondJmp(F, irn);
544 }
545
546 /**
547  * Emits code for conditional jump with two variables.
548  */
549 static void emit_ia32_CondJmp(const ir_node *irn, emit_env_t *env) {
550         CondJmp_emitter(irn, env);
551 }
552
553 /**
554  * Emits code for conditional jump with immediate.
555  */
556 void emit_ia32_CondJmp_i(const ir_node *irn, emit_env_t *env) {
557         CondJmp_emitter(irn, env);
558 }
559
560
561
562 /*********************************************************
563  *                 _ _       _
564  *                (_) |     (_)
565  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
566  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
567  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
568  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
569  *                         _/ |               | |
570  *                        |__/                |_|
571  *********************************************************/
572
573 /* jump table entry (target and corresponding number) */
574 typedef struct _branch_t {
575         ir_node *target;
576         int      value;
577 } branch_t;
578
579 /* jump table for switch generation */
580 typedef struct _jmp_tbl_t {
581         ir_node  *defProj;         /**< default target */
582         int       min_value;       /**< smallest switch case */
583         int       max_value;       /**< largest switch case */
584         int       num_branches;    /**< number of jumps */
585         char     *label;           /**< label of the jump table */
586         branch_t *branches;        /**< jump array */
587 } jmp_tbl_t;
588
589 /**
590  * Compare two variables of type branch_t. Used to sort all switch cases
591  */
592 static int ia32_cmp_branch_t(const void *a, const void *b) {
593         branch_t *b1 = (branch_t *)a;
594         branch_t *b2 = (branch_t *)b;
595
596         if (b1->value <= b2->value)
597                 return -1;
598         else
599                 return 1;
600 }
601
602 /**
603  * Emits code for a SwitchJmp (creates a jump table if
604  * possible otherwise a cmp-jmp cascade). Port from
605  * cggg ia32 backend
606  */
607 void emit_ia32_SwitchJmp(const ir_node *irn, emit_env_t *emit_env) {
608         unsigned long       interval;
609         char                buf[SNPRINTF_BUF_LEN];
610         int                 last_value, i, pn, do_jmp_tbl = 1;
611         jmp_tbl_t           tbl;
612         ir_node            *proj;
613         const ir_edge_t    *edge;
614         const lc_arg_env_t *env = ia32_get_arg_env();
615         FILE               *F   = emit_env->out;
616         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
617
618         /* fill the table structure */
619         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
620         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
621         tbl.defProj      = NULL;
622         tbl.num_branches = get_irn_n_edges(irn);
623         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
624         tbl.min_value    = INT_MAX;
625         tbl.max_value    = INT_MIN;
626
627         i = 0;
628         /* go over all proj's and collect them */
629         foreach_out_edge(irn, edge) {
630                 proj = get_edge_src_irn(edge);
631                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
632
633                 pn = get_Proj_proj(proj);
634
635                 /* create branch entry */
636                 tbl.branches[i].target = proj;
637                 tbl.branches[i].value  = pn;
638
639                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
640                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
641
642                 /* check for default proj */
643                 if (pn == get_ia32_pncode(irn)) {
644                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
645                         tbl.defProj = proj;
646                 }
647
648                 i++;
649         }
650
651         /* sort the branches by their number */
652         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
653
654         /* two-complement's magic make this work without overflow */
655         interval = tbl.max_value - tbl.min_value;
656
657         /* check value interval */
658         if (interval > 16 * 1024) {
659                 do_jmp_tbl = 0;
660         }
661
662         /* check ratio of value interval to number of branches */
663         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
664                 do_jmp_tbl = 0;
665         }
666
667         if (do_jmp_tbl) {
668                 /* emit the table */
669                 if (tbl.min_value != 0) {
670                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %lu, -%d(%1S)",
671                                 interval, tbl.min_value, irn);
672                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* first switch value is not 0 */");
673
674                         IA32_DO_EMIT;
675                 }
676                 else {
677                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %lu, %1S", interval, irn);
678                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* compare for switch */");
679
680                         IA32_DO_EMIT;
681                 }
682
683                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "ja %s", get_cfop_target(tbl.defProj, buf));
684                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default jump if out of range  */");
685                 IA32_DO_EMIT;
686
687                 if (tbl.num_branches > 1) {
688                         /* create table */
689
690                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "jmp [%1S*4+%s]", irn, tbl.label);
691                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* get jump table entry as target */");
692                         IA32_DO_EMIT;
693
694                         fprintf(F, "\t.section\t.rodata\n");
695                         fprintf(F, "\t.align 4\n");
696
697                         fprintf(F, "%s:\n", tbl.label);
698
699                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[0].target, buf));
700                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */\n",  tbl.branches[0].value);
701                         IA32_DO_EMIT;
702
703                         last_value = tbl.branches[0].value;
704                         for (i = 1; i < tbl.num_branches; ++i) {
705                                 while (++last_value < tbl.branches[i].value) {
706                                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.defProj, buf));
707                                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
708                                         IA32_DO_EMIT;
709                                 }
710                                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, ".long %s", get_cfop_target(tbl.branches[i].target, buf), last_value);
711                                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", last_value);
712                                 IA32_DO_EMIT;
713                         }
714
715                         fprintf(F, "\t.text");
716                 }
717                 else {
718                         /* one jump is enough */
719                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.branches[0].target, buf));
720                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* only one case given */");
721                         IA32_DO_EMIT;
722                 }
723         }
724         else { // no jump table
725                 for (i = 0; i < tbl.num_branches; ++i) {
726                         lc_esnprintf(env, cmd_buf, SNPRINTF_BUF_LEN, "cmpl %d, %1S", tbl.branches[i].value, irn);
727                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* case %d */", i);
728                         IA32_DO_EMIT;
729                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
730                 }
731
732                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(tbl.defProj, buf));
733                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* default case */");
734                 IA32_DO_EMIT;
735         }
736
737         if (tbl.label)
738                 free(tbl.label);
739         if (tbl.branches)
740                 free(tbl.branches);
741 }
742
743 /**
744  * Emits code for a unconditional jump.
745  */
746 void emit_Jmp(const ir_node *irn, emit_env_t *env) {
747         FILE *F = env->out;
748         char buf[SNPRINTF_BUF_LEN], cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
749
750         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "jmp %s", get_cfop_target(irn, buf), get_irn_link(irn));
751         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F) */", irn, get_irn_link(irn));
752         IA32_DO_EMIT;
753 }
754
755
756
757 /****************************
758  *                  _
759  *                 (_)
760  *  _ __  _ __ ___  _  ___
761  * | '_ \| '__/ _ \| |/ __|
762  * | |_) | | | (_) | |\__ \
763  * | .__/|_|  \___/| ||___/
764  * | |            _/ |
765  * |_|           |__/
766  ****************************/
767
768 /**
769  * Emits code for a proj -> node
770  */
771 void emit_Proj(const ir_node *irn, emit_env_t *env) {
772         ir_node *pred = get_Proj_pred(irn);
773
774         if (get_irn_op(pred) == op_Start) {
775                 switch(get_Proj_proj(irn)) {
776                         case pn_Start_X_initial_exec:
777                                 emit_Jmp(irn, env);
778                                 break;
779                         default:
780                                 break;
781                 }
782         }
783 }
784
785 /**********************************
786  *   _____                  ____
787  *  / ____|                |  _ \
788  * | |     ___  _ __  _   _| |_) |
789  * | |    / _ \| '_ \| | | |  _ <
790  * | |___| (_) | |_) | |_| | |_) |
791  *  \_____\___/| .__/ \__, |____/
792  *             | |     __/ |
793  *             |_|    |___/
794  **********************************/
795
796 /**
797  * Emit movsb/w instructions to make mov count divideable by 4
798  */
799 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
800         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
801
802         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
803
804         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cld");
805         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* copy direction forward*/");
806         IA32_DO_EMIT;
807
808         switch(rem) {
809                 case 1:
810                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
811                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 1 */");
812                         break;
813                 case 2:
814                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
815                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 2 */");
816                         break;
817                 case 3:
818                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsb");
819                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
820                         IA32_DO_EMIT;
821                         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsw");
822                         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy remainder 3 */");
823                         break;
824         }
825
826         IA32_DO_EMIT;
827 }
828
829 /**
830  * Emit rep movsd instruction for memcopy.
831  */
832 void emit_ia32_CopyB(const ir_node *irn, emit_env_t *emit_env) {
833         FILE   *F    = emit_env->out;
834         tarval *tv   = get_ia32_Immop_tarval(irn);
835         int     rem  = get_tarval_long(tv);
836         int     size = get_tarval_long(get_ia32_Immop_tarval(get_irn_n(irn, 2)));
837         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
838
839         emit_CopyB_prolog(F, rem, size);
840
841         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "rep movsd");
842         snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy */");
843         IA32_DO_EMIT;
844 }
845
846 /**
847  * Emits unrolled memcopy.
848  */
849 void emit_ia32_CopyB_i(const ir_node *irn, emit_env_t *emit_env) {
850         tarval *tv   = get_ia32_Immop_tarval(irn);
851         int     size = get_tarval_long(tv);
852         FILE   *F    = emit_env->out;
853         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
854
855         emit_CopyB_prolog(F, size & 0x3, size);
856
857         size >>= 2;
858         while (size--) {
859                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "movsd");
860                 snprintf(cmnt_buf, SNPRINTF_BUF_LEN, "/* memcopy unrolled */");
861                 IA32_DO_EMIT;
862         }
863 }
864
865
866
867 /***************************
868  *   _____
869  *  / ____|
870  * | |     ___  _ ____   __
871  * | |    / _ \| '_ \ \ / /
872  * | |___| (_) | | | \ V /
873  *  \_____\___/|_| |_|\_/
874  *
875  ***************************/
876
877 /**
878  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
879  */
880 static void emit_ia32_Conv(const ir_node *irn, emit_env_t *emit_env) {
881         FILE               *F    = emit_env->out;
882         const lc_arg_env_t *env  = ia32_get_arg_env();
883         char               *from, *to, buf[64];
884         ir_mode *src_mode, *tgt_mode;
885         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
886
887         src_mode = is_ia32_AddrModeS(irn) ? get_ia32_ls_mode(irn) : get_irn_mode(get_irn_n(irn, 2));
888         tgt_mode = get_ia32_res_mode(irn);
889
890         from = mode_is_float(src_mode) ? (get_mode_size_bits(src_mode) == 32 ? "ss" : "sd") : "si";
891         to   = mode_is_float(tgt_mode) ? (get_mode_size_bits(tgt_mode) == 32 ? "ss" : "sd") : "si";
892
893         switch(get_ia32_op_type(irn)) {
894                 case ia32_Normal:
895                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %3S", irn, irn);
896                         break;
897                 case ia32_AddrModeS:
898                         lc_esnprintf(env, buf, sizeof(buf), "%1D, %s", irn, ia32_emit_am(irn));
899                         break;
900                 default:
901                         assert(0 && "unsupported op type for Conv");
902         }
903
904         snprintf(cmd_buf, SNPRINTF_BUF_LEN, "cvt%s2%s %s", from, to, buf);
905         lc_esnprintf(env, cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%+F, %+F) */", irn, src_mode, tgt_mode);
906         IA32_DO_EMIT;
907 }
908
909 void emit_ia32_Conv_I2FP(const ir_node *irn, emit_env_t *emit_env) {
910         emit_ia32_Conv(irn, emit_env);
911 }
912
913 void emit_ia32_Conv_FP2I(const ir_node *irn, emit_env_t *emit_env) {
914         emit_ia32_Conv(irn, emit_env);
915 }
916
917 void emit_ia32_Conv_FP2FP(const ir_node *irn, emit_env_t *emit_env) {
918         emit_ia32_Conv(irn, emit_env);
919 }
920
921
922
923 /*******************************************
924  *  _                          _
925  * | |                        | |
926  * | |__   ___ _ __   ___   __| | ___  ___
927  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
928  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
929  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
930  *
931  *******************************************/
932
933 /**
934  * Emits a backend call
935  */
936 void emit_be_Call(const ir_node *irn, emit_env_t *emit_env) {
937         FILE *F = emit_env->out;
938         entity *ent = be_Call_get_entity(irn);
939         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
940
941         if (ent) {
942                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, "call %s", get_entity_name(ent));
943         }
944         else {
945                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "%1D", get_irn_n(irn, be_pos_Call_ptr));
946         }
947
948         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (be_Call) */", irn);
949
950         IA32_DO_EMIT;
951 }
952
953 /**
954  * Emits code to increase stack pointer.
955  */
956 void emit_be_IncSP(const ir_node *irn, emit_env_t *emit_env) {
957         FILE          *F    = emit_env->out;
958         unsigned       offs = be_get_IncSP_offset(irn);
959         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
960         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
961
962         if (offs) {
963                 lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "add %1S,%s%u", irn,
964                         (dir == be_stack_dir_along) ? " -" : " ", offs);
965                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (IncSP) */", irn);
966         }
967         else {
968                 snprintf(cmd_buf, SNPRINTF_BUF_LEN, " ");
969                 lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* omitted %+F (IncSP) with 0 */", irn);
970         }
971
972         IA32_DO_EMIT;
973 }
974
975 /**
976  * Emits code to set stack pointer.
977  */
978 void emit_be_SetSP(const ir_node *irn, emit_env_t *emit_env) {
979         FILE *F = emit_env->out;
980         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
981
982         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %3S", irn, irn);
983         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F (restore SP) */", irn);
984         IA32_DO_EMIT;
985 }
986
987 /**
988  * Emits code for Copy.
989  */
990 void emit_be_Copy(const ir_node *irn, emit_env_t *emit_env) {
991         FILE *F = emit_env->out;
992         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
993
994         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "mov %1D, %1S", irn, irn);
995         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F */", irn);
996         IA32_DO_EMIT;
997 }
998
999 /**
1000  * Emits code for exchange.
1001  */
1002 void emit_be_Perm(const ir_node *irn, emit_env_t *emit_env) {
1003         FILE *F = emit_env->out;
1004         char cmd_buf[SNPRINTF_BUF_LEN], cmnt_buf[SNPRINTF_BUF_LEN];
1005
1006         lc_esnprintf(ia32_get_arg_env(), cmd_buf, SNPRINTF_BUF_LEN, "xchg %1S, %2S", irn, irn);
1007         lc_esnprintf(ia32_get_arg_env(), cmnt_buf, SNPRINTF_BUF_LEN, "/* %+F(%1A, %2A) */", irn, irn, irn);
1008         IA32_DO_EMIT;
1009 }
1010
1011 /***********************************************************************************
1012  *                  _          __                                             _
1013  *                 (_)        / _|                                           | |
1014  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1015  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1016  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1017  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1018  *
1019  ***********************************************************************************/
1020
1021 /**
1022  * Enters the emitter functions for handled nodes into the generic
1023  * pointer of an opcode.
1024  */
1025 static void ia32_register_emitters(void) {
1026
1027 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
1028 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
1029 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
1030
1031         /* first clear the generic function pointer for all ops */
1032         clear_irp_opcodes_generic_func();
1033
1034         /* register all emitter functions defined in spec */
1035         ia32_register_spec_emitters();
1036
1037         /* other ia32 emitter functions */
1038         IA32_EMIT(CondJmp);
1039         IA32_EMIT(SwitchJmp);
1040         IA32_EMIT(CopyB);
1041         IA32_EMIT(CopyB_i);
1042         IA32_EMIT(Conv_I2FP);
1043         IA32_EMIT(Conv_FP2I);
1044         IA32_EMIT(Conv_FP2FP);
1045
1046         /* benode emitter */
1047         BE_EMIT(Call);
1048         BE_EMIT(IncSP);
1049         BE_EMIT(SetSP);
1050         BE_EMIT(Copy);
1051         BE_EMIT(Perm);
1052
1053         /* firm emitter */
1054         EMIT(Jmp);
1055         EMIT(Proj);
1056
1057 #undef IA32_EMIT
1058 #undef BE_EMIT
1059 #undef EMIT
1060 }
1061
1062 /**
1063  * Emits code for a node.
1064  */
1065 static void ia32_emit_node(const ir_node *irn, void *env) {
1066         emit_env_t        *emit_env = env;
1067         firm_dbg_module_t *mod      = emit_env->mod;
1068         FILE              *F        = emit_env->out;
1069         ir_op             *op       = get_irn_op(irn);
1070
1071         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
1072
1073         if (op->ops.generic) {
1074                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
1075                 (*emit)(irn, env);
1076         }
1077         else {
1078                 ir_fprintf(F, "\t%35s /* %+F */\n", " ", irn);
1079         }
1080 }
1081
1082 /**
1083  * Walks over the nodes in a block connected by scheduling edges
1084  * and emits code for each node.
1085  */
1086 static void ia32_gen_block(ir_node *block, void *env) {
1087         const ir_node *irn;
1088
1089         if (! is_Block(block))
1090                 return;
1091
1092         fprintf(((emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
1093         sched_foreach(block, irn) {
1094                 ia32_emit_node(irn, env);
1095         }
1096 }
1097
1098
1099 /**
1100  * Emits code for function start.
1101  */
1102 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
1103         const char *irg_name = get_entity_name(get_irg_entity(irg));
1104
1105         fprintf(F, "\t.text\n");
1106         fprintf(F, ".globl %s\n", irg_name);
1107         fprintf(F, "\t.type\t%s, @function\n", irg_name);
1108         fprintf(F, "%s:\n", irg_name);
1109 }
1110
1111 /**
1112  * Emits code for function end
1113  */
1114 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
1115         const char *irg_name = get_entity_name(get_irg_entity(irg));
1116
1117         fprintf(F, "\tret\n");
1118         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
1119 }
1120
1121 /**
1122  * Sets labels for control flow nodes (jump target)
1123  * TODO: Jump optimization
1124  */
1125 static void ia32_gen_labels(ir_node *block, void *env) {
1126         ir_node *pred;
1127         int n = get_Block_n_cfgpreds(block);
1128
1129         for (n--; n >= 0; n--) {
1130                 pred = get_Block_cfgpred(block, n);
1131                 set_irn_link(pred, block);
1132         }
1133 }
1134
1135 /**
1136  * Main driver. Emits the code for one routine.
1137  */
1138 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
1139         emit_env_t emit_env;
1140
1141         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
1142         emit_env.out      = F;
1143         emit_env.arch_env = cg->arch_env;
1144         emit_env.cg       = cg;
1145
1146         /* set the global arch_env (needed by print hooks) */
1147         arch_env = cg->arch_env;
1148
1149         ia32_register_emitters();
1150
1151         ia32_emit_func_prolog(F, irg);
1152         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
1153         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
1154         ia32_emit_func_epilog(F, irg);
1155 }