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