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