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