- improve set transformation
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       This file implements the ia32 node emitter.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include <limits.h>
31
32 #include "xmalloc.h"
33 #include "tv.h"
34 #include "iredges.h"
35 #include "debug.h"
36 #include "irgwalk.h"
37 #include "irprintf.h"
38 #include "irop_t.h"
39 #include "irargs_t.h"
40 #include "irprog_t.h"
41 #include "iredges_t.h"
42 #include "execfreq.h"
43 #include "error.h"
44 #include "raw_bitset.h"
45
46 #include "../besched_t.h"
47 #include "../benode_t.h"
48 #include "../beabi.h"
49 #include "../be_dbgout.h"
50 #include "../beemitter.h"
51 #include "../begnuas.h"
52 #include "../beirg_t.h"
53
54 #include "ia32_emitter.h"
55 #include "gen_ia32_emitter.h"
56 #include "gen_ia32_regalloc_if.h"
57 #include "ia32_nodes_attr.h"
58 #include "ia32_new_nodes.h"
59 #include "ia32_map_regs.h"
60 #include "bearch_ia32_t.h"
61
62 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
63
64 #define BLOCK_PREFIX ".L"
65
66 #define SNPRINTF_BUF_LEN 128
67
68 static const arch_env_t *arch_env;
69 static const ia32_isa_t *isa;
70 static ia32_code_gen_t  *cg;
71
72 /**
73  * Returns the register at in position pos.
74  */
75 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
76 {
77         ir_node               *op;
78         const arch_register_t *reg = NULL;
79
80         assert(get_irn_arity(irn) > pos && "Invalid IN position");
81
82         /* The out register of the operator at position pos is the
83            in register we need. */
84         op = get_irn_n(irn, pos);
85
86         reg = arch_get_irn_register(arch_env, op);
87
88         assert(reg && "no in register found");
89
90         if(reg == &ia32_gp_regs[REG_GP_NOREG])
91                 panic("trying to emit noreg for %+F input %d", irn, pos);
92
93         /* in case of unknown register: just return a valid register */
94         if (reg == &ia32_gp_regs[REG_GP_UKNWN]) {
95                 const arch_register_req_t *req;
96
97                 /* ask for the requirements */
98                 req = arch_get_register_req(arch_env, irn, pos);
99
100                 if (arch_register_req_is(req, limited)) {
101                         /* in case of limited requirements: get the first allowed register */
102                         unsigned idx = rbitset_next(req->limited, 0, 1);
103                         reg = arch_register_for_index(req->cls, idx);
104                 } else {
105                         /* otherwise get first register in class */
106                         reg = arch_register_for_index(req->cls, 0);
107                 }
108         }
109
110         return reg;
111 }
112
113 /**
114  * Returns the register at out position pos.
115  */
116 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
117 {
118         ir_node               *proj;
119         const arch_register_t *reg = NULL;
120
121         /* 1st case: irn is not of mode_T, so it has only                 */
122         /*           one OUT register -> good                             */
123         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
124         /*           Proj with the corresponding projnum for the register */
125
126         if (get_irn_mode(irn) != mode_T) {
127                 assert(pos == 0);
128                 reg = arch_get_irn_register(arch_env, irn);
129         } else if (is_ia32_irn(irn)) {
130                 reg = get_ia32_out_reg(irn, pos);
131         } else {
132                 const ir_edge_t *edge;
133
134                 foreach_out_edge(irn, edge) {
135                         proj = get_edge_src_irn(edge);
136                         assert(is_Proj(proj) && "non-Proj from mode_T node");
137                         if (get_Proj_proj(proj) == pos) {
138                                 reg = arch_get_irn_register(arch_env, proj);
139                                 break;
140                         }
141                 }
142         }
143
144         assert(reg && "no out register found");
145         return reg;
146 }
147
148 /**
149  * Add a number to a prefix. This number will not be used a second time.
150  */
151 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
152 {
153         static unsigned long id = 0;
154         snprintf(buf, buflen, "%s%lu", prefix, ++id);
155         return buf;
156 }
157
158 /*************************************************************
159  *             _       _    __   _          _
160  *            (_)     | |  / _| | |        | |
161  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
162  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
163  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
164  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
165  * | |                                       | |
166  * |_|                                       |_|
167  *************************************************************/
168
169 static void emit_8bit_register(const arch_register_t *reg)
170 {
171         const char *reg_name = arch_register_get_name(reg);
172
173         be_emit_char('%');
174         be_emit_char(reg_name[1]);
175         be_emit_char('l');
176 }
177
178 static void emit_16bit_register(const arch_register_t *reg)
179 {
180         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
181
182         be_emit_char('%');
183         be_emit_string(reg_name);
184 }
185
186 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
187 {
188         const char *reg_name;
189
190         if(mode != NULL) {
191                 int size = get_mode_size_bits(mode);
192                 if(size == 8) {
193                         emit_8bit_register(reg);
194                         return;
195                 } else if(size == 16) {
196                         emit_16bit_register(reg);
197                         return;
198                 } else {
199                         assert(mode_is_float(mode) || size == 32);
200                 }
201         }
202
203         reg_name = arch_register_get_name(reg);
204
205         be_emit_char('%');
206         be_emit_string(reg_name);
207 }
208
209 void ia32_emit_source_register(const ir_node *node, int pos)
210 {
211         const arch_register_t *reg      = get_in_reg(node, pos);
212
213         emit_register(reg, NULL);
214 }
215
216 static void emit_ia32_Immediate(const ir_node *node);
217
218 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
219 {
220         const arch_register_t *reg;
221         ir_node               *in = get_irn_n(node, pos);
222         if(is_ia32_Immediate(in)) {
223                 emit_ia32_Immediate(in);
224                 return;
225         }
226
227         reg = get_in_reg(node, pos);
228         emit_8bit_register(reg);
229 }
230
231 void ia32_emit_dest_register(const ir_node *node, int pos)
232 {
233         const arch_register_t *reg  = get_out_reg(node, pos);
234
235         emit_register(reg, NULL);
236 }
237
238 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
239 {
240         const arch_register_t *reg  = get_out_reg(node, pos);
241
242         emit_register(reg, mode_Bu);
243 }
244
245 void ia32_emit_x87_register(const ir_node *node, int pos)
246 {
247         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
248
249         assert(pos < 3);
250         be_emit_char('%');
251         be_emit_string(attr->x87[pos]->name);
252 }
253
254 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
255 {
256         if(mode_is_float(mode)) {
257                 switch(get_mode_size_bits(mode)) {
258                 case 32: be_emit_char('s'); return;
259                 case 64: be_emit_char('l'); return;
260                 case 80: be_emit_char('t'); return;
261                 }
262         } else {
263                 assert(mode_is_int(mode) || mode_is_reference(mode));
264                 switch(get_mode_size_bits(mode)) {
265                 case 64: be_emit_cstring("ll"); return;
266                                  /* gas docu says q is the suffix but gcc, objdump and icc use
267                                         ll apparently */
268                 case 32: be_emit_char('l'); return;
269                 case 16: be_emit_char('w'); return;
270                 case 8:  be_emit_char('b'); return;
271                 }
272         }
273         panic("Can't output mode_suffix for %+F\n", mode);
274 }
275
276 void ia32_emit_mode_suffix(const ir_node *node)
277 {
278         ir_mode *mode = get_ia32_ls_mode(node);
279         if(mode == NULL)
280                 mode = mode_Iu;
281
282         ia32_emit_mode_suffix_mode(mode);
283 }
284
285 void ia32_emit_x87_mode_suffix(const ir_node *node)
286 {
287         ir_mode *mode = get_ia32_ls_mode(node);
288         assert(mode != NULL);
289         /* we only need to emit the mode on address mode */
290         if(get_ia32_op_type(node) != ia32_Normal)
291                 ia32_emit_mode_suffix_mode(mode);
292 }
293
294 static
295 char get_xmm_mode_suffix(ir_mode *mode)
296 {
297         assert(mode_is_float(mode));
298         switch(get_mode_size_bits(mode)) {
299         case 32:
300                 return 's';
301         case 64:
302                 return 'd';
303         default:
304                 assert(0);
305         }
306         return '%';
307 }
308
309 void ia32_emit_xmm_mode_suffix(const ir_node *node)
310 {
311         ir_mode *mode = get_ia32_ls_mode(node);
312         assert(mode != NULL);
313         be_emit_char('s');
314         be_emit_char(get_xmm_mode_suffix(mode));
315 }
316
317 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
318 {
319         ir_mode *mode = get_ia32_ls_mode(node);
320         assert(mode != NULL);
321         be_emit_char(get_xmm_mode_suffix(mode));
322 }
323
324 void ia32_emit_extend_suffix(const ir_mode *mode)
325 {
326         if(get_mode_size_bits(mode) == 32)
327                 return;
328         if(mode_is_signed(mode)) {
329                 be_emit_char('s');
330         } else {
331                 be_emit_char('z');
332         }
333 }
334
335 static
336 void ia32_emit_function_object(const char *name)
337 {
338         switch (be_gas_flavour) {
339         case GAS_FLAVOUR_NORMAL:
340                 be_emit_cstring("\t.type\t");
341                 be_emit_string(name);
342                 be_emit_cstring(", @function\n");
343                 be_emit_write_line();
344                 break;
345         case GAS_FLAVOUR_MINGW:
346                 be_emit_cstring("\t.def\t");
347                 be_emit_string(name);
348                 be_emit_cstring(";\t.scl\t2;\t.type\t32;\t.endef\n");
349                 be_emit_write_line();
350                 break;
351         default:
352                 break;
353         }
354 }
355
356 static
357 void ia32_emit_function_size(const char *name)
358 {
359         switch (be_gas_flavour) {
360         case GAS_FLAVOUR_NORMAL:
361                 be_emit_cstring("\t.size\t");
362                 be_emit_string(name);
363                 be_emit_cstring(", .-");
364                 be_emit_string(name);
365                 be_emit_char('\n');
366                 be_emit_write_line();
367                 break;
368         default:
369                 break;
370         }
371 }
372
373
374 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
375 {
376         ir_node *in = get_irn_n(node, pos);
377         if(is_ia32_Immediate(in)) {
378                 emit_ia32_Immediate(in);
379         } else {
380                 const ir_mode         *mode = get_ia32_ls_mode(node);
381                 const arch_register_t *reg  = get_in_reg(node, pos);
382                 emit_register(reg, mode);
383         }
384 }
385
386 /**
387  * Emits registers and/or address mode of a binary operation.
388  */
389 void ia32_emit_binop(const ir_node *node) {
390         const ir_node         *right_op  = get_irn_n(node, n_ia32_binary_right);
391         const ir_mode         *mode      = get_ia32_ls_mode(node);
392         const arch_register_t *reg_left;
393
394         switch(get_ia32_op_type(node)) {
395         case ia32_Normal:
396                 reg_left = get_in_reg(node, n_ia32_binary_left);
397                 if(is_ia32_Immediate(right_op)) {
398                         emit_ia32_Immediate(right_op);
399                         be_emit_cstring(", ");
400                         emit_register(reg_left, mode);
401                         break;
402                 } else {
403                         const arch_register_t *reg_right
404                                 = get_in_reg(node, n_ia32_binary_right);
405                         emit_register(reg_right, mode);
406                         be_emit_cstring(", ");
407                         emit_register(reg_left, mode);
408                 }
409                 break;
410         case ia32_AddrModeS:
411                 if(is_ia32_Immediate(right_op)) {
412                         emit_ia32_Immediate(right_op);
413                         be_emit_cstring(", ");
414                         ia32_emit_am(node);
415                 } else {
416                         reg_left = get_in_reg(node, n_ia32_binary_left);
417                         ia32_emit_am(node);
418                         be_emit_cstring(", ");
419                         emit_register(reg_left, mode);
420                 }
421                 break;
422         case ia32_AddrModeD:
423                 panic("DestMode can't be output by %%binop anymore");
424                 break;
425         default:
426                 assert(0 && "unsupported op type");
427         }
428 }
429
430 /**
431  * Emits registers and/or address mode of a binary operation.
432  */
433 void ia32_emit_x87_binop(const ir_node *node) {
434         switch(get_ia32_op_type(node)) {
435                 case ia32_Normal:
436                         {
437                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
438                                 const arch_register_t *in1      = x87_attr->x87[0];
439                                 const arch_register_t *in2      = x87_attr->x87[1];
440                                 const arch_register_t *out      = x87_attr->x87[2];
441                                 const arch_register_t *in;
442
443                                 in  = out ? ((out == in2) ? in1 : in2) : in2;
444                                 out = out ? out : in1;
445
446                                 be_emit_char('%');
447                                 be_emit_string(arch_register_get_name(in));
448                                 be_emit_cstring(", %");
449                                 be_emit_string(arch_register_get_name(out));
450                         }
451                         break;
452                 case ia32_AddrModeS:
453                         ia32_emit_am(node);
454                         break;
455                 case ia32_AddrModeD:
456                 default:
457                         assert(0 && "unsupported op type");
458         }
459 }
460
461 void ia32_emit_am_or_dest_register(const ir_node *node,
462                                    int pos) {
463         if(get_ia32_op_type(node) == ia32_Normal) {
464                 ia32_emit_dest_register(node, pos);
465         } else {
466                 assert(get_ia32_op_type(node) == ia32_AddrModeD);
467                 ia32_emit_am(node);
468         }
469 }
470
471 /**
472  * Emits registers and/or address mode of a unary operation.
473  */
474 void ia32_emit_unop(const ir_node *node, int pos) {
475         const ir_node *op;
476
477         switch(get_ia32_op_type(node)) {
478         case ia32_Normal:
479                 op = get_irn_n(node, pos);
480                 if (is_ia32_Immediate(op)) {
481                         emit_ia32_Immediate(op);
482                 } else {
483                         ia32_emit_source_register(node, pos);
484                 }
485                 break;
486         case ia32_AddrModeS:
487         case ia32_AddrModeD:
488                 ia32_emit_am(node);
489                 break;
490         default:
491                 assert(0 && "unsupported op type");
492         }
493 }
494
495 /**
496  * Emits address mode.
497  */
498 void ia32_emit_am(const ir_node *node) {
499         ir_entity *ent       = get_ia32_am_sc(node);
500         int        offs      = get_ia32_am_offs_int(node);
501         ir_node   *base      = get_irn_n(node, 0);
502         int        has_base  = !is_ia32_NoReg_GP(base);
503         ir_node   *index     = get_irn_n(node, 1);
504         int        has_index = !is_ia32_NoReg_GP(index);
505
506         /* just to be sure... */
507         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
508
509         /* emit offset */
510         if (ent != NULL) {
511                 ident *id;
512
513                 set_entity_backend_marked(ent, 1);
514                 id = get_entity_ld_ident(ent);
515                 if (is_ia32_am_sc_sign(node))
516                         be_emit_char('-');
517                 be_emit_ident(id);
518
519                 if(get_entity_owner(ent) == get_tls_type()) {
520                         if (get_entity_visibility(ent) == visibility_external_allocated) {
521                                 be_emit_cstring("@INDNTPOFF");
522                         } else {
523                                 be_emit_cstring("@NTPOFF");
524                         }
525                 }
526         }
527
528         if(offs != 0) {
529                 if(ent != NULL) {
530                         be_emit_irprintf("%+d", offs);
531                 } else {
532                         be_emit_irprintf("%d", offs);
533                 }
534         }
535
536         if (has_base || has_index) {
537                 be_emit_char('(');
538
539                 /* emit base */
540                 if (has_base) {
541                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
542                         emit_register(reg, NULL);
543                 }
544
545                 /* emit index + scale */
546                 if (has_index) {
547                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
548                         int scale;
549                         be_emit_char(',');
550                         emit_register(reg, NULL);
551
552                         scale = get_ia32_am_scale(node);
553                         if (scale > 0) {
554                                 be_emit_irprintf(",%d", 1 << get_ia32_am_scale(node));
555                         }
556                 }
557                 be_emit_char(')');
558         }
559
560         /* special case if nothing is set */
561         if(ent == NULL && offs == 0 && !has_base && !has_index) {
562                 be_emit_char('0');
563         }
564 }
565
566 static void emit_ia32_IMul(const ir_node *node)
567 {
568         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
569         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
570
571         be_emit_cstring("\timul");
572         ia32_emit_mode_suffix(node);
573         be_emit_char(' ');
574
575         ia32_emit_binop(node);
576
577         /* do we need the 3-address form? */
578         if(is_ia32_NoReg_GP(left) ||
579                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
580                 be_emit_cstring(", ");
581                 emit_register(out_reg, get_ia32_ls_mode(node));
582         }
583         be_emit_finish_line_gas(node);
584 }
585
586 /*************************************************
587  *                 _ _                         _
588  *                (_) |                       | |
589  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
590  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
591  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
592  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
593  *
594  *************************************************/
595
596 #undef IA32_DO_EMIT
597 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
598
599 /*
600  * coding of conditions
601  */
602 struct cmp2conditon_t {
603         const char *name;
604         int         num;
605 };
606
607 /*
608  * positive conditions for signed compares
609  */
610 static const struct cmp2conditon_t cmp2condition_s[] = {
611         { NULL,              pn_Cmp_False },  /* always false */
612         { "e",               pn_Cmp_Eq },     /* == */
613         { "l",               pn_Cmp_Lt },     /* < */
614         { "le",              pn_Cmp_Le },     /* <= */
615         { "g",               pn_Cmp_Gt },     /* > */
616         { "ge",              pn_Cmp_Ge },     /* >= */
617         { "ne",              pn_Cmp_Lg },     /* != */
618         { NULL,              pn_Cmp_Leg},     /* always true */
619 };
620
621 /*
622  * positive conditions for unsigned compares
623  */
624 static const struct cmp2conditon_t cmp2condition_u[] = {
625         { NULL,              pn_Cmp_False },  /* always false */
626         { "e",               pn_Cmp_Eq },     /* == */
627         { "b",               pn_Cmp_Lt },     /* < */
628         { "be",              pn_Cmp_Le },     /* <= */
629         { "a",               pn_Cmp_Gt },     /* > */
630         { "ae",              pn_Cmp_Ge },     /* >= */
631         { "ne",              pn_Cmp_Lg },     /* != */
632         { NULL,              pn_Cmp_Leg },   /* always true  */
633 };
634
635 enum {
636         ia32_pn_Cmp_unsigned = 0x1000,
637         ia32_pn_Cmp_float    = 0x2000,
638 };
639
640 /**
641  * walks up a tree of copies/perms/spills/reloads to find the original value
642  * that is moved around
643  */
644 static ir_node *find_original_value(ir_node *node)
645 {
646         inc_irg_visited(current_ir_graph);
647         while(1) {
648                 mark_irn_visited(node);
649                 if(be_is_Copy(node)) {
650                         node = be_get_Copy_op(node);
651                 } else if(be_is_CopyKeep(node)) {
652                         node = be_get_CopyKeep_op(node);
653                 } else if(is_Proj(node)) {
654                         ir_node *pred = get_Proj_pred(node);
655                         if(be_is_Perm(pred)) {
656                                 node = get_irn_n(pred, get_Proj_proj(node));
657                         } else if(be_is_MemPerm(pred)) {
658                                 node = get_irn_n(pred, get_Proj_proj(node) + 1);
659                         } else if(is_ia32_Load(pred)) {
660                                 node = get_irn_n(pred, n_ia32_Load_mem);
661                         } else {
662                                 return node;
663                         }
664                 } else if(is_ia32_Store(node)) {
665                         node = get_irn_n(node, n_ia32_Store_val);
666                 } else if(is_Phi(node)) {
667                         int i, arity;
668                         arity = get_irn_arity(node);
669                         for(i = 0; i < arity; ++i) {
670                                 ir_node *in = get_irn_n(node, i);
671                                 if(irn_visited(in))
672                                         continue;
673                                 node = in;
674                                 break;
675                         }
676                         assert(i < arity);
677                 } else {
678                         return node;
679                 }
680         }
681 }
682
683 static int determine_final_pnc(const ir_node *node, int flags_pos,
684                                int pnc)
685 {
686         ir_node           *flags = get_irn_n(node, flags_pos);
687         const ia32_attr_t *flags_attr;
688         flags = skip_Proj(flags);
689
690         if(is_ia32_Sahf(flags)) {
691                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
692                 if(!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
693                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
694                         cmp = find_original_value(cmp);
695                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
696                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
697                 }
698
699                 flags_attr = get_ia32_attr_const(cmp);
700                 if(flags_attr->data.ins_permuted)
701                         pnc = get_mirrored_pnc(pnc);
702                 pnc |= ia32_pn_Cmp_float;
703         } else if(is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
704                         || is_ia32_Fucompi(flags)) {
705                 flags_attr = get_ia32_attr_const(flags);
706
707                 if(flags_attr->data.ins_permuted)
708                         pnc = get_mirrored_pnc(pnc);
709                 pnc |= ia32_pn_Cmp_float;
710         } else {
711                 assert(is_ia32_Cmp(flags) || is_ia32_Test(flags)
712                                 || is_ia32_Cmp8Bit(flags) || is_ia32_Test8Bit(flags));
713                 flags_attr = get_ia32_attr_const(flags);
714
715                 if(flags_attr->data.ins_permuted)
716                         pnc = get_mirrored_pnc(pnc);
717                 if(flags_attr->data.cmp_unsigned)
718                         pnc |= ia32_pn_Cmp_unsigned;
719         }
720
721         return pnc;
722 }
723
724 static void ia32_emit_cmp_suffix(int pnc)
725 {
726         const char        *str;
727
728         if((pnc & ia32_pn_Cmp_float) || (pnc & ia32_pn_Cmp_unsigned)) {
729                 pnc = pnc & 7;
730                 assert(cmp2condition_u[pnc].num == pnc);
731                 str = cmp2condition_u[pnc].name;
732         } else {
733                 pnc = pnc & 7;
734                 assert(cmp2condition_s[pnc].num == pnc);
735                 str = cmp2condition_s[pnc].name;
736         }
737
738         be_emit_string(str);
739 }
740
741 void ia32_emit_cmp_suffix_node(const ir_node *node,
742                                int flags_pos)
743 {
744         const ia32_attr_t *attr = get_ia32_attr_const(node);
745
746         pn_Cmp pnc = get_ia32_condcode(node);
747
748         pnc = determine_final_pnc(node, flags_pos, pnc);
749         if(attr->data.ins_permuted) {
750                 if(pnc & ia32_pn_Cmp_float) {
751                         pnc = get_negated_pnc(pnc, mode_F);
752                 } else {
753                         pnc = get_negated_pnc(pnc, mode_Iu);
754                 }
755         }
756
757         ia32_emit_cmp_suffix(pnc);
758 }
759
760 /**
761  * Returns the target block for a control flow node.
762  */
763 static
764 ir_node *get_cfop_target_block(const ir_node *irn) {
765         return get_irn_link(irn);
766 }
767
768 /**
769  * Emits a block label for the given block.
770  */
771 static
772 void ia32_emit_block_name(const ir_node *block)
773 {
774         if (has_Block_label(block)) {
775                 be_emit_string(be_gas_label_prefix());
776                 be_emit_irprintf("%u", (unsigned)get_Block_label(block));
777         } else {
778                 be_emit_cstring(BLOCK_PREFIX);
779                 be_emit_irprintf("%d", get_irn_node_nr(block));
780         }
781 }
782
783 /**
784  * Emits the target label for a control flow node.
785  */
786 static void ia32_emit_cfop_target(const ir_node *node)
787 {
788         ir_node *block = get_cfop_target_block(node);
789
790         ia32_emit_block_name(block);
791 }
792
793 /** Return the next block in Block schedule */
794 static ir_node *next_blk_sched(const ir_node *block)
795 {
796         return get_irn_link(block);
797 }
798
799 /**
800  * Returns the Proj with projection number proj and NOT mode_M
801  */
802 static ir_node *get_proj(const ir_node *node, long proj) {
803         const ir_edge_t *edge;
804         ir_node         *src;
805
806         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
807
808         foreach_out_edge(node, edge) {
809                 src = get_edge_src_irn(edge);
810
811                 assert(is_Proj(src) && "Proj expected");
812                 if (get_irn_mode(src) == mode_M)
813                         continue;
814
815                 if (get_Proj_proj(src) == proj)
816                         return src;
817         }
818         return NULL;
819 }
820
821 /**
822  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
823  */
824 static void emit_ia32_Jcc(const ir_node *node)
825 {
826         const ir_node *proj_true;
827         const ir_node *proj_false;
828         const ir_node *block;
829         const ir_node *next_block;
830         pn_Cmp         pnc = get_ia32_condcode(node);
831
832         pnc = determine_final_pnc(node, 0, pnc);
833
834         /* get both Projs */
835         proj_true = get_proj(node, pn_ia32_Jcc_true);
836         assert(proj_true && "Jcc without true Proj");
837
838         proj_false = get_proj(node, pn_ia32_Jcc_false);
839         assert(proj_false && "Jcc without false Proj");
840
841         block      = get_nodes_block(node);
842         next_block = next_blk_sched(block);
843
844         if (get_cfop_target_block(proj_true) == next_block) {
845                 /* exchange both proj's so the second one can be omitted */
846                 const ir_node *t = proj_true;
847
848                 proj_true  = proj_false;
849                 proj_false = t;
850                 if(pnc & ia32_pn_Cmp_float) {
851                         pnc = get_negated_pnc(pnc, mode_F);
852                 } else {
853                         pnc = get_negated_pnc(pnc, mode_Iu);
854                 }
855         }
856
857         if (pnc & ia32_pn_Cmp_float) {
858                 /* Some floating point comparisons require a test of the parity flag,
859                  * which indicates that the result is unordered */
860                 switch (pnc & 15) {
861                         case pn_Cmp_Uo:
862                                 be_emit_cstring("\tjp ");
863                                 ia32_emit_cfop_target(proj_true);
864                                 be_emit_finish_line_gas(proj_true);
865                                 break;
866
867                         case pn_Cmp_Leg:
868                                 be_emit_cstring("\tjnp ");
869                                 ia32_emit_cfop_target(proj_true);
870                                 be_emit_finish_line_gas(proj_true);
871                                 break;
872
873                         case pn_Cmp_Eq:
874                         case pn_Cmp_Lt:
875                         case pn_Cmp_Le:
876                                 be_emit_cstring("\tjp ");
877                                 ia32_emit_cfop_target(proj_false);
878                                 be_emit_finish_line_gas(proj_false);
879                                 goto emit_jcc;
880
881                         case pn_Cmp_Ug:
882                         case pn_Cmp_Uge:
883                         case pn_Cmp_Ne:
884                                 be_emit_cstring("\tjp ");
885                                 ia32_emit_cfop_target(proj_true);
886                                 be_emit_finish_line_gas(proj_true);
887                                 goto emit_jcc;
888
889                         default:
890                                 goto emit_jcc;
891                 }
892         } else {
893 emit_jcc:
894                 be_emit_cstring("\tj");
895                 ia32_emit_cmp_suffix(pnc);
896                 be_emit_char(' ');
897                 ia32_emit_cfop_target(proj_true);
898                 be_emit_finish_line_gas(proj_true);
899         }
900
901         /* the second Proj might be a fallthrough */
902         if (get_cfop_target_block(proj_false) != next_block) {
903                 be_emit_cstring("\tjmp ");
904                 ia32_emit_cfop_target(proj_false);
905                 be_emit_finish_line_gas(proj_false);
906         } else {
907                 be_emit_cstring("\t/* fallthrough to ");
908                 ia32_emit_cfop_target(proj_false);
909                 be_emit_cstring(" */");
910                 be_emit_finish_line_gas(proj_false);
911         }
912 }
913
914 static void emit_ia32_CMov(const ir_node *node)
915 {
916         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
917         int                    ins_permuted = attr->data.ins_permuted;
918         const arch_register_t *out          = arch_get_irn_register(arch_env, node);
919         pn_Cmp                 pnc          = get_ia32_condcode(node);
920         const arch_register_t *in_true;
921         const arch_register_t *in_false;
922
923         pnc = determine_final_pnc(node, n_ia32_CMov_eflags, pnc);
924
925         in_true  = arch_get_irn_register(arch_env,
926                                          get_irn_n(node, n_ia32_CMov_val_true));
927         in_false = arch_get_irn_register(arch_env,
928                                          get_irn_n(node, n_ia32_CMov_val_false));
929
930         /* should be same constraint fullfilled? */
931         if(out == in_false) {
932                 /* yes -> nothing to do */
933         } else if(out == in_true) {
934                 const arch_register_t *tmp;
935
936                 assert(get_ia32_op_type(node) == ia32_Normal);
937
938                 ins_permuted = !ins_permuted;
939
940                 tmp      = in_true;
941                 in_true  = in_false;
942                 in_false = tmp;
943         } else {
944                 /* we need a mov */
945                 be_emit_cstring("\tmovl ");
946                 emit_register(in_false, NULL);
947                 be_emit_cstring(", ");
948                 emit_register(out, NULL);
949                 be_emit_finish_line_gas(node);
950         }
951
952         if(ins_permuted) {
953                 if(pnc & ia32_pn_Cmp_float) {
954                         pnc = get_negated_pnc(pnc, mode_F);
955                 } else {
956                         pnc = get_negated_pnc(pnc, mode_Iu);
957                 }
958         }
959
960         /* TODO: handling of Nans isn't correct yet */
961
962         be_emit_cstring("\tcmov");
963         ia32_emit_cmp_suffix(pnc);
964         be_emit_char(' ');
965         if(get_ia32_op_type(node) == ia32_AddrModeS) {
966                 ia32_emit_am(node);
967         } else {
968                 emit_register(in_true, get_ia32_ls_mode(node));
969         }
970         be_emit_cstring(", ");
971         emit_register(out, get_ia32_ls_mode(node));
972         be_emit_finish_line_gas(node);
973 }
974
975 /*********************************************************
976  *                 _ _       _
977  *                (_) |     (_)
978  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
979  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
980  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
981  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
982  *                         _/ |               | |
983  *                        |__/                |_|
984  *********************************************************/
985
986 /* jump table entry (target and corresponding number) */
987 typedef struct _branch_t {
988         ir_node *target;
989         int      value;
990 } branch_t;
991
992 /* jump table for switch generation */
993 typedef struct _jmp_tbl_t {
994         ir_node  *defProj;         /**< default target */
995         long      min_value;       /**< smallest switch case */
996         long      max_value;       /**< largest switch case */
997         long      num_branches;    /**< number of jumps */
998         char     *label;           /**< label of the jump table */
999         branch_t *branches;        /**< jump array */
1000 } jmp_tbl_t;
1001
1002 /**
1003  * Compare two variables of type branch_t. Used to sort all switch cases
1004  */
1005 static
1006 int ia32_cmp_branch_t(const void *a, const void *b) {
1007         branch_t *b1 = (branch_t *)a;
1008         branch_t *b2 = (branch_t *)b;
1009
1010         if (b1->value <= b2->value)
1011                 return -1;
1012         else
1013                 return 1;
1014 }
1015
1016 /**
1017  * Emits code for a SwitchJmp (creates a jump table if
1018  * possible otherwise a cmp-jmp cascade). Port from
1019  * cggg ia32 backend
1020  */
1021 static
1022 void emit_ia32_SwitchJmp(const ir_node *node) {
1023         unsigned long       interval;
1024         int                 last_value, i;
1025         long                pnc;
1026         jmp_tbl_t           tbl;
1027         ir_node            *proj;
1028         const ir_edge_t    *edge;
1029
1030         /* fill the table structure */
1031         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
1032         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, ".TBL_");
1033         tbl.defProj      = NULL;
1034         tbl.num_branches = get_irn_n_edges(node);
1035         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
1036         tbl.min_value    = INT_MAX;
1037         tbl.max_value    = INT_MIN;
1038
1039         i = 0;
1040         /* go over all proj's and collect them */
1041         foreach_out_edge(node, edge) {
1042                 proj = get_edge_src_irn(edge);
1043                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1044
1045                 pnc = get_Proj_proj(proj);
1046
1047                 /* create branch entry */
1048                 tbl.branches[i].target = proj;
1049                 tbl.branches[i].value  = pnc;
1050
1051                 tbl.min_value = pnc < tbl.min_value ? pnc : tbl.min_value;
1052                 tbl.max_value = pnc > tbl.max_value ? pnc : tbl.max_value;
1053
1054                 /* check for default proj */
1055                 if (pnc == get_ia32_condcode(node)) {
1056                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
1057                         tbl.defProj = proj;
1058                 }
1059
1060                 i++;
1061         }
1062
1063         /* sort the branches by their number */
1064         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1065
1066         /* two-complement's magic make this work without overflow */
1067         interval = tbl.max_value - tbl.min_value;
1068
1069         /* emit the table */
1070         be_emit_cstring("\tcmpl $");
1071         be_emit_irprintf("%u, ", interval);
1072         ia32_emit_source_register(node, 0);
1073         be_emit_finish_line_gas(node);
1074
1075         be_emit_cstring("\tja ");
1076         ia32_emit_cfop_target(tbl.defProj);
1077         be_emit_finish_line_gas(node);
1078
1079         if (tbl.num_branches > 1) {
1080                 /* create table */
1081                 be_emit_cstring("\tjmp *");
1082                 be_emit_string(tbl.label);
1083                 be_emit_cstring("(,");
1084                 ia32_emit_source_register(node, 0);
1085                 be_emit_cstring(",4)");
1086                 be_emit_finish_line_gas(node);
1087
1088                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1089                 be_emit_cstring("\t.align 4\n");
1090                 be_emit_write_line();
1091
1092                 be_emit_string(tbl.label);
1093                 be_emit_cstring(":\n");
1094                 be_emit_write_line();
1095
1096                 be_emit_cstring(".long ");
1097                 ia32_emit_cfop_target(tbl.branches[0].target);
1098                 be_emit_finish_line_gas(NULL);
1099
1100                 last_value = tbl.branches[0].value;
1101                 for (i = 1; i < tbl.num_branches; ++i) {
1102                         while (++last_value < tbl.branches[i].value) {
1103                                 be_emit_cstring(".long ");
1104                                 ia32_emit_cfop_target(tbl.defProj);
1105                                 be_emit_finish_line_gas(NULL);
1106                         }
1107                         be_emit_cstring(".long ");
1108                         ia32_emit_cfop_target(tbl.branches[i].target);
1109                         be_emit_finish_line_gas(NULL);
1110                 }
1111                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1112         } else {
1113                 /* one jump is enough */
1114                 be_emit_cstring("\tjmp ");
1115                 ia32_emit_cfop_target(tbl.branches[0].target);
1116                 be_emit_finish_line_gas(node);
1117         }
1118
1119         if (tbl.label)
1120                 free(tbl.label);
1121         if (tbl.branches)
1122                 free(tbl.branches);
1123 }
1124
1125 /**
1126  * Emits code for a unconditional jump.
1127  */
1128 static void emit_Jmp(const ir_node *node)
1129 {
1130         ir_node *block, *next_block;
1131
1132         /* for now, the code works for scheduled and non-schedules blocks */
1133         block = get_nodes_block(node);
1134
1135         /* we have a block schedule */
1136         next_block = next_blk_sched(block);
1137         if (get_cfop_target_block(node) != next_block) {
1138                 be_emit_cstring("\tjmp ");
1139                 ia32_emit_cfop_target(node);
1140         } else {
1141                 be_emit_cstring("\t/* fallthrough to ");
1142                 ia32_emit_cfop_target(node);
1143                 be_emit_cstring(" */");
1144         }
1145         be_emit_finish_line_gas(node);
1146 }
1147
1148 static void emit_ia32_Immediate(const ir_node *node)
1149 {
1150         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
1151
1152         be_emit_char('$');
1153         if(attr->symconst != NULL) {
1154                 ident *id = get_entity_ld_ident(attr->symconst);
1155
1156                 if(attr->sc_sign)
1157                         be_emit_char('-');
1158                 be_emit_ident(id);
1159         }
1160         if(attr->symconst == NULL || attr->offset != 0) {
1161                 if(attr->symconst != NULL) {
1162                         be_emit_irprintf("%+d", attr->offset);
1163                 } else {
1164                         be_emit_irprintf("0x%X", attr->offset);
1165                 }
1166         }
1167 }
1168
1169 /**
1170  * Emit an inline assembler operand.
1171  *
1172  * @param node  the ia32_ASM node
1173  * @param s     points to the operand (a %c)
1174  *
1175  * @return  pointer to the first char in s NOT in the current operand
1176  */
1177 static const char* emit_asm_operand(const ir_node *node, const char *s)
1178 {
1179         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1180         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1181                                                             ia32_attr);
1182         const arch_register_t *reg;
1183         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1184         const ia32_asm_reg_t  *asm_reg;
1185         const char            *reg_name;
1186         char                   c;
1187         char                   modifier = 0;
1188         int                    num      = -1;
1189         int                    p;
1190
1191         assert(*s == '%');
1192         c = *(++s);
1193
1194         /* parse modifiers */
1195         switch(c) {
1196         case 0:
1197                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %\n", node);
1198                 be_emit_char('%');
1199                 return s + 1;
1200         case '%':
1201                 be_emit_char('%');
1202                 return s + 1;
1203         case 'w':
1204         case 'b':
1205         case 'h':
1206                 modifier = c;
1207                 ++s;
1208                 break;
1209         case '0':
1210         case '1':
1211         case '2':
1212         case '3':
1213         case '4':
1214         case '5':
1215         case '6':
1216         case '7':
1217         case '8':
1218         case '9':
1219                 break;
1220         default:
1221                 ir_fprintf(stderr, "Warning: asm text (%+F) contains unknown modifier "
1222                            "'%c' for asm op\n", node, c);
1223                 ++s;
1224                 break;
1225         }
1226
1227         /* parse number */
1228         sscanf(s, "%d%n", &num, &p);
1229         if(num < 0) {
1230                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1231                            node);
1232                 return s;
1233         } else {
1234                 s += p;
1235         }
1236
1237         if(num < 0 || num >= ARR_LEN(asm_regs)) {
1238                 ir_fprintf(stderr, "Error: Custom assembler references invalid "
1239                            "input/output (%+F)\n", node);
1240                 return s;
1241         }
1242         asm_reg = & asm_regs[num];
1243         assert(asm_reg->valid);
1244
1245         /* get register */
1246         if(asm_reg->use_input == 0) {
1247                 reg = get_out_reg(node, asm_reg->inout_pos);
1248         } else {
1249                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1250
1251                 /* might be an immediate value */
1252                 if(is_ia32_Immediate(pred)) {
1253                         emit_ia32_Immediate(pred);
1254                         return s;
1255                 }
1256                 reg = get_in_reg(node, asm_reg->inout_pos);
1257         }
1258         if(reg == NULL) {
1259                 ir_fprintf(stderr, "Warning: no register assigned for %d asm op "
1260                            "(%+F)\n", num, node);
1261                 return s;
1262         }
1263
1264         if(asm_reg->memory) {
1265                 be_emit_char('(');
1266         }
1267
1268         /* emit it */
1269         if(modifier != 0) {
1270                 be_emit_char('%');
1271                 switch(modifier) {
1272                 case 'b':
1273                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1274                         break;
1275                 case 'h':
1276                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1277                         break;
1278                 case 'w':
1279                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1280                         break;
1281                 default:
1282                         panic("Invalid asm op modifier");
1283                 }
1284                 be_emit_string(reg_name);
1285         } else {
1286                 emit_register(reg, asm_reg->mode);
1287         }
1288
1289         if(asm_reg->memory) {
1290                 be_emit_char(')');
1291         }
1292
1293         return s;
1294 }
1295
1296 /**
1297  * Emits code for an ASM pseudo op.
1298  */
1299 static void emit_ia32_Asm(const ir_node *node)
1300 {
1301         const void            *gen_attr = get_irn_generic_attr_const(node);
1302         const ia32_asm_attr_t *attr
1303                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1304         ident                 *asm_text = attr->asm_text;
1305         const char            *s        = get_id_str(asm_text);
1306
1307         be_emit_cstring("# Begin ASM \t");
1308         be_emit_finish_line_gas(node);
1309
1310         if (s[0] != '\t')
1311                 be_emit_char('\t');
1312
1313         while(*s != 0) {
1314                 if(*s == '%') {
1315                         s = emit_asm_operand(node, s);
1316                         continue;
1317                 } else {
1318                         be_emit_char(*s);
1319                 }
1320                 ++s;
1321         }
1322
1323         be_emit_char('\n');
1324         be_emit_write_line();
1325
1326         be_emit_cstring("# End ASM\n");
1327         be_emit_write_line();
1328 }
1329
1330 /**********************************
1331  *   _____                  ____
1332  *  / ____|                |  _ \
1333  * | |     ___  _ __  _   _| |_) |
1334  * | |    / _ \| '_ \| | | |  _ <
1335  * | |___| (_) | |_) | |_| | |_) |
1336  *  \_____\___/| .__/ \__, |____/
1337  *             | |     __/ |
1338  *             |_|    |___/
1339  **********************************/
1340
1341 /**
1342  * Emit movsb/w instructions to make mov count divideable by 4
1343  */
1344 static void emit_CopyB_prolog(unsigned size) {
1345         be_emit_cstring("\tcld");
1346         be_emit_finish_line_gas(NULL);
1347
1348         switch (size) {
1349         case 1:
1350                 be_emit_cstring("\tmovsb");
1351                 be_emit_finish_line_gas(NULL);
1352                 break;
1353         case 2:
1354                 be_emit_cstring("\tmovsw");
1355                 be_emit_finish_line_gas(NULL);
1356                 break;
1357         case 3:
1358                 be_emit_cstring("\tmovsb");
1359                 be_emit_finish_line_gas(NULL);
1360                 be_emit_cstring("\tmovsw");
1361                 be_emit_finish_line_gas(NULL);
1362                 break;
1363         }
1364 }
1365
1366 /**
1367  * Emit rep movsd instruction for memcopy.
1368  */
1369 static void emit_ia32_CopyB(const ir_node *node)
1370 {
1371         unsigned size = get_ia32_copyb_size(node);
1372
1373         emit_CopyB_prolog(size);
1374
1375         be_emit_cstring("\trep movsd");
1376         be_emit_finish_line_gas(node);
1377 }
1378
1379 /**
1380  * Emits unrolled memcopy.
1381  */
1382 static void emit_ia32_CopyB_i(const ir_node *node)
1383 {
1384         unsigned size = get_ia32_copyb_size(node);
1385
1386         emit_CopyB_prolog(size & 0x3);
1387
1388         size >>= 2;
1389         while (size--) {
1390                 be_emit_cstring("\tmovsd");
1391                 be_emit_finish_line_gas(NULL);
1392         }
1393 }
1394
1395
1396
1397 /***************************
1398  *   _____
1399  *  / ____|
1400  * | |     ___  _ ____   __
1401  * | |    / _ \| '_ \ \ / /
1402  * | |___| (_) | | | \ V /
1403  *  \_____\___/|_| |_|\_/
1404  *
1405  ***************************/
1406
1407 /**
1408  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1409  */
1410 static void emit_ia32_Conv_with_FP(const ir_node *node)
1411 {
1412         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1413         int                 ls_bits = get_mode_size_bits(ls_mode);
1414
1415         be_emit_cstring("\tcvt");
1416
1417         if(is_ia32_Conv_I2FP(node)) {
1418                 if(ls_bits == 32) {
1419                         be_emit_cstring("si2ss");
1420                 } else {
1421                         be_emit_cstring("si2sd");
1422                 }
1423         } else if(is_ia32_Conv_FP2I(node)) {
1424                 if(ls_bits == 32) {
1425                         be_emit_cstring("ss2si");
1426                 } else {
1427                         be_emit_cstring("sd2si");
1428                 }
1429         } else {
1430                 assert(is_ia32_Conv_FP2FP(node));
1431                 if(ls_bits == 32) {
1432                         be_emit_cstring("sd2ss");
1433                 } else {
1434                         be_emit_cstring("ss2sd");
1435                 }
1436         }
1437         be_emit_char(' ');
1438
1439         switch(get_ia32_op_type(node)) {
1440                 case ia32_Normal:
1441                         ia32_emit_source_register(node, n_ia32_unary_op);
1442                         break;
1443                 case ia32_AddrModeS:
1444                         ia32_emit_am(node);
1445                         break;
1446                 default:
1447                         assert(0 && "unsupported op type for Conv");
1448         }
1449         be_emit_cstring(", ");
1450         ia32_emit_dest_register(node, 0);
1451         be_emit_finish_line_gas(node);
1452 }
1453
1454 static void emit_ia32_Conv_I2FP(const ir_node *node)
1455 {
1456         emit_ia32_Conv_with_FP(node);
1457 }
1458
1459 static void emit_ia32_Conv_FP2I(const ir_node *node)
1460 {
1461         emit_ia32_Conv_with_FP(node);
1462 }
1463
1464 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1465 {
1466         emit_ia32_Conv_with_FP(node);
1467 }
1468
1469 /**
1470  * Emits code for an Int conversion.
1471  */
1472 static void emit_ia32_Conv_I2I(const ir_node *node)
1473 {
1474         const char            *sign_suffix;
1475         ir_mode               *smaller_mode = get_ia32_ls_mode(node);
1476         int                    smaller_bits = get_mode_size_bits(smaller_mode);
1477         int                    signed_mode;
1478         const arch_register_t *in_reg, *out_reg;
1479
1480         assert(!mode_is_float(smaller_mode));
1481         assert(smaller_bits == 8 || smaller_bits == 16 || smaller_bits == 32);
1482
1483         signed_mode = mode_is_signed(smaller_mode);
1484         if(smaller_bits == 32) {
1485                 // this should not happen as it's no convert
1486                 assert(0);
1487                 sign_suffix = "";
1488         } else {
1489                 sign_suffix = signed_mode ? "s" : "z";
1490         }
1491
1492         out_reg = get_out_reg(node, 0);
1493
1494         switch(get_ia32_op_type(node)) {
1495                 case ia32_Normal:
1496                         in_reg  = get_in_reg(node, n_ia32_unary_op);
1497
1498                         if (in_reg  == &ia32_gp_regs[REG_EAX] &&
1499                                 out_reg == &ia32_gp_regs[REG_EAX] &&
1500                                 signed_mode &&
1501                                 smaller_bits == 16)
1502                         {
1503                                 /* argument and result are both in EAX and */
1504                                 /* signedness is ok: -> use the smaller cwtl opcode */
1505                                 be_emit_cstring("\tcwtl");
1506                         } else {
1507                                 be_emit_cstring("\tmov");
1508                                 be_emit_string(sign_suffix);
1509                                 ia32_emit_mode_suffix_mode(smaller_mode);
1510                                 be_emit_cstring("l ");
1511                                 emit_register(in_reg, smaller_mode);
1512                                 be_emit_cstring(", ");
1513                                 emit_register(out_reg, NULL);
1514                         }
1515                         break;
1516                 case ia32_AddrModeS: {
1517                         be_emit_cstring("\tmov");
1518                         be_emit_string(sign_suffix);
1519                         ia32_emit_mode_suffix_mode(smaller_mode);
1520                         be_emit_cstring("l ");
1521                         ia32_emit_am(node);
1522                         be_emit_cstring(", ");
1523                         emit_register(out_reg, NULL);
1524                         break;
1525                 }
1526                 default:
1527                         assert(0 && "unsupported op type for Conv");
1528         }
1529         be_emit_finish_line_gas(node);
1530 }
1531
1532
1533 /*******************************************
1534  *  _                          _
1535  * | |                        | |
1536  * | |__   ___ _ __   ___   __| | ___  ___
1537  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1538  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1539  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1540  *
1541  *******************************************/
1542
1543 /**
1544  * Emits a backend call
1545  */
1546 static void emit_be_Call(const ir_node *node)
1547 {
1548         ir_entity *ent = be_Call_get_entity(node);
1549
1550         be_emit_cstring("\tcall ");
1551         if (ent) {
1552                 set_entity_backend_marked(ent, 1);
1553                 be_emit_string(get_entity_ld_name(ent));
1554         } else {
1555                 const arch_register_t *reg = get_in_reg(node, be_pos_Call_ptr);
1556                 be_emit_char('*');
1557                 emit_register(reg, NULL);
1558         }
1559         be_emit_finish_line_gas(node);
1560 }
1561
1562 /**
1563  * Emits code to increase stack pointer.
1564  */
1565 static void emit_be_IncSP(const ir_node *node)
1566 {
1567         int                    offs = be_get_IncSP_offset(node);
1568         const arch_register_t *reg  = arch_get_irn_register(arch_env, node);
1569
1570         if (offs == 0)
1571                 return;
1572
1573         if (offs > 0) {
1574                 be_emit_cstring("\tsubl $");
1575                 be_emit_irprintf("%u, ", offs);
1576                 emit_register(reg, NULL);
1577         } else {
1578                 be_emit_cstring("\taddl $");
1579                 be_emit_irprintf("%u, ", -offs);
1580                 emit_register(reg, NULL);
1581         }
1582         be_emit_finish_line_gas(node);
1583 }
1584
1585 /**
1586  * Emits code for Copy/CopyKeep.
1587  */
1588 static void Copy_emitter(const ir_node *node, const ir_node *op)
1589 {
1590         const arch_register_t *in  = arch_get_irn_register(arch_env, op);
1591         const arch_register_t *out = arch_get_irn_register(arch_env, node);
1592         ir_mode               *mode;
1593
1594         if(in == out) {
1595                 return;
1596         }
1597         if(is_unknown_reg(in))
1598                 return;
1599         /* copies of vf nodes aren't real... */
1600         if(arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1601                 return;
1602
1603         mode = get_irn_mode(node);
1604         if (mode == mode_E) {
1605                 be_emit_cstring("\tmovsd ");
1606                 emit_register(in, NULL);
1607                 be_emit_cstring(", ");
1608                 emit_register(out, NULL);
1609         } else {
1610                 be_emit_cstring("\tmovl ");
1611                 emit_register(in, NULL);
1612                 be_emit_cstring(", ");
1613                 emit_register(out, NULL);
1614         }
1615         be_emit_finish_line_gas(node);
1616 }
1617
1618 static void emit_be_Copy(const ir_node *node)
1619 {
1620         Copy_emitter(node, be_get_Copy_op(node));
1621 }
1622
1623 static void emit_be_CopyKeep(const ir_node *node)
1624 {
1625         Copy_emitter(node, be_get_CopyKeep_op(node));
1626 }
1627
1628 /**
1629  * Emits code for exchange.
1630  */
1631 static void emit_be_Perm(const ir_node *node)
1632 {
1633         const arch_register_t *in0, *in1;
1634         const arch_register_class_t *cls0, *cls1;
1635
1636         in0 = arch_get_irn_register(arch_env, get_irn_n(node, 0));
1637         in1 = arch_get_irn_register(arch_env, get_irn_n(node, 1));
1638
1639         cls0 = arch_register_get_class(in0);
1640         cls1 = arch_register_get_class(in1);
1641
1642         assert(cls0 == cls1 && "Register class mismatch at Perm");
1643
1644         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1645                 be_emit_cstring("\txchg ");
1646                 emit_register(in1, NULL);
1647                 be_emit_cstring(", ");
1648                 emit_register(in0, NULL);
1649                 be_emit_finish_line_gas(node);
1650         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1651                 be_emit_cstring("\txorpd ");
1652                 emit_register(in1, NULL);
1653                 be_emit_cstring(", ");
1654                 emit_register(in0, NULL);
1655                 be_emit_finish_line_gas(NULL);
1656
1657                 be_emit_cstring("\txorpd ");
1658                 emit_register(in0, NULL);
1659                 be_emit_cstring(", ");
1660                 emit_register(in1, NULL);
1661                 be_emit_finish_line_gas(NULL);
1662
1663                 be_emit_cstring("\txorpd ");
1664                 emit_register(in1, NULL);
1665                 be_emit_cstring(", ");
1666                 emit_register(in0, NULL);
1667                 be_emit_finish_line_gas(node);
1668         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1669                 /* is a NOP */
1670         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1671                 /* is a NOP */
1672         } else {
1673                 panic("unexpected register class in be_Perm (%+F)\n", node);
1674         }
1675 }
1676
1677 /**
1678  * Emits code for Constant loading.
1679  */
1680 static void emit_ia32_Const(const ir_node *node)
1681 {
1682         be_emit_cstring("\tmovl ");
1683         emit_ia32_Immediate(node);
1684         be_emit_cstring(", ");
1685         ia32_emit_dest_register(node, 0);
1686
1687         be_emit_finish_line_gas(node);
1688 }
1689
1690 /**
1691  * Emits code to load the TLS base
1692  */
1693 static void emit_ia32_LdTls(const ir_node *node)
1694 {
1695         be_emit_cstring("\tmovl %gs:0, ");
1696         ia32_emit_dest_register(node, 0);
1697         be_emit_finish_line_gas(node);
1698 }
1699
1700 /* helper function for emit_ia32_Minus64Bit */
1701 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1702 {
1703         be_emit_cstring("\tmovl ");
1704         emit_register(src, NULL);
1705         be_emit_cstring(", ");
1706         emit_register(dst, NULL);
1707         be_emit_finish_line_gas(node);
1708 }
1709
1710 /* helper function for emit_ia32_Minus64Bit */
1711 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1712 {
1713         be_emit_cstring("\tnegl ");
1714         emit_register(reg, NULL);
1715         be_emit_finish_line_gas(node);
1716 }
1717
1718 /* helper function for emit_ia32_Minus64Bit */
1719 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1720 {
1721         be_emit_cstring("\tsbbl $0, ");
1722         emit_register(reg, NULL);
1723         be_emit_finish_line_gas(node);
1724 }
1725
1726 /* helper function for emit_ia32_Minus64Bit */
1727 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1728 {
1729         be_emit_cstring("\tsbbl ");
1730         emit_register(src, NULL);
1731         be_emit_cstring(", ");
1732         emit_register(dst, NULL);
1733         be_emit_finish_line_gas(node);
1734 }
1735
1736 /* helper function for emit_ia32_Minus64Bit */
1737 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1738 {
1739         be_emit_cstring("\txchgl ");
1740         emit_register(src, NULL);
1741         be_emit_cstring(", ");
1742         emit_register(dst, NULL);
1743         be_emit_finish_line_gas(node);
1744 }
1745
1746 /* helper function for emit_ia32_Minus64Bit */
1747 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1748 {
1749         be_emit_cstring("\txorl ");
1750         emit_register(reg, NULL);
1751         be_emit_cstring(", ");
1752         emit_register(reg, NULL);
1753         be_emit_finish_line_gas(node);
1754 }
1755
1756 static void emit_ia32_Minus64Bit(const ir_node *node)
1757 {
1758         const arch_register_t *in_lo  = get_in_reg(node, 0);
1759         const arch_register_t *in_hi  = get_in_reg(node, 1);
1760         const arch_register_t *out_lo = get_out_reg(node, 0);
1761         const arch_register_t *out_hi = get_out_reg(node, 1);
1762
1763         if (out_lo == in_lo) {
1764                 if (out_hi != in_hi) {
1765                         /* a -> a, b -> d */
1766                         goto zero_neg;
1767                 } else {
1768                         /* a -> a, b -> b */
1769                         goto normal_neg;
1770                 }
1771         } else if (out_lo == in_hi) {
1772                 if (out_hi == in_lo) {
1773                         /* a -> b, b -> a */
1774                         emit_xchg(node, in_lo, in_hi);
1775                         goto normal_neg;
1776                 } else {
1777                         /* a -> b, b -> d */
1778                         emit_mov(node, in_hi, out_hi);
1779                         emit_mov(node, in_lo, out_lo);
1780                         goto normal_neg;
1781                 }
1782         } else {
1783                 if (out_hi == in_lo) {
1784                         /* a -> c, b -> a */
1785                         emit_mov(node, in_lo, out_lo);
1786                         goto zero_neg;
1787                 } else if (out_hi == in_hi) {
1788                         /* a -> c, b -> b */
1789                         emit_mov(node, in_lo, out_lo);
1790                         goto normal_neg;
1791                 } else {
1792                         /* a -> c, b -> d */
1793                         emit_mov(node, in_lo, out_lo);
1794                         goto zero_neg;
1795                 }
1796         }
1797
1798 normal_neg:
1799         emit_neg( node, out_hi);
1800         emit_neg( node, out_lo);
1801         emit_sbb0(node, out_hi);
1802         return;
1803
1804 zero_neg:
1805         emit_zero(node, out_hi);
1806         emit_neg( node, out_lo);
1807         emit_sbb( node, in_hi, out_hi);
1808 }
1809
1810 static void emit_be_Return(const ir_node *node)
1811 {
1812         unsigned pop;
1813         be_emit_cstring("\tret");
1814
1815         pop = be_Return_get_pop(node);
1816         if(pop > 0) {
1817                 be_emit_irprintf(" $%d", pop);
1818         }
1819         be_emit_finish_line_gas(node);
1820 }
1821
1822 static void emit_Nothing(const ir_node *node)
1823 {
1824         (void) node;
1825 }
1826
1827
1828 /***********************************************************************************
1829  *                  _          __                                             _
1830  *                 (_)        / _|                                           | |
1831  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1832  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1833  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1834  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1835  *
1836  ***********************************************************************************/
1837
1838 /**
1839  * Enters the emitter functions for handled nodes into the generic
1840  * pointer of an opcode.
1841  */
1842 static
1843 void ia32_register_emitters(void) {
1844
1845 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1846 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1847 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1848 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1849 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1850 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1851
1852         /* first clear the generic function pointer for all ops */
1853         clear_irp_opcodes_generic_func();
1854
1855         /* register all emitter functions defined in spec */
1856         ia32_register_spec_emitters();
1857
1858         /* other ia32 emitter functions */
1859         IA32_EMIT(Asm);
1860         IA32_EMIT(CMov);
1861         IA32_EMIT(IMul);
1862         IA32_EMIT(SwitchJmp);
1863         IA32_EMIT(CopyB);
1864         IA32_EMIT(CopyB_i);
1865         IA32_EMIT(Conv_I2FP);
1866         IA32_EMIT(Conv_FP2I);
1867         IA32_EMIT(Conv_FP2FP);
1868         IA32_EMIT(Conv_I2I);
1869         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1870         IA32_EMIT(Const);
1871         IA32_EMIT(LdTls);
1872         IA32_EMIT(Minus64Bit);
1873         IA32_EMIT(Jcc);
1874
1875         /* benode emitter */
1876         BE_EMIT(Call);
1877         BE_EMIT(IncSP);
1878         BE_EMIT(Copy);
1879         BE_EMIT(CopyKeep);
1880         BE_EMIT(Perm);
1881         BE_EMIT(Return);
1882
1883         BE_IGN(RegParams);
1884         BE_IGN(Barrier);
1885         BE_IGN(Keep);
1886
1887         /* firm emitter */
1888         EMIT(Jmp);
1889         IGN(Proj);
1890         IGN(Phi);
1891         IGN(Start);
1892
1893 #undef BE_EMIT
1894 #undef EMIT
1895 #undef IGN
1896 #undef IA32_EMIT2
1897 #undef IA32_EMIT
1898 }
1899
1900 static const char *last_name = NULL;
1901 static unsigned last_line = -1;
1902 static unsigned num = -1;
1903
1904 /**
1905  * Emit the debug support for node node.
1906  */
1907 static void ia32_emit_dbg(const ir_node *node)
1908 {
1909         dbg_info *db = get_irn_dbg_info(node);
1910         unsigned lineno;
1911         const char *fname = be_retrieve_dbg_info(db, &lineno);
1912
1913         if (! cg->birg->main_env->options->stabs_debug_support)
1914                 return;
1915
1916         if (fname) {
1917                 if (last_name != fname) {
1918                         last_line = -1;
1919                         be_dbg_include_begin(cg->birg->main_env->db_handle, fname);
1920                         last_name = fname;
1921                 }
1922                 if (last_line != lineno) {
1923                         char name[64];
1924
1925                         snprintf(name, sizeof(name), ".LM%u", ++num);
1926                         last_line = lineno;
1927                         be_dbg_line(cg->birg->main_env->db_handle, lineno, name);
1928                         be_emit_string(name);
1929                         be_emit_cstring(":\n");
1930                         be_emit_write_line();
1931                 }
1932         }
1933 }
1934
1935 typedef void (*emit_func_ptr) (const ir_node *);
1936
1937 /**
1938  * Emits code for a node.
1939  */
1940 static void ia32_emit_node(const ir_node *node)
1941 {
1942         ir_op *op = get_irn_op(node);
1943
1944         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1945
1946         if (op->ops.generic) {
1947                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1948                 ia32_emit_dbg(node);
1949                 (*func) (node);
1950         } else {
1951                 emit_Nothing(node);
1952                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1953                 abort();
1954         }
1955 }
1956
1957 /**
1958  * Emits gas alignment directives
1959  */
1960 static void ia32_emit_alignment(unsigned align, unsigned skip)
1961 {
1962         be_emit_cstring("\t.p2align ");
1963         be_emit_irprintf("%u,,%u\n", align, skip);
1964         be_emit_write_line();
1965 }
1966
1967 /**
1968  * Emits gas alignment directives for Functions depended on cpu architecture.
1969  */
1970 static void ia32_emit_align_func(cpu_support cpu)
1971 {
1972         unsigned align;
1973         unsigned maximum_skip;
1974
1975         switch (cpu) {
1976                 case arch_i386:
1977                         align = 2;
1978                         break;
1979                 case arch_i486:
1980                         align = 4;
1981                         break;
1982                 case arch_k6:
1983                         align = 5;
1984                         break;
1985                 default:
1986                         align = 4;
1987         }
1988         maximum_skip = (1 << align) - 1;
1989         ia32_emit_alignment(align, maximum_skip);
1990 }
1991
1992 /**
1993  * Emits gas alignment directives for Labels depended on cpu architecture.
1994  */
1995 static void ia32_emit_align_label(cpu_support cpu)
1996 {
1997         unsigned align; unsigned maximum_skip;
1998
1999         switch (cpu) {
2000                 case arch_i386:
2001                         align = 2;
2002                         break;
2003                 case arch_i486:
2004                         align = 4;
2005                         break;
2006                 case arch_k6:
2007                         align = 5;
2008                         break;
2009                 default:
2010                         align = 4;
2011         }
2012         maximum_skip = (1 << align) - 1;
2013         ia32_emit_alignment(align, maximum_skip);
2014 }
2015
2016 /**
2017  * Test wether a block should be aligned.
2018  * For cpus in the P4/Athlon class it is useful to align jump labels to
2019  * 16 bytes. However we should only do that if the alignment nops before the
2020  * label aren't executed more often than we have jumps to the label.
2021  */
2022 static int should_align_block(ir_node *block, ir_node *prev)
2023 {
2024         static const double DELTA = .0001;
2025         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
2026         double        block_freq;
2027         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
2028         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
2029         cpu_support   cpu       = isa->opt_arch;
2030         int           i, n_cfgpreds;
2031
2032         if(exec_freq == NULL)
2033                 return 0;
2034         if(cpu == arch_i386 || cpu == arch_i486)
2035                 return 0;
2036
2037         block_freq = get_block_execfreq(exec_freq, block);
2038         if(block_freq < DELTA)
2039                 return 0;
2040
2041         n_cfgpreds = get_Block_n_cfgpreds(block);
2042         for(i = 0; i < n_cfgpreds; ++i) {
2043                 ir_node *pred      = get_Block_cfgpred_block(block, i);
2044                 double   pred_freq = get_block_execfreq(exec_freq, pred);
2045
2046                 if(pred == prev) {
2047                         prev_freq += pred_freq;
2048                 } else {
2049                         jmp_freq  += pred_freq;
2050                 }
2051         }
2052
2053         if(prev_freq < DELTA && !(jmp_freq < DELTA))
2054                 return 1;
2055
2056         jmp_freq /= prev_freq;
2057
2058         switch (cpu) {
2059                 case arch_athlon:
2060                 case arch_athlon_64:
2061                 case arch_k6:
2062                         return jmp_freq > 3;
2063                 default:
2064                         return jmp_freq > 2;
2065         }
2066 }
2067
2068 static void ia32_emit_block_header(ir_node *block, ir_node *prev)
2069 {
2070         int           n_cfgpreds;
2071         int           need_label;
2072         int           i, arity;
2073         ir_exec_freq  *exec_freq = cg->birg->exec_freq;
2074
2075         n_cfgpreds = get_Block_n_cfgpreds(block);
2076         need_label = (n_cfgpreds != 0);
2077
2078         if (should_align_block(block, prev)) {
2079                 assert(need_label);
2080                 ia32_emit_align_label(isa->opt_arch);
2081         }
2082
2083         if(need_label) {
2084                 ia32_emit_block_name(block);
2085                 be_emit_char(':');
2086
2087                 be_emit_pad_comment();
2088                 be_emit_cstring("   /* preds:");
2089
2090                 /* emit list of pred blocks in comment */
2091                 arity = get_irn_arity(block);
2092                 for (i = 0; i < arity; ++i) {
2093                         ir_node *predblock = get_Block_cfgpred_block(block, i);
2094                         be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2095                 }
2096         } else {
2097                 be_emit_cstring("\t/* ");
2098                 ia32_emit_block_name(block);
2099                 be_emit_cstring(": ");
2100         }
2101         if (exec_freq != NULL) {
2102                 be_emit_irprintf(" freq: %f",
2103                                  get_block_execfreq(exec_freq, block));
2104         }
2105         be_emit_cstring(" */\n");
2106         be_emit_write_line();
2107 }
2108
2109 /**
2110  * Walks over the nodes in a block connected by scheduling edges
2111  * and emits code for each node.
2112  */
2113 static void ia32_gen_block(ir_node *block, ir_node *last_block)
2114 {
2115         const ir_node *node;
2116
2117         ia32_emit_block_header(block, last_block);
2118
2119         /* emit the contents of the block */
2120         ia32_emit_dbg(block);
2121         sched_foreach(block, node) {
2122                 ia32_emit_node(node);
2123         }
2124 }
2125
2126 /**
2127  * Emits code for function start.
2128  */
2129 static void ia32_emit_func_prolog(ir_graph *irg)
2130 {
2131         ir_entity  *irg_ent  = get_irg_entity(irg);
2132         const char *irg_name = get_entity_ld_name(irg_ent);
2133         cpu_support cpu      = isa->opt_arch;
2134         const be_irg_t *birg = cg->birg;
2135
2136         /* write the begin line (used by scripts processing the assembler... */
2137         be_emit_write_line();
2138         be_emit_cstring("# -- Begin  ");
2139         be_emit_string(irg_name);
2140         be_emit_char('\n');
2141         be_emit_write_line();
2142
2143         be_gas_emit_switch_section(GAS_SECTION_TEXT);
2144         be_dbg_method_begin(birg->main_env->db_handle, irg_ent, be_abi_get_stack_layout(birg->abi));
2145         ia32_emit_align_func(cpu);
2146         if (get_entity_visibility(irg_ent) == visibility_external_visible) {
2147                 be_emit_cstring(".global ");
2148                 be_emit_string(irg_name);
2149                 be_emit_char('\n');
2150                 be_emit_write_line();
2151         }
2152         ia32_emit_function_object(irg_name);
2153         be_emit_string(irg_name);
2154         be_emit_cstring(":\n");
2155         be_emit_write_line();
2156 }
2157
2158 /**
2159  * Emits code for function end
2160  */
2161 static void ia32_emit_func_epilog(ir_graph *irg)
2162 {
2163         const char     *irg_name = get_entity_ld_name(get_irg_entity(irg));
2164         const be_irg_t *birg     = cg->birg;
2165
2166         ia32_emit_function_size(irg_name);
2167         be_dbg_method_end(birg->main_env->db_handle);
2168
2169         be_emit_cstring("# -- End  ");
2170         be_emit_string(irg_name);
2171         be_emit_char('\n');
2172         be_emit_write_line();
2173
2174         be_emit_char('\n');
2175         be_emit_write_line();
2176 }
2177
2178 /**
2179  * Block-walker:
2180  * Sets labels for control flow nodes (jump target)
2181  */
2182 static void ia32_gen_labels(ir_node *block, void *data)
2183 {
2184         ir_node *pred;
2185         int n = get_Block_n_cfgpreds(block);
2186         (void) data;
2187
2188         for (n--; n >= 0; n--) {
2189                 pred = get_Block_cfgpred(block, n);
2190                 set_irn_link(pred, block);
2191         }
2192 }
2193
2194 /**
2195  * Emit an exception label if the current instruction can fail.
2196  */
2197 void ia32_emit_exc_label(const ir_node *node)
2198 {
2199         if (get_ia32_exc_label(node)) {
2200                 be_emit_irprintf(".EXL%u\n", 0);
2201                 be_emit_write_line();
2202         }
2203 }
2204
2205 /**
2206  * Main driver. Emits the code for one routine.
2207  */
2208 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2209 {
2210         ir_node *block;
2211         ir_node *last_block = NULL;
2212         int i, n;
2213
2214         cg       = ia32_cg;
2215         isa      = (const ia32_isa_t*) cg->arch_env->isa;
2216         arch_env = cg->arch_env;
2217
2218         ia32_register_emitters();
2219
2220         ia32_emit_func_prolog(irg);
2221         irg_block_walk_graph(irg, ia32_gen_labels, NULL, NULL);
2222
2223         n = ARR_LEN(cg->blk_sched);
2224         for (i = 0; i < n;) {
2225                 ir_node *next_bl;
2226
2227                 block   = cg->blk_sched[i];
2228                 ++i;
2229                 next_bl = i < n ? cg->blk_sched[i] : NULL;
2230
2231                 /* set here the link. the emitter expects to find the next block here */
2232                 set_irn_link(block, next_bl);
2233                 ia32_gen_block(block, last_block);
2234                 last_block = block;
2235         }
2236
2237         ia32_emit_func_epilog(irg);
2238 }
2239
2240 void ia32_init_emitter(void)
2241 {
2242         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
2243 }