fixed several bugs
[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 /**
238  * Returns the number of the in register at position pos.
239  */
240 int get_ia32_reg_nr(ir_node *irn, int pos, int in_out) {
241         const arch_register_t *reg;
242
243         if (in_out == 1) {
244                 reg = get_in_reg(irn, pos);
245         }
246         else {
247                 reg = get_out_reg(irn, pos);
248         }
249
250         return arch_register_get_index(reg);
251 }
252
253 enum io_direction {
254   IN_REG,
255   OUT_REG
256 };
257
258 /**
259  * Returns the name of the in register at position pos.
260  */
261 static const char *get_ia32_reg_name(ir_node *irn, int pos, enum io_direction in_out) {
262         const arch_register_t *reg;
263
264         if (in_out == IN_REG) {
265                 reg = get_in_reg(irn, pos);
266         }
267         else {
268                 /* destination address mode nodes don't have outputs */
269                 if (get_ia32_op_type(irn) == ia32_AddrModeD) {
270                         return "MEM";
271                 }
272
273                 reg = get_out_reg(irn, pos);
274         }
275
276         return arch_register_get_name(reg);
277 }
278
279 /**
280  * Get the register name for a node.
281  */
282 static int ia32_get_reg_name(lc_appendable_t *app,
283     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
284 {
285         const char *buf;
286         ir_node    *X  = arg->v_ptr;
287         int         nr = occ->width - 1;
288
289         if (!X)
290                 return lc_arg_append(app, occ, "(null)", 6);
291
292         buf = get_ia32_reg_name(X, nr, occ->conversion == 'S' ? IN_REG : OUT_REG);
293
294         return lc_arg_append(app, occ, buf, strlen(buf));
295 }
296
297 /**
298  * Returns the tarval, offset or scale of an ia32 as a string.
299  */
300 static int ia32_const_to_str(lc_appendable_t *app,
301     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
302 {
303         const char *buf;
304         ir_node    *X = arg->v_ptr;
305
306         if (!X)
307                 return lc_arg_append(app, occ, "(null)", 6);
308
309         if (occ->conversion == 'C') {
310                 buf = get_ia32_cnst(X);
311         }
312         else { /* 'O' */
313                 buf = get_ia32_am_offs(X);
314         }
315
316         return buf ? lc_arg_append(app, occ, buf, strlen(buf)) : 0;
317 }
318
319 /**
320  * Determines the SSE suffix depending on the mode.
321  */
322 static int ia32_get_mode_suffix(lc_appendable_t *app,
323     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
324 {
325         ir_node *X = arg->v_ptr;
326
327         if (!X)
328                 return lc_arg_append(app, occ, "(null)", 6);
329
330         return lc_appendable_chadd(app, get_mode_size_bits(get_irn_mode(X)) == 32 ? 's' : 'd');
331 }
332
333 /**
334  * Return the ia32 printf arg environment.
335  * We use the firm environment with some additional handlers.
336  */
337 const lc_arg_env_t *ia32_get_arg_env(void) {
338         static lc_arg_env_t *env = NULL;
339
340         static const lc_arg_handler_t ia32_reg_handler   = { ia32_get_arg_type, ia32_get_reg_name };
341         static const lc_arg_handler_t ia32_const_handler = { ia32_get_arg_type, ia32_const_to_str };
342         static const lc_arg_handler_t ia32_mode_handler  = { ia32_get_arg_type, ia32_get_mode_suffix };
343
344         if(env == NULL) {
345                 /* extend the firm printer */
346                 env = firm_get_arg_env();
347
348                 lc_arg_register(env, "ia32:sreg", 'S', &ia32_reg_handler);
349                 lc_arg_register(env, "ia32:dreg", 'D', &ia32_reg_handler);
350                 lc_arg_register(env, "ia32:cnst", 'C', &ia32_const_handler);
351                 lc_arg_register(env, "ia32:offs", 'O', &ia32_const_handler);
352                 lc_arg_register(env, "ia32:mode", 'M', &ia32_mode_handler);
353         }
354
355         return env;
356 }
357
358
359 /*
360  * Add a number to a prefix. This number will not be used a second time.
361  */
362 static char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
363         static unsigned long id = 0;
364         snprintf(buf, buflen, "%s%lu", prefix, ++id);
365         return buf;
366 }
367
368
369 /*************************************************
370  *                 _ _                         _
371  *                (_) |                       | |
372  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
373  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
374  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
375  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
376  *
377  *************************************************/
378
379 /*
380  * coding of conditions
381  */
382 struct cmp2conditon_t {
383         const char *name;
384         pn_Cmp      num;
385 };
386
387 /*
388  * positive conditions for signed compares
389  */
390 static const struct cmp2conditon_t cmp2condition_s[] = {
391   { NULL,              pn_Cmp_False },  /* always false */
392   { "e",               pn_Cmp_Eq },     /* == */
393   { "l",               pn_Cmp_Lt },     /* < */
394   { "le",              pn_Cmp_Le },     /* <= */
395   { "g",               pn_Cmp_Gt },     /* > */
396   { "ge",              pn_Cmp_Ge },     /* >= */
397   { "ne",              pn_Cmp_Lg },     /* != */
398   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
399   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
400   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
401   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
402   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
403   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
404   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
405   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
406   { NULL,              pn_Cmp_True },   /* always true */
407 };
408
409 /*
410  * positive conditions for unsigned compares
411  */
412 static const struct cmp2conditon_t cmp2condition_u[] = {
413   { NULL,              pn_Cmp_False },  /* always false */
414   { "e",               pn_Cmp_Eq },     /* == */
415   { "b",               pn_Cmp_Lt },     /* < */
416   { "be",              pn_Cmp_Le },     /* <= */
417   { "a",               pn_Cmp_Gt },     /* > */
418   { "ae",              pn_Cmp_Ge },     /* >= */
419   { "ne",              pn_Cmp_Lg },     /* != */
420   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
421   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
422   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
423   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
424   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
425   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
426   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
427   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
428   { NULL,              pn_Cmp_True },   /* always true */
429 };
430
431 /*
432  * returns the condition code
433  */
434 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
435 {
436         assert(cmp2condition_s[cmp_code].num == cmp_code);
437         assert(cmp2condition_u[cmp_code].num == cmp_code);
438
439         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
440 }
441
442 /**
443  * Returns the target label for a control flow node.
444  */
445 static char *get_cfop_target(const ir_node *irn, char *buf) {
446         ir_node *bl = get_irn_link(irn);
447
448         snprintf(buf, SNPRINTF_BUF_LEN, "BLOCK_%ld", get_irn_node_nr(bl));
449         return buf;
450 }
451
452 /**
453  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
454  */
455 static void finish_CondJmp(FILE *F, const ir_node *irn) {
456         const ir_node   *proj;
457         const ir_edge_t *edge;
458         char buf[SNPRINTF_BUF_LEN];
459
460         edge = get_irn_out_edge_first(irn);
461         proj = get_edge_src_irn(edge);
462         assert(is_Proj(proj) && "CondJmp with a non-Proj");
463
464         if (get_Proj_proj(proj) == 1) {
465                 fprintf(F, "\tj%s %s\t\t\t/* cmp(a, b) == TRUE */\n",
466                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
467                                         get_cfop_target(proj, buf));
468         }
469         else  {
470                 fprintf(F, "\tjn%s %s\t\t\t/* cmp(a, b) == FALSE */\n",
471                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
472                                         get_cfop_target(proj, buf));
473         }
474
475         edge = get_irn_out_edge_next(irn, edge);
476         if (edge) {
477                 proj = get_edge_src_irn(edge);
478                 assert(is_Proj(proj) && "CondJmp with a non-Proj");
479                 fprintf(F, "\tjmp %s\t\t\t/* otherwise */\n", get_cfop_target(proj, buf));
480         }
481 }
482
483 /**
484  * Emits code for conditional jump with two variables.
485  */
486 static void emit_ia32_CondJmp(const ir_node *irn, emit_env_t *env) {
487         FILE *F = env->out;
488
489         lc_efprintf(ia32_get_arg_env(), F, "\tcmp %s\t\t\t/* CondJmp(%+F, %+F) */\n",
490                 ia32_emit_binop(irn), get_irn_n(irn, 0), get_irn_n(irn, 1));
491         finish_CondJmp(F, irn);
492 }
493
494 /**
495  * Emits code for conditional jump with immediate.
496  */
497 void emit_ia32_CondJmp_i(const ir_node *irn, emit_env_t *env) {
498         FILE *F = env->out;
499
500         lc_efprintf(ia32_get_arg_env(), F, "\tcmp %s\t\t\t/* CondJmp_i(%+F) */\n",
501                 ia32_emit_binop(irn), get_irn_n(irn, 0));
502         finish_CondJmp(F, irn);
503 }
504
505
506
507 /*********************************************************
508  *                 _ _       _
509  *                (_) |     (_)
510  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
511  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
512  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
513  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
514  *                         _/ |               | |
515  *                        |__/                |_|
516  *********************************************************/
517
518 /* jump table entry (target and corresponding number) */
519 typedef struct _branch_t {
520         ir_node *target;
521         int      value;
522 } branch_t;
523
524 /* jump table for switch generation */
525 typedef struct _jmp_tbl_t {
526         ir_node  *defProj;         /**< default target */
527         int       min_value;       /**< smallest switch case */
528         int       max_value;       /**< largest switch case */
529         int       num_branches;    /**< number of jumps */
530         char     *label;           /**< label of the jump table */
531         branch_t *branches;        /**< jump array */
532 } jmp_tbl_t;
533
534 /**
535  * Compare two variables of type branch_t. Used to sort all switch cases
536  */
537 static int ia32_cmp_branch_t(const void *a, const void *b) {
538         branch_t *b1 = (branch_t *)a;
539         branch_t *b2 = (branch_t *)b;
540
541         if (b1->value <= b2->value)
542                 return -1;
543         else
544                 return 1;
545 }
546
547 /**
548  * Emits code for a SwitchJmp (creates a jump table if
549  * possible otherwise a cmp-jmp cascade). Port from
550  * cggg ia32 backend
551  */
552 void emit_ia32_SwitchJmp(const ir_node *irn, emit_env_t *emit_env) {
553         unsigned long       interval;
554         char                buf[SNPRINTF_BUF_LEN];
555         int                 last_value, i, pn, do_jmp_tbl = 1;
556         jmp_tbl_t           tbl;
557         ir_node            *proj;
558         const ir_edge_t    *edge;
559         const lc_arg_env_t *env = ia32_get_arg_env();
560         FILE               *F   = emit_env->out;
561
562         /* fill the table structure */
563         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
564         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
565         tbl.defProj      = NULL;
566         tbl.num_branches = get_irn_n_edges(irn);
567         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
568         tbl.min_value    = INT_MAX;
569         tbl.max_value    = INT_MIN;
570
571         i = 0;
572         /* go over all proj's and collect them */
573         foreach_out_edge(irn, edge) {
574                 proj = get_edge_src_irn(edge);
575                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
576
577                 pn = get_Proj_proj(proj);
578
579                 /* create branch entry */
580                 tbl.branches[i].target = proj;
581                 tbl.branches[i].value  = pn;
582
583                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
584                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
585
586                 /* check for default proj */
587                 if (pn == get_ia32_pncode(irn)) {
588                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
589                         tbl.defProj = proj;
590                 }
591
592                 i++;
593         }
594
595         /* sort the branches by their number */
596         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
597
598         /* two-complement's magic make this work without overflow */
599         interval = tbl.max_value - tbl.min_value;
600
601         /* check value interval */
602         if (interval > 16 * 1024) {
603                 do_jmp_tbl = 0;
604         }
605
606         /* check ratio of value interval to number of branches */
607         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
608                 do_jmp_tbl = 0;
609         }
610
611         if (do_jmp_tbl) {
612                 /* emit the table */
613                 if (tbl.min_value != 0) {
614                         lc_efprintf(env, F, "\tcmpl %lu, -%d(%1S)\t\t/* first switch value is not 0 */\n",
615                                 interval, tbl.min_value, irn);
616                 }
617                 else {
618                         lc_efprintf(env, F, "\tcmpl %lu, %1S\t\t\t/* compare for switch */\n", interval, irn);
619                 }
620
621                 fprintf(F, "\tja %s\t\t\t/* default jump if out of range  */\n", get_cfop_target(tbl.defProj, buf));
622
623                 if (tbl.num_branches > 1) {
624                         /* create table */
625
626                         lc_efprintf(env, F, "\tjmp [%1S*4+%s]\t\t/* get jump table entry as target */\n", irn, tbl.label);
627
628                         fprintf(F, "\t.section\t.rodata\t\t/* start jump table */\n");
629                         fprintf(F, "\t.align 4\n");
630
631                         fprintf(F, "%s:\n", tbl.label);
632                         fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[0].target, buf), tbl.branches[0].value);
633
634                         last_value = tbl.branches[0].value;
635                         for (i = 1; i < tbl.num_branches; ++i) {
636                                 while (++last_value < tbl.branches[i].value) {
637                                         fprintf(F, "\t.long %s\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
638                                 }
639                                 fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[i].target, buf), last_value);
640                         }
641
642                         fprintf(F, "\t.text\t\t\t\t/* end of jump table */\n");
643                 }
644                 else {
645                         /* one jump is enough */
646                         fprintf(F, "\tjmp %s\t\t/* only one case given */\n", get_cfop_target(tbl.branches[0].target, buf));
647                 }
648         }
649         else { // no jump table
650                 for (i = 0; i < tbl.num_branches; ++i) {
651                         lc_efprintf(env, F, "\tcmpl %d, %1S\t\t\t/* case %d */\n", tbl.branches[i].value, irn, i);
652                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
653                 }
654
655                 fprintf(F, "\tjmp %s\t\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
656         }
657
658         if (tbl.label)
659                 free(tbl.label);
660         if (tbl.branches)
661                 free(tbl.branches);
662 }
663
664 /**
665  * Emits code for a unconditional jump.
666  */
667 void emit_Jmp(const ir_node *irn, emit_env_t *env) {
668         FILE *F = env->out;
669
670         char buf[SNPRINTF_BUF_LEN];
671         ir_fprintf(F, "\tjmp %s\t\t\t/* Jmp(%+F) */\n", get_cfop_target(irn, buf), get_irn_link(irn));
672 }
673
674
675
676 /****************************
677  *                  _
678  *                 (_)
679  *  _ __  _ __ ___  _  ___
680  * | '_ \| '__/ _ \| |/ __|
681  * | |_) | | | (_) | |\__ \
682  * | .__/|_|  \___/| ||___/
683  * | |            _/ |
684  * |_|           |__/
685  ****************************/
686
687 /**
688  * Emits code for a proj -> node
689  */
690 void emit_Proj(const ir_node *irn, emit_env_t *env) {
691         ir_node *pred = get_Proj_pred(irn);
692
693         if (get_irn_op(pred) == op_Start) {
694                 switch(get_Proj_proj(irn)) {
695                         case pn_Start_X_initial_exec:
696                                 emit_Jmp(irn, env);
697                                 break;
698                         default:
699                                 break;
700                 }
701         }
702 }
703
704 /**********************************
705  *   _____                  ____
706  *  / ____|                |  _ \
707  * | |     ___  _ __  _   _| |_) |
708  * | |    / _ \| '_ \| | | |  _ <
709  * | |___| (_) | |_) | |_| | |_) |
710  *  \_____\___/| .__/ \__, |____/
711  *             | |     __/ |
712  *             |_|    |___/
713  **********************************/
714
715 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
716         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
717         fprintf(F, "\tcld\t\t\t\t/* copy direction forward*/\n");
718
719         switch(rem) {
720                 case 1:
721                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 1 */\n");
722                         break;
723                 case 2:
724                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 2 */\n");
725                         break;
726                 case 3:
727                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 3 */\n");
728                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 3 */\n");
729                         break;
730         }
731 }
732
733 void emit_ia32_CopyB(const ir_node *irn, emit_env_t *emit_env) {
734         FILE   *F    = emit_env->out;
735         tarval *tv   = get_ia32_Immop_tarval(irn);
736         int     rem  = get_tarval_long(tv);
737         int     size = get_tarval_long(get_ia32_Immop_tarval(get_irn_n(irn, 2)));
738
739         emit_CopyB_prolog(F, rem, size);
740
741         fprintf(F, "\trep movsd\t\t\t\t/* memcopy */\n");
742 }
743
744 void emit_ia32_CopyB_i(const ir_node *irn, emit_env_t *emit_env) {
745         tarval *tv   = get_ia32_Immop_tarval(irn);
746         int     size = get_tarval_long(tv);
747         FILE   *F    = emit_env->out;
748
749         emit_CopyB_prolog(F, size & 0x3, size);
750
751         size >>= 2;
752         while (size--) {
753                 fprintf(F, "\tmovsd\t\t\t\t/* memcopy unrolled */\n");
754         }
755 }
756
757
758
759 /*******************************************
760  *  _                          _
761  * | |                        | |
762  * | |__   ___ _ __   ___   __| | ___  ___
763  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
764  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
765  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
766  *
767  *******************************************/
768
769 void emit_be_Call(const ir_node *irn, emit_env_t *emit_env) {
770         FILE *F = emit_env->out;
771
772         lc_efprintf(ia32_get_arg_env(), F, "\tcall %3S\t\t\t/* %+F(%+F) (be_Call) */\n", irn, irn, get_irn_n(irn, 2));
773 }
774
775 void emit_be_IncSP(const ir_node *irn, emit_env_t *emit_env) {
776         FILE          *F    = emit_env->out;
777         unsigned       offs = be_get_IncSP_offset(irn);
778         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
779
780         if (offs) {
781                 lc_efprintf(ia32_get_arg_env(), F, "\tadd %1S,%s%u\t\t\t/* %+F (IncSP) */\n", irn,
782                         (dir == be_stack_dir_along) ? " -" : " ", offs, irn);
783         }
784         else {
785                 fprintf(F, "\t\t\t\t\t/* omitted IncSP with 0 */\n");
786         }
787 }
788
789
790 /***********************************************************************************
791  *                  _          __                                             _
792  *                 (_)        / _|                                           | |
793  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
794  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
795  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
796  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
797  *
798  ***********************************************************************************/
799
800 /**
801  * Enters the emitter functions for handled nodes into the generic
802  * pointer of an opcode.
803  */
804 static void ia32_register_emitters(void) {
805
806 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
807 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
808 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
809
810         /* first clear the generic function pointer for all ops */
811         clear_irp_opcodes_generic_func();
812
813         /* register all emitter functions defined in spec */
814         ia32_register_spec_emitters();
815
816         /* other ia32 emitter functions */
817         IA32_EMIT(CondJmp);
818         IA32_EMIT(SwitchJmp);
819         IA32_EMIT(CopyB);
820         IA32_EMIT(CopyB_i);
821
822         /* benode emitter */
823         BE_EMIT(Call);
824         BE_EMIT(IncSP);
825
826         /* firm emitter */
827         EMIT(Jmp);
828         EMIT(Proj);
829
830 #undef IA32_EMIT
831 #undef BE_EMIT
832 #undef EMIT
833 }
834
835 /**
836  * Emits code for a node.
837  */
838 static void ia32_emit_node(const ir_node *irn, void *env) {
839         emit_env_t        *emit_env = env;
840         firm_dbg_module_t *mod      = emit_env->mod;
841         FILE              *F        = emit_env->out;
842         ir_op             *op       = get_irn_op(irn);
843
844         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
845
846         if (op->ops.generic) {
847                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
848                 (*emit)(irn, env);
849         }
850         else {
851                 ir_fprintf(F, "\t\t\t\t\t/* %+F */\n", irn);
852         }
853 }
854
855 /**
856  * Walks over the nodes in a block connected by scheduling edges
857  * and emits code for each node.
858  */
859 static void ia32_gen_block(ir_node *block, void *env) {
860         const ir_node *irn;
861
862         if (! is_Block(block))
863                 return;
864
865         fprintf(((emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
866         sched_foreach(block, irn) {
867                 ia32_emit_node(irn, env);
868         }
869 }
870
871
872 /**
873  * Emits code for function start.
874  */
875 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
876         const char *irg_name = get_entity_name(get_irg_entity(irg));
877
878         fprintf(F, "\t.text\n");
879         fprintf(F, ".globl %s\n", irg_name);
880         fprintf(F, "\t.type\t%s, @function\n", irg_name);
881         fprintf(F, "%s:\n", irg_name);
882 }
883
884 /**
885  * Emits code for function end
886  */
887 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
888         const char *irg_name = get_entity_name(get_irg_entity(irg));
889
890         fprintf(F, "\tret\n");
891         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
892 }
893
894 /**
895  * Sets labels for control flow nodes (jump target)
896  * TODO: Jump optimization
897  */
898 static void ia32_gen_labels(ir_node *block, void *env) {
899         ir_node *pred;
900         int n = get_Block_n_cfgpreds(block);
901
902         for (n--; n >= 0; n--) {
903                 pred = get_Block_cfgpred(block, n);
904                 set_irn_link(pred, block);
905         }
906 }
907
908 /**
909  * Main driver. Emits the code for one routine.
910  */
911 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
912         emit_env_t emit_env;
913
914         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
915         emit_env.out      = F;
916         emit_env.arch_env = cg->arch_env;
917         emit_env.cg       = cg;
918
919         /* set the global arch_env (needed by print hooks) */
920         arch_env = cg->arch_env;
921
922         ia32_register_emitters();
923
924         ia32_emit_func_prolog(F, irg);
925         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
926         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
927         ia32_emit_func_epilog(F, irg);
928 }