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