backend: created a (not so nice) macro to iterate over all values defined by an instr...
[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  * Summary table for x86 floatingpoint compares:
27  *   pnc_Eq  => !P && E
28  *   pnc_Lt  => !P && B
29  *   pnc_Le  => !P && BE
30  *   pnc_Gt  => A
31  *   pnc_Ge  => AE
32  *   pnc_Lg  => P || NE
33  *   pnc_Leg => NP  (ordered)
34  *   pnc_Uo  => P
35  *   pnc_Ue  => E
36  *   pnc_Ul  => B
37  *   pnc_Ule => BE
38  *   pnc_Ug  => P || A
39  *   pnc_Uge => P || AE
40  *   pnc_Ne  => NE
41  */
42 #include "config.h"
43
44 #include <limits.h>
45
46 #include "xmalloc.h"
47 #include "tv.h"
48 #include "iredges.h"
49 #include "debug.h"
50 #include "irgwalk.h"
51 #include "irprintf.h"
52 #include "irop_t.h"
53 #include "irargs_t.h"
54 #include "irprog_t.h"
55 #include "iredges_t.h"
56 #include "irtools.h"
57 #include "execfreq.h"
58 #include "error.h"
59 #include "raw_bitset.h"
60 #include "dbginfo.h"
61 #include "lc_opts.h"
62
63 #include "../besched.h"
64 #include "../benode.h"
65 #include "../beabi.h"
66 #include "../be_dbgout.h"
67 #include "../beemitter.h"
68 #include "../begnuas.h"
69 #include "../beirg.h"
70 #include "../be_dbgout.h"
71
72 #include "ia32_emitter.h"
73 #include "ia32_common_transform.h"
74 #include "gen_ia32_emitter.h"
75 #include "gen_ia32_regalloc_if.h"
76 #include "ia32_nodes_attr.h"
77 #include "ia32_new_nodes.h"
78 #include "ia32_map_regs.h"
79 #include "ia32_architecture.h"
80 #include "bearch_ia32_t.h"
81
82 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
83
84 #define SNPRINTF_BUF_LEN 128
85
86 static const ia32_isa_t *isa;
87 static ia32_code_gen_t  *cg;
88 static char              pic_base_label[128];
89 static ir_label_t        exc_label_id;
90 static int               mark_spill_reload = 0;
91 static int               do_pic;
92
93 /** Return the next block in Block schedule */
94 static ir_node *get_prev_block_sched(const ir_node *block)
95 {
96         return get_irn_link(block);
97 }
98
99 /** Checks if the current block is a fall-through target. */
100 static int is_fallthrough(const ir_node *cfgpred)
101 {
102         ir_node *pred;
103
104         if (!is_Proj(cfgpred))
105                 return 1;
106         pred = get_Proj_pred(cfgpred);
107         if (is_ia32_SwitchJmp(pred))
108                 return 0;
109
110         return 1;
111 }
112
113 /**
114  * returns non-zero if the given block needs a label
115  * because of being a jump-target (and not a fall-through)
116  */
117 static int block_needs_label(const ir_node *block)
118 {
119         int need_label = 1;
120         int  n_cfgpreds = get_Block_n_cfgpreds(block);
121
122         if (has_Block_entity(block))
123                 return 1;
124
125         if (n_cfgpreds == 0) {
126                 need_label = 0;
127         } else if (n_cfgpreds == 1) {
128                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
129                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
130
131                 if (get_prev_block_sched(block) == cfgpred_block
132                                 && is_fallthrough(cfgpred)) {
133                         need_label = 0;
134                 }
135         }
136
137         return need_label;
138 }
139
140 /**
141  * Returns the register at in position pos.
142  */
143 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
144 {
145         ir_node               *op;
146         const arch_register_t *reg = NULL;
147
148         assert(get_irn_arity(irn) > pos && "Invalid IN position");
149
150         /* The out register of the operator at position pos is the
151            in register we need. */
152         op = get_irn_n(irn, pos);
153
154         reg = arch_get_irn_register(op);
155
156         assert(reg && "no in register found");
157
158         if (reg == &ia32_gp_regs[REG_GP_NOREG])
159                 panic("trying to emit noreg for %+F input %d", irn, pos);
160
161         return reg;
162 }
163
164 /**
165  * Returns the register at out position pos.
166  */
167 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
168 {
169         ir_node               *proj;
170         const arch_register_t *reg = NULL;
171
172         /* 1st case: irn is not of mode_T, so it has only                 */
173         /*           one OUT register -> good                             */
174         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
175         /*           Proj with the corresponding projnum for the register */
176
177         if (get_irn_mode(irn) != mode_T) {
178                 assert(pos == 0);
179                 reg = arch_get_irn_register(irn);
180         } else if (is_ia32_irn(irn)) {
181                 reg = arch_irn_get_register(irn, pos);
182         } else {
183                 const ir_edge_t *edge;
184
185                 foreach_out_edge(irn, edge) {
186                         proj = get_edge_src_irn(edge);
187                         assert(is_Proj(proj) && "non-Proj from mode_T node");
188                         if (get_Proj_proj(proj) == pos) {
189                                 reg = arch_get_irn_register(proj);
190                                 break;
191                         }
192                 }
193         }
194
195         assert(reg && "no out register found");
196         return reg;
197 }
198
199 /**
200  * Add a number to a prefix. This number will not be used a second time.
201  */
202 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
203 {
204         static unsigned long id = 0;
205         snprintf(buf, buflen, "%s%s%lu", be_gas_get_private_prefix(), prefix, ++id);
206         return buf;
207 }
208
209
210 /**
211  * Emit the name of the 8bit low register
212  */
213 static void emit_8bit_register(const arch_register_t *reg)
214 {
215         const char *reg_name = arch_register_get_name(reg);
216
217         be_emit_char('%');
218         be_emit_char(reg_name[1]);
219         be_emit_char('l');
220 }
221
222 /**
223  * Emit the name of the 8bit high register
224  */
225 static void emit_8bit_register_high(const arch_register_t *reg)
226 {
227         const char *reg_name = arch_register_get_name(reg);
228
229         be_emit_char('%');
230         be_emit_char(reg_name[1]);
231         be_emit_char('h');
232 }
233
234 static void emit_16bit_register(const arch_register_t *reg)
235 {
236         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
237
238         be_emit_char('%');
239         be_emit_string(reg_name);
240 }
241
242 /**
243  * emit a register, possible shortened by a mode
244  *
245  * @param reg   the register
246  * @param mode  the mode of the register or NULL for full register
247  */
248 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
249 {
250         const char *reg_name;
251
252         if (mode != NULL) {
253                 int size = get_mode_size_bits(mode);
254                 switch (size) {
255                         case  8: emit_8bit_register(reg);  return;
256                         case 16: emit_16bit_register(reg); return;
257                 }
258                 assert(mode_is_float(mode) || size == 32);
259         }
260
261         reg_name = arch_register_get_name(reg);
262
263         be_emit_char('%');
264         be_emit_string(reg_name);
265 }
266
267 void ia32_emit_source_register(const ir_node *node, int pos)
268 {
269         const arch_register_t *reg = get_in_reg(node, pos);
270
271         emit_register(reg, NULL);
272 }
273
274 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
275 {
276         be_gas_emit_entity(entity);
277
278         if (get_entity_owner(entity) == get_tls_type()) {
279                 if (get_entity_visibility(entity) == ir_visibility_external) {
280                         be_emit_cstring("@INDNTPOFF");
281                 } else {
282                         be_emit_cstring("@NTPOFF");
283                 }
284         }
285
286         if (do_pic && !no_pic_adjust) {
287                 be_emit_char('-');
288                 be_emit_string(pic_base_label);
289         }
290 }
291
292 static void emit_ia32_Immediate_no_prefix(const ir_node *node)
293 {
294         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
295
296         if (attr->symconst != NULL) {
297                 if (attr->sc_sign)
298                         be_emit_char('-');
299                 ia32_emit_entity(attr->symconst, attr->no_pic_adjust);
300         }
301         if (attr->symconst == NULL || attr->offset != 0) {
302                 if (attr->symconst != NULL) {
303                         be_emit_irprintf("%+d", attr->offset);
304                 } else {
305                         be_emit_irprintf("0x%X", attr->offset);
306                 }
307         }
308 }
309
310 static void emit_ia32_Immediate(const ir_node *node)
311 {
312         be_emit_char('$');
313         emit_ia32_Immediate_no_prefix(node);
314 }
315
316 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
317 {
318         const arch_register_t *reg;
319         const ir_node         *in = get_irn_n(node, pos);
320         if (is_ia32_Immediate(in)) {
321                 emit_ia32_Immediate(in);
322                 return;
323         }
324
325         reg = get_in_reg(node, pos);
326         emit_8bit_register(reg);
327 }
328
329 void ia32_emit_8bit_high_source_register(const ir_node *node, int pos)
330 {
331         const arch_register_t *reg = get_in_reg(node, pos);
332         emit_8bit_register_high(reg);
333 }
334
335 void ia32_emit_16bit_source_register_or_immediate(const ir_node *node, int pos)
336 {
337         const arch_register_t *reg;
338         const ir_node         *in = get_irn_n(node, pos);
339         if (is_ia32_Immediate(in)) {
340                 emit_ia32_Immediate(in);
341                 return;
342         }
343
344         reg = get_in_reg(node, pos);
345         emit_16bit_register(reg);
346 }
347
348 void ia32_emit_dest_register(const ir_node *node, int pos)
349 {
350         const arch_register_t *reg  = get_out_reg(node, pos);
351
352         emit_register(reg, NULL);
353 }
354
355 void ia32_emit_dest_register_size(const ir_node *node, int pos)
356 {
357         const arch_register_t *reg  = get_out_reg(node, pos);
358
359         emit_register(reg, get_ia32_ls_mode(node));
360 }
361
362 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
363 {
364         const arch_register_t *reg  = get_out_reg(node, pos);
365
366         emit_register(reg, mode_Bu);
367 }
368
369 void ia32_emit_x87_register(const ir_node *node, int pos)
370 {
371         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
372
373         assert(pos < 3);
374         be_emit_char('%');
375         be_emit_string(attr->x87[pos]->name);
376 }
377
378 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
379 {
380         assert(mode_is_int(mode) || mode_is_reference(mode));
381         switch (get_mode_size_bits(mode)) {
382                 case 8:  be_emit_char('b');     return;
383                 case 16: be_emit_char('w');     return;
384                 case 32: be_emit_char('l');     return;
385                 /* gas docu says q is the suffix but gcc, objdump and icc use ll
386                  * apparently */
387                 case 64: be_emit_cstring("ll"); return;
388         }
389         panic("Can't output mode_suffix for %+F", mode);
390 }
391
392 void ia32_emit_mode_suffix(const ir_node *node)
393 {
394         ir_mode *mode = get_ia32_ls_mode(node);
395         if (mode == NULL)
396                 mode = mode_Iu;
397
398         ia32_emit_mode_suffix_mode(mode);
399 }
400
401 void ia32_emit_x87_mode_suffix(const ir_node *node)
402 {
403         ir_mode *mode;
404
405         /* we only need to emit the mode on address mode */
406         if (get_ia32_op_type(node) == ia32_Normal)
407                 return;
408
409         mode = get_ia32_ls_mode(node);
410         assert(mode != NULL);
411
412         if (mode_is_float(mode)) {
413                 switch (get_mode_size_bits(mode)) {
414                         case  32: be_emit_char('s'); return;
415                         case  64: be_emit_char('l'); return;
416                         /* long doubles have different sizes due to alignment on different
417                          * platforms. */
418                         case  80:
419                         case  96:
420                         case 128: be_emit_char('t'); return;
421                 }
422         } else {
423                 assert(mode_is_int(mode) || mode_is_reference(mode));
424                 switch (get_mode_size_bits(mode)) {
425                         case 16: be_emit_char('s');     return;
426                         case 32: be_emit_char('l');     return;
427                         /* gas docu says q is the suffix but gcc, objdump and icc use ll
428                          * apparently */
429                         case 64: be_emit_cstring("ll"); return;
430                 }
431         }
432         panic("Can't output mode_suffix for %+F", mode);
433 }
434
435 static char get_xmm_mode_suffix(ir_mode *mode)
436 {
437         assert(mode_is_float(mode));
438         switch (get_mode_size_bits(mode)) {
439         case 32: return 's';
440         case 64: return 'd';
441         default: panic("Invalid XMM mode");
442         }
443 }
444
445 void ia32_emit_xmm_mode_suffix(const ir_node *node)
446 {
447         ir_mode *mode = get_ia32_ls_mode(node);
448         assert(mode != NULL);
449         be_emit_char('s');
450         be_emit_char(get_xmm_mode_suffix(mode));
451 }
452
453 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
454 {
455         ir_mode *mode = get_ia32_ls_mode(node);
456         assert(mode != NULL);
457         be_emit_char(get_xmm_mode_suffix(mode));
458 }
459
460 void ia32_emit_extend_suffix(const ir_node *node)
461 {
462         ir_mode *mode = get_ia32_ls_mode(node);
463         if (get_mode_size_bits(mode) == 32)
464                 return;
465         be_emit_char(mode_is_signed(mode) ? 's' : 'z');
466         ia32_emit_mode_suffix_mode(mode);
467 }
468
469 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
470 {
471         ir_node *in = get_irn_n(node, pos);
472         if (is_ia32_Immediate(in)) {
473                 emit_ia32_Immediate(in);
474         } else {
475                 const ir_mode         *mode = get_ia32_ls_mode(node);
476                 const arch_register_t *reg  = get_in_reg(node, pos);
477                 emit_register(reg, mode);
478         }
479 }
480
481 /**
482  * Returns the target block for a control flow node.
483  */
484 static ir_node *get_cfop_target_block(const ir_node *irn)
485 {
486         assert(get_irn_mode(irn) == mode_X);
487         return get_irn_link(irn);
488 }
489
490 /**
491  * Emits the target label for a control flow node.
492  */
493 static void ia32_emit_cfop_target(const ir_node *node)
494 {
495         ir_node *block = get_cfop_target_block(node);
496         be_gas_emit_block_name(block);
497 }
498
499 /*
500  * positive conditions for signed compares
501  */
502 static const char *const cmp2condition_s[] = {
503         NULL, /* always false */
504         "e",  /* == */
505         "l",  /* <  */
506         "le", /* <= */
507         "g",  /* >  */
508         "ge", /* >= */
509         "ne", /* != */
510         NULL  /* always true */
511 };
512
513 /*
514  * positive conditions for unsigned compares
515  */
516 static const char *const cmp2condition_u[] = {
517         NULL, /* always false */
518         "e",  /* == */
519         "b",  /* <  */
520         "be", /* <= */
521         "a",  /* >  */
522         "ae", /* >= */
523         "ne", /* != */
524         NULL  /* always true */
525 };
526
527 /**
528  * Emit the suffix for a compare instruction.
529  */
530 static void ia32_emit_cmp_suffix(int pnc)
531 {
532         const char *str;
533
534         if (pnc == ia32_pn_Cmp_parity) {
535                 be_emit_char('p');
536                 return;
537         }
538
539         if (pnc & ia32_pn_Cmp_float || pnc & ia32_pn_Cmp_unsigned) {
540                 str = cmp2condition_u[pnc & 7];
541         } else {
542                 str = cmp2condition_s[pnc & 7];
543         }
544
545         be_emit_string(str);
546 }
547
548 typedef enum ia32_emit_mod_t {
549         EMIT_RESPECT_LS   = 1U << 0,
550         EMIT_ALTERNATE_AM = 1U << 1,
551         EMIT_LONG         = 1U << 2,
552         EMIT_HIGH_REG     = 1U << 3,
553         EMIT_LOW_REG      = 1U << 4
554 } ia32_emit_mod_t;
555
556 /**
557  * Emits address mode.
558  */
559 void ia32_emit_am(const ir_node *node)
560 {
561         ir_entity *ent       = get_ia32_am_sc(node);
562         int        offs      = get_ia32_am_offs_int(node);
563         ir_node   *base      = get_irn_n(node, n_ia32_base);
564         int        has_base  = !is_ia32_NoReg_GP(base);
565         ir_node   *index     = get_irn_n(node, n_ia32_index);
566         int        has_index = !is_ia32_NoReg_GP(index);
567
568         /* just to be sure... */
569         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
570
571         /* emit offset */
572         if (ent != NULL) {
573                 const ia32_attr_t *attr = get_ia32_attr_const(node);
574                 if (is_ia32_am_sc_sign(node))
575                         be_emit_char('-');
576                 ia32_emit_entity(ent, attr->data.am_sc_no_pic_adjust);
577         }
578
579         /* also handle special case if nothing is set */
580         if (offs != 0 || (ent == NULL && !has_base && !has_index)) {
581                 if (ent != NULL) {
582                         be_emit_irprintf("%+d", offs);
583                 } else {
584                         be_emit_irprintf("%d", offs);
585                 }
586         }
587
588         if (has_base || has_index) {
589                 be_emit_char('(');
590
591                 /* emit base */
592                 if (has_base) {
593                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
594                         emit_register(reg, NULL);
595                 }
596
597                 /* emit index + scale */
598                 if (has_index) {
599                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
600                         int scale;
601                         be_emit_char(',');
602                         emit_register(reg, NULL);
603
604                         scale = get_ia32_am_scale(node);
605                         if (scale > 0) {
606                                 be_emit_irprintf(",%d", 1 << scale);
607                         }
608                 }
609                 be_emit_char(')');
610         }
611 }
612
613 /**
614  * fmt  parameter               output
615  * ---- ----------------------  ---------------------------------------------
616  * %%                           %
617  * %AM  <node>                  address mode of the node
618  * %AR  const arch_register_t*  address mode of the node or register
619  * %ASx <node>                  address mode of the node or source register x
620  * %Dx  <node>                  destination register x
621  * %I   <node>                  immediate of the node
622  * %L   <node>                  control flow target of the node
623  * %M   <node>                  mode suffix of the node
624  * %P   int                     condition code
625  * %R   const arch_register_t*  register
626  * %Sx  <node>                  source register x
627  * %s   const char*             string
628  * %u   unsigned int            unsigned int
629  * %d   signed int              signed int
630  *
631  * x starts at 0
632  * # modifier for %ASx, %D, %R, and %S uses ls mode of node to alter register width
633  * * modifier does not prefix immediates with $, but AM with *
634  * l modifier for %lu and %ld
635  * > modifier to output high 8bit register (ah, bh)
636  * < modifier to output low 8bit register (al, bl)
637  */
638 static void ia32_emitf(const ir_node *node, const char *fmt, ...)
639 {
640         va_list ap;
641         va_start(ap, fmt);
642
643         for (;;) {
644                 const char      *start = fmt;
645                 ia32_emit_mod_t  mod   = 0;
646
647                 while (*fmt != '%' && *fmt != '\n' && *fmt != '\0')
648                         ++fmt;
649                 if (fmt != start) {
650                         be_emit_string_len(start, fmt - start);
651                 }
652
653                 if (*fmt == '\n') {
654                         be_emit_finish_line_gas(node);
655                         ++fmt;
656                         if (*fmt == '\0')
657                                 break;
658                         continue;
659                 }
660
661                 if (*fmt == '\0')
662                         break;
663
664                 ++fmt;
665                 for (;;) {
666                         switch (*fmt) {
667                         case '*': mod |= EMIT_ALTERNATE_AM; break;
668                         case '#': mod |= EMIT_RESPECT_LS;   break;
669                         case 'l': mod |= EMIT_LONG;         break;
670                         case '>': mod |= EMIT_HIGH_REG;     break;
671                         case '<': mod |= EMIT_LOW_REG;      break;
672                         default:
673                                 goto end_of_mods;
674                         }
675                         ++fmt;
676                 }
677 end_of_mods:
678
679                 switch (*fmt++) {
680                         case '%':
681                                 be_emit_char('%');
682                                 break;
683
684                         case 'A': {
685                                 switch (*fmt++) {
686 emit_AM:
687                                         case 'M':
688                                                 if (mod & EMIT_ALTERNATE_AM)
689                                                         be_emit_char('*');
690                                                 ia32_emit_am(node);
691                                                 break;
692
693                                         case 'R': {
694                                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
695                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
696                                                         goto emit_AM;
697                                                 } else {
698                                                         if (mod & EMIT_ALTERNATE_AM)
699                                                                 be_emit_char('*');
700                                                         emit_register(reg, NULL);
701                                                 }
702                                                 break;
703                                         }
704
705                                         case 'S':
706                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
707                                                         ++fmt;
708                                                         goto emit_AM;
709                                                 } else {
710                                                         assert(get_ia32_op_type(node) == ia32_Normal);
711                                                         goto emit_S;
712                                                 }
713                                                 break;
714
715                                         default: goto unknown;
716                                 }
717                                 break;
718                         }
719
720                         case 'D': {
721                                 unsigned               pos;
722                                 const arch_register_t *reg;
723
724                                 if (*fmt < '0' || '9' <= *fmt)
725                                         goto unknown;
726
727                                 pos = *fmt++ - '0';
728                                 reg = get_out_reg(node, pos);
729                                 emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
730                                 break;
731                         }
732
733                         case 'I':
734                                 if (!(mod & EMIT_ALTERNATE_AM))
735                                         be_emit_char('$');
736                                 emit_ia32_Immediate_no_prefix(node);
737                                 break;
738
739                         case 'L':
740                                 ia32_emit_cfop_target(node);
741                                 break;
742
743                         case 'M': {
744                                 ia32_emit_mode_suffix_mode(get_ia32_ls_mode(node));
745                                 break;
746                         }
747
748                         case 'P': {
749                                 int pnc = va_arg(ap, int);
750                                 ia32_emit_cmp_suffix(pnc);
751                                 break;
752                         }
753
754                         case 'R': {
755                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
756                                 if (mod & EMIT_HIGH_REG) {
757                                         emit_8bit_register_high(reg);
758                                 } else if (mod & EMIT_LOW_REG) {
759                                         emit_8bit_register(reg);
760                                 } else {
761                                         emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
762                                 }
763                                 break;
764                         }
765
766 emit_S:
767                         case 'S': {
768                                 unsigned       pos;
769                                 const ir_node *in;
770
771                                 if (*fmt < '0' || '9' <= *fmt)
772                                         goto unknown;
773
774                                 pos = *fmt++ - '0';
775                                 in  = get_irn_n(node, pos);
776                                 if (is_ia32_Immediate(in)) {
777                                         if (!(mod & EMIT_ALTERNATE_AM))
778                                                 be_emit_char('$');
779                                         emit_ia32_Immediate_no_prefix(in);
780                                 } else {
781                                         const arch_register_t *reg;
782
783                                         if (mod & EMIT_ALTERNATE_AM)
784                                                 be_emit_char('*');
785                                         reg = get_in_reg(node, pos);
786                                         emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
787                                 }
788                                 break;
789                         }
790
791                         case 's': {
792                                 const char *str = va_arg(ap, const char*);
793                                 be_emit_string(str);
794                                 break;
795                         }
796
797                         case 'u':
798                                 if (mod & EMIT_LONG) {
799                                         unsigned long num = va_arg(ap, unsigned long);
800                                         be_emit_irprintf("%lu", num);
801                                 } else {
802                                         unsigned num = va_arg(ap, unsigned);
803                                         be_emit_irprintf("%u", num);
804                                 }
805                                 break;
806
807                         case 'd':
808                                 if (mod & EMIT_LONG) {
809                                         long num = va_arg(ap, long);
810                                         be_emit_irprintf("%ld", num);
811                                 } else {
812                                         int num = va_arg(ap, int);
813                                         be_emit_irprintf("%d", num);
814                                 }
815                                 break;
816
817                         default:
818 unknown:
819                                 panic("unknown format conversion in ia32_emitf()");
820                 }
821         }
822
823         va_end(ap);
824 }
825
826 /**
827  * Emits registers and/or address mode of a binary operation.
828  */
829 void ia32_emit_binop(const ir_node *node)
830 {
831         if (is_ia32_Immediate(get_irn_n(node, n_ia32_binary_right))) {
832                 ia32_emitf(node, "%#S4, %#AS3");
833         } else {
834                 ia32_emitf(node, "%#AS4, %#S3");
835         }
836 }
837
838 /**
839  * Emits registers and/or address mode of a binary operation.
840  */
841 void ia32_emit_x87_binop(const ir_node *node)
842 {
843         switch (get_ia32_op_type(node)) {
844                 case ia32_Normal:
845                         {
846                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
847                                 const arch_register_t *in1      = x87_attr->x87[0];
848                                 const arch_register_t *in       = x87_attr->x87[1];
849                                 const arch_register_t *out      = x87_attr->x87[2];
850
851                                 if (out == NULL) {
852                                         out = in1;
853                                 } else if (out == in) {
854                                         in = in1;
855                                 }
856
857                                 be_emit_char('%');
858                                 be_emit_string(arch_register_get_name(in));
859                                 be_emit_cstring(", %");
860                                 be_emit_string(arch_register_get_name(out));
861                         }
862                         break;
863                 case ia32_AddrModeS:
864                         ia32_emit_am(node);
865                         break;
866                 case ia32_AddrModeD:
867                 default:
868                         assert(0 && "unsupported op type");
869         }
870 }
871
872 /**
873  * Emits registers and/or address mode of a unary operation.
874  */
875 void ia32_emit_unop(const ir_node *node, int pos)
876 {
877         char fmt[] = "%ASx";
878         fmt[3] = '0' + pos;
879         ia32_emitf(node, fmt);
880 }
881
882 static void emit_ia32_IMul(const ir_node *node)
883 {
884         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
885         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
886
887         /* do we need the 3-address form? */
888         if (is_ia32_NoReg_GP(left) ||
889                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
890                 ia32_emitf(node, "\timul%M %#S4, %#AS3, %#D0\n");
891         } else {
892                 ia32_emitf(node, "\timul%M %#AS4, %#S3\n");
893         }
894 }
895
896 /**
897  * walks up a tree of copies/perms/spills/reloads to find the original value
898  * that is moved around
899  */
900 static ir_node *find_original_value(ir_node *node)
901 {
902         if (irn_visited(node))
903                 return NULL;
904
905         mark_irn_visited(node);
906         if (be_is_Copy(node)) {
907                 return find_original_value(be_get_Copy_op(node));
908         } else if (be_is_CopyKeep(node)) {
909                 return find_original_value(be_get_CopyKeep_op(node));
910         } else if (is_Proj(node)) {
911                 ir_node *pred = get_Proj_pred(node);
912                 if (be_is_Perm(pred)) {
913                         return find_original_value(get_irn_n(pred, get_Proj_proj(node)));
914                 } else if (be_is_MemPerm(pred)) {
915                         return find_original_value(get_irn_n(pred, get_Proj_proj(node) + 1));
916                 } else if (is_ia32_Load(pred)) {
917                         return find_original_value(get_irn_n(pred, n_ia32_Load_mem));
918                 } else {
919                         return node;
920                 }
921         } else if (is_ia32_Store(node)) {
922                 return find_original_value(get_irn_n(node, n_ia32_Store_val));
923         } else if (is_Phi(node)) {
924                 int i, arity;
925                 arity = get_irn_arity(node);
926                 for (i = 0; i < arity; ++i) {
927                         ir_node *in  = get_irn_n(node, i);
928                         ir_node *res = find_original_value(in);
929
930                         if (res != NULL)
931                                 return res;
932                 }
933                 return NULL;
934         } else {
935                 return node;
936         }
937 }
938
939 static int determine_final_pnc(const ir_node *node, int flags_pos, int pnc)
940 {
941         ir_node           *flags = get_irn_n(node, flags_pos);
942         const ia32_attr_t *flags_attr;
943         flags = skip_Proj(flags);
944
945         if (is_ia32_Sahf(flags)) {
946                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
947                 if (!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
948                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
949                         inc_irg_visited(current_ir_graph);
950                         cmp = find_original_value(cmp);
951                         assert(cmp != NULL);
952                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
953                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
954                 }
955
956                 flags_attr = get_ia32_attr_const(cmp);
957                 if (flags_attr->data.ins_permuted)
958                         pnc = get_mirrored_pnc(pnc);
959                 pnc |= ia32_pn_Cmp_float;
960         } else if (is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
961                         || is_ia32_Fucompi(flags)) {
962                 flags_attr = get_ia32_attr_const(flags);
963
964                 if (flags_attr->data.ins_permuted)
965                         pnc = get_mirrored_pnc(pnc);
966                 pnc |= ia32_pn_Cmp_float;
967         } else {
968                 flags_attr = get_ia32_attr_const(flags);
969
970                 if (flags_attr->data.ins_permuted)
971                         pnc = get_mirrored_pnc(pnc);
972                 if (flags_attr->data.cmp_unsigned)
973                         pnc |= ia32_pn_Cmp_unsigned;
974         }
975
976         return pnc;
977 }
978
979 static pn_Cmp ia32_get_negated_pnc(pn_Cmp pnc)
980 {
981         ir_mode *mode = pnc & ia32_pn_Cmp_float ? mode_F : mode_Iu;
982         return get_negated_pnc(pnc, mode);
983 }
984
985 void ia32_emit_cmp_suffix_node(const ir_node *node, int flags_pos)
986 {
987         pn_Cmp pnc = get_ia32_condcode(node);
988         pnc = determine_final_pnc(node, flags_pos, pnc);
989
990         ia32_emit_cmp_suffix(pnc);
991 }
992
993 /**
994  * Emits an exception label for a given node.
995  */
996 static void ia32_emit_exc_label(const ir_node *node)
997 {
998         be_emit_string(be_gas_insn_label_prefix());
999         be_emit_irprintf("%lu", get_ia32_exc_label_id(node));
1000 }
1001
1002 /**
1003  * Returns the Proj with projection number proj and NOT mode_M
1004  */
1005 static ir_node *get_proj(const ir_node *node, long proj)
1006 {
1007         const ir_edge_t *edge;
1008         ir_node         *src;
1009
1010         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
1011
1012         foreach_out_edge(node, edge) {
1013                 src = get_edge_src_irn(edge);
1014
1015                 assert(is_Proj(src) && "Proj expected");
1016                 if (get_irn_mode(src) == mode_M)
1017                         continue;
1018
1019                 if (get_Proj_proj(src) == proj)
1020                         return src;
1021         }
1022         return NULL;
1023 }
1024
1025 static int can_be_fallthrough(const ir_node *node)
1026 {
1027         ir_node *target_block = get_cfop_target_block(node);
1028         ir_node *block        = get_nodes_block(node);
1029         return get_prev_block_sched(target_block) == block;
1030 }
1031
1032 /**
1033  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
1034  */
1035 static void emit_ia32_Jcc(const ir_node *node)
1036 {
1037         int            need_parity_label = 0;
1038         const ir_node *proj_true;
1039         const ir_node *proj_false;
1040         pn_Cmp         pnc = get_ia32_condcode(node);
1041
1042         pnc = determine_final_pnc(node, 0, pnc);
1043
1044         /* get both Projs */
1045         proj_true = get_proj(node, pn_ia32_Jcc_true);
1046         assert(proj_true && "Jcc without true Proj");
1047
1048         proj_false = get_proj(node, pn_ia32_Jcc_false);
1049         assert(proj_false && "Jcc without false Proj");
1050
1051         if (can_be_fallthrough(proj_true)) {
1052                 /* exchange both proj's so the second one can be omitted */
1053                 const ir_node *t = proj_true;
1054
1055                 proj_true  = proj_false;
1056                 proj_false = t;
1057                 pnc        = ia32_get_negated_pnc(pnc);
1058         }
1059
1060         if (pnc & ia32_pn_Cmp_float) {
1061                 /* Some floating point comparisons require a test of the parity flag,
1062                  * which indicates that the result is unordered */
1063                 switch (pnc & 0x0f) {
1064                 case pn_Cmp_Uo: {
1065                         ia32_emitf(proj_true, "\tjp %L\n");
1066                         break;
1067                 }
1068
1069                 case pn_Cmp_Leg:
1070                         ia32_emitf(proj_true, "\tjnp %L\n");
1071                         break;
1072
1073                 case pn_Cmp_Eq:
1074                 case pn_Cmp_Lt:
1075                 case pn_Cmp_Le:
1076                         /* we need a local label if the false proj is a fallthrough
1077                          * as the falseblock might have no label emitted then */
1078                         if (can_be_fallthrough(proj_false)) {
1079                                 need_parity_label = 1;
1080                                 ia32_emitf(proj_false, "\tjp 1f\n");
1081                         } else {
1082                                 ia32_emitf(proj_false, "\tjp %L\n");
1083                         }
1084                         goto emit_jcc;
1085
1086                 case pn_Cmp_Ug:
1087                 case pn_Cmp_Uge:
1088                 case pn_Cmp_Ne:
1089                         ia32_emitf(proj_true, "\tjp %L\n");
1090                         goto emit_jcc;
1091
1092                 default:
1093                         goto emit_jcc;
1094                 }
1095         } else {
1096 emit_jcc:
1097                 ia32_emitf(proj_true, "\tj%P %L\n", pnc);
1098         }
1099
1100         if (need_parity_label) {
1101                 ia32_emitf(NULL, "1:\n");
1102         }
1103
1104         /* the second Proj might be a fallthrough */
1105         if (can_be_fallthrough(proj_false)) {
1106                 ia32_emitf(proj_false, "\t/* fallthrough to %L */\n");
1107         } else {
1108                 ia32_emitf(proj_false, "\tjmp %L\n");
1109         }
1110 }
1111
1112 /**
1113  * Emits an ia32 Setcc. This is mostly easy but some floating point compares
1114  * are tricky.
1115  */
1116 static void emit_ia32_Setcc(const ir_node *node)
1117 {
1118         const arch_register_t *dreg = get_out_reg(node, pn_ia32_Setcc_res);
1119
1120         pn_Cmp pnc = get_ia32_condcode(node);
1121         pnc        = determine_final_pnc(node, n_ia32_Setcc_eflags, pnc);
1122         if (pnc & ia32_pn_Cmp_float) {
1123                 switch (pnc & 0x0f) {
1124                 case pn_Cmp_Uo:
1125                         ia32_emitf(node, "\tsetp %#R\n", dreg);
1126                         return;
1127
1128                 case pn_Cmp_Leg:
1129                         ia32_emitf(node, "\tsetnp %#R\n", dreg);
1130                         return;
1131
1132                 case pn_Cmp_Eq:
1133                 case pn_Cmp_Lt:
1134                 case pn_Cmp_Le:
1135                         ia32_emitf(node, "\tset%P %<R\n", pnc, dreg);
1136                         ia32_emitf(node, "\tsetnp %>R\n", dreg);
1137                         ia32_emitf(node, "\tandb %>R, %<R\n", dreg, dreg);
1138                         return;
1139
1140                 case pn_Cmp_Ug:
1141                 case pn_Cmp_Uge:
1142                 case pn_Cmp_Ne:
1143                         ia32_emitf(node, "\tset%P %<R\n", pnc, dreg);
1144                         ia32_emitf(node, "\tsetp %>R\n", dreg);
1145                         ia32_emitf(node, "\torb %>R, %<R\n", dreg, dreg);
1146                         return;
1147
1148                 default:
1149                         break;
1150                 }
1151         }
1152         ia32_emitf(node, "\tset%P %#R\n", pnc, dreg);
1153 }
1154
1155 static void emit_ia32_CMovcc(const ir_node *node)
1156 {
1157         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
1158         const arch_register_t *out          = arch_irn_get_register(node, pn_ia32_res);
1159         pn_Cmp                 pnc          = get_ia32_condcode(node);
1160         const arch_register_t *in_true;
1161         const arch_register_t *in_false;
1162
1163         pnc = determine_final_pnc(node, n_ia32_CMovcc_eflags, pnc);
1164         /* although you can't set ins_permuted in the constructor it might still
1165          * be set by memory operand folding
1166          * Permuting inputs of a cmov means the condition is negated!
1167          */
1168         if (attr->data.ins_permuted)
1169                 pnc = ia32_get_negated_pnc(pnc);
1170
1171         in_true  = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_true));
1172         in_false = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_false));
1173
1174         /* should be same constraint fullfilled? */
1175         if (out == in_false) {
1176                 /* yes -> nothing to do */
1177         } else if (out == in_true) {
1178                 const arch_register_t *tmp;
1179
1180                 assert(get_ia32_op_type(node) == ia32_Normal);
1181
1182                 pnc = ia32_get_negated_pnc(pnc);
1183
1184                 tmp      = in_true;
1185                 in_true  = in_false;
1186                 in_false = tmp;
1187         } else {
1188                 /* we need a mov */
1189                 ia32_emitf(node, "\tmovl %R, %R\n", in_false, out);
1190         }
1191
1192         /* TODO: handling of Nans isn't correct yet */
1193         if (pnc & ia32_pn_Cmp_float) {
1194                 switch (pnc & 0x0f) {
1195                 case pn_Cmp_Uo:
1196                 case pn_Cmp_Leg:
1197                 case pn_Cmp_Eq:
1198                 case pn_Cmp_Lt:
1199                 case pn_Cmp_Le:
1200                 case pn_Cmp_Ug:
1201                 case pn_Cmp_Uge:
1202                 case pn_Cmp_Ne:
1203                         panic("CMov with floatingpoint compare/parity not supported yet");
1204                 }
1205         }
1206
1207         ia32_emitf(node, "\tcmov%P %#AR, %#R\n", pnc, in_true, out);
1208 }
1209
1210
1211 /* jump table entry (target and corresponding number) */
1212 typedef struct _branch_t {
1213         ir_node *target;
1214         int      value;
1215 } branch_t;
1216
1217 /* jump table for switch generation */
1218 typedef struct _jmp_tbl_t {
1219         ir_node  *defProj;                 /**< default target */
1220         long      min_value;               /**< smallest switch case */
1221         long      max_value;               /**< largest switch case */
1222         long      num_branches;            /**< number of jumps */
1223         char      label[SNPRINTF_BUF_LEN]; /**< label of the jump table */
1224         branch_t *branches;                /**< jump array */
1225 } jmp_tbl_t;
1226
1227 /**
1228  * Compare two variables of type branch_t. Used to sort all switch cases
1229  */
1230 static int ia32_cmp_branch_t(const void *a, const void *b)
1231 {
1232         branch_t *b1 = (branch_t *)a;
1233         branch_t *b2 = (branch_t *)b;
1234
1235         if (b1->value <= b2->value)
1236                 return -1;
1237         else
1238                 return 1;
1239 }
1240
1241 static void generate_jump_table(jmp_tbl_t *tbl, const ir_node *node)
1242 {
1243         int                 i;
1244         long                pnc;
1245         long                default_pn;
1246         ir_node            *proj;
1247         const ir_edge_t    *edge;
1248
1249         /* fill the table structure */
1250         get_unique_label(tbl->label, SNPRINTF_BUF_LEN, "TBL_");
1251         tbl->defProj      = NULL;
1252         tbl->num_branches = get_irn_n_edges(node) - 1;
1253         tbl->branches     = XMALLOCNZ(branch_t, tbl->num_branches);
1254         tbl->min_value    = LONG_MAX;
1255         tbl->max_value    = LONG_MIN;
1256
1257         default_pn = get_ia32_condcode(node);
1258         i = 0;
1259         /* go over all proj's and collect them */
1260         foreach_out_edge(node, edge) {
1261                 proj = get_edge_src_irn(edge);
1262                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1263
1264                 pnc = get_Proj_proj(proj);
1265
1266                 /* check for default proj */
1267                 if (pnc == default_pn) {
1268                         assert(tbl->defProj == NULL && "found two default Projs at SwitchJmp");
1269                         tbl->defProj = proj;
1270                 } else {
1271                         tbl->min_value = pnc < tbl->min_value ? pnc : tbl->min_value;
1272                         tbl->max_value = pnc > tbl->max_value ? pnc : tbl->max_value;
1273
1274                         /* create branch entry */
1275                         tbl->branches[i].target = proj;
1276                         tbl->branches[i].value  = pnc;
1277                         ++i;
1278                 }
1279
1280         }
1281         assert(i == tbl->num_branches);
1282
1283         /* sort the branches by their number */
1284         qsort(tbl->branches, tbl->num_branches, sizeof(tbl->branches[0]), ia32_cmp_branch_t);
1285 }
1286
1287 /**
1288  * Emits code for a SwitchJmp (creates a jump table if
1289  * possible otherwise a cmp-jmp cascade). Port from
1290  * cggg ia32 backend
1291  */
1292 static void emit_ia32_SwitchJmp(const ir_node *node)
1293 {
1294         unsigned long       interval;
1295         int                 last_value, i;
1296         jmp_tbl_t           tbl;
1297
1298         /* fill the table structure */
1299         generate_jump_table(&tbl, node);
1300
1301         /* two-complement's magic make this work without overflow */
1302         interval = tbl.max_value - tbl.min_value;
1303
1304         /* emit the table */
1305         ia32_emitf(node,        "\tcmpl $%u, %S0\n", interval);
1306         ia32_emitf(tbl.defProj, "\tja %L\n");
1307
1308         if (tbl.num_branches > 1) {
1309                 /* create table */
1310                 ia32_emitf(node, "\tjmp *%s(,%S0,4)\n", tbl.label);
1311
1312                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1313                 ia32_emitf(NULL, "\t.align 4\n");
1314                 ia32_emitf(NULL, "%s:\n", tbl.label);
1315
1316                 last_value = tbl.branches[0].value;
1317                 for (i = 0; i != tbl.num_branches; ++i) {
1318                         while (last_value != tbl.branches[i].value) {
1319                                 ia32_emitf(tbl.defProj, ".long %L\n");
1320                                 ++last_value;
1321                         }
1322                         ia32_emitf(tbl.branches[i].target, ".long %L\n");
1323                         ++last_value;
1324                 }
1325                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1326         } else {
1327                 /* one jump is enough */
1328                 ia32_emitf(tbl.branches[0].target, "\tjmp %L\n");
1329         }
1330
1331         free(tbl.branches);
1332 }
1333
1334 /**
1335  * Emits code for a unconditional jump.
1336  */
1337 static void emit_ia32_Jmp(const ir_node *node)
1338 {
1339         ir_node *block;
1340
1341         /* for now, the code works for scheduled and non-schedules blocks */
1342         block = get_nodes_block(node);
1343
1344         /* we have a block schedule */
1345         if (can_be_fallthrough(node)) {
1346                 ia32_emitf(node, "\t/* fallthrough to %L */\n");
1347         } else {
1348                 ia32_emitf(node, "\tjmp %L\n");
1349         }
1350 }
1351
1352 /**
1353  * Emit an inline assembler operand.
1354  *
1355  * @param node  the ia32_ASM node
1356  * @param s     points to the operand (a %c)
1357  *
1358  * @return  pointer to the first char in s NOT in the current operand
1359  */
1360 static const char* emit_asm_operand(const ir_node *node, const char *s)
1361 {
1362         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1363         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1364                                                             ia32_attr);
1365         const arch_register_t *reg;
1366         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1367         const ia32_asm_reg_t  *asm_reg;
1368         const char            *reg_name;
1369         char                   c;
1370         char                   modifier = 0;
1371         int                    num      = -1;
1372         int                    p;
1373
1374         assert(*s == '%');
1375         c = *(++s);
1376
1377         /* parse modifiers */
1378         switch (c) {
1379         case 0:
1380                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %%\n", node);
1381                 be_emit_char('%');
1382                 return s + 1;
1383         case '%':
1384                 be_emit_char('%');
1385                 return s + 1;
1386         case 'w':
1387         case 'b':
1388         case 'h':
1389                 modifier = c;
1390                 ++s;
1391                 break;
1392         case '0':
1393         case '1':
1394         case '2':
1395         case '3':
1396         case '4':
1397         case '5':
1398         case '6':
1399         case '7':
1400         case '8':
1401         case '9':
1402                 break;
1403         default:
1404                 ir_fprintf(stderr,
1405                                 "Warning: asm text (%+F) contains unknown modifier '%c' for asm op\n",
1406                                 node, c);
1407                 ++s;
1408                 break;
1409         }
1410
1411         /* parse number */
1412         sscanf(s, "%d%n", &num, &p);
1413         if (num < 0) {
1414                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1415                            node);
1416                 return s;
1417         } else {
1418                 s += p;
1419         }
1420
1421         if (num < 0 || ARR_LEN(asm_regs) <= num) {
1422                 ir_fprintf(stderr,
1423                                 "Error: Custom assembler references invalid input/output (%+F)\n",
1424                                 node);
1425                 return s;
1426         }
1427         asm_reg = & asm_regs[num];
1428         assert(asm_reg->valid);
1429
1430         /* get register */
1431         if (asm_reg->use_input == 0) {
1432                 reg = get_out_reg(node, asm_reg->inout_pos);
1433         } else {
1434                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1435
1436                 /* might be an immediate value */
1437                 if (is_ia32_Immediate(pred)) {
1438                         emit_ia32_Immediate(pred);
1439                         return s;
1440                 }
1441                 reg = get_in_reg(node, asm_reg->inout_pos);
1442         }
1443         if (reg == NULL) {
1444                 ir_fprintf(stderr,
1445                                 "Warning: no register assigned for %d asm op (%+F)\n",
1446                                 num, node);
1447                 return s;
1448         }
1449
1450         if (asm_reg->memory) {
1451                 be_emit_char('(');
1452         }
1453
1454         /* emit it */
1455         if (modifier != 0) {
1456                 be_emit_char('%');
1457                 switch (modifier) {
1458                 case 'b':
1459                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1460                         break;
1461                 case 'h':
1462                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1463                         break;
1464                 case 'w':
1465                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1466                         break;
1467                 default:
1468                         panic("Invalid asm op modifier");
1469                 }
1470                 be_emit_string(reg_name);
1471         } else {
1472                 emit_register(reg, asm_reg->mode);
1473         }
1474
1475         if (asm_reg->memory) {
1476                 be_emit_char(')');
1477         }
1478
1479         return s;
1480 }
1481
1482 /**
1483  * Emits code for an ASM pseudo op.
1484  */
1485 static void emit_ia32_Asm(const ir_node *node)
1486 {
1487         const void            *gen_attr = get_irn_generic_attr_const(node);
1488         const ia32_asm_attr_t *attr
1489                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1490         ident                 *asm_text = attr->asm_text;
1491         const char            *s        = get_id_str(asm_text);
1492
1493         ia32_emitf(node, "#APP\t\n");
1494
1495         if (s[0] != '\t')
1496                 be_emit_char('\t');
1497
1498         while (*s != 0) {
1499                 if (*s == '%') {
1500                         s = emit_asm_operand(node, s);
1501                 } else {
1502                         be_emit_char(*s++);
1503                 }
1504         }
1505
1506         ia32_emitf(NULL, "\n#NO_APP\n");
1507 }
1508
1509
1510 /**
1511  * Emit movsb/w instructions to make mov count divideable by 4
1512  */
1513 static void emit_CopyB_prolog(unsigned size)
1514 {
1515         if (size & 1)
1516                 ia32_emitf(NULL, "\tmovsb\n");
1517         if (size & 2)
1518                 ia32_emitf(NULL, "\tmovsw\n");
1519 }
1520
1521 /**
1522  * Emit rep movsd instruction for memcopy.
1523  */
1524 static void emit_ia32_CopyB(const ir_node *node)
1525 {
1526         unsigned size = get_ia32_copyb_size(node);
1527
1528         emit_CopyB_prolog(size);
1529         ia32_emitf(node, "\trep movsd\n");
1530 }
1531
1532 /**
1533  * Emits unrolled memcopy.
1534  */
1535 static void emit_ia32_CopyB_i(const ir_node *node)
1536 {
1537         unsigned size = get_ia32_copyb_size(node);
1538
1539         emit_CopyB_prolog(size);
1540
1541         size >>= 2;
1542         while (size--) {
1543                 ia32_emitf(NULL, "\tmovsd\n");
1544         }
1545 }
1546
1547
1548 /**
1549  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1550  */
1551 static void emit_ia32_Conv_with_FP(const ir_node *node, const char* conv_f,
1552                 const char* conv_d)
1553 {
1554         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1555         int                 ls_bits = get_mode_size_bits(ls_mode);
1556         const char         *conv    = ls_bits == 32 ? conv_f : conv_d;
1557
1558         ia32_emitf(node, "\tcvt%s %AS3, %D0\n", conv);
1559 }
1560
1561 static void emit_ia32_Conv_I2FP(const ir_node *node)
1562 {
1563         emit_ia32_Conv_with_FP(node, "si2ss", "si2sd");
1564 }
1565
1566 static void emit_ia32_Conv_FP2I(const ir_node *node)
1567 {
1568         emit_ia32_Conv_with_FP(node, "ss2si", "sd2si");
1569 }
1570
1571 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1572 {
1573         emit_ia32_Conv_with_FP(node, "sd2ss", "ss2sd");
1574 }
1575
1576 /**
1577  * Emits code for an Int conversion.
1578  */
1579 static void emit_ia32_Conv_I2I(const ir_node *node)
1580 {
1581         ir_mode *smaller_mode = get_ia32_ls_mode(node);
1582         int      signed_mode  = mode_is_signed(smaller_mode);
1583         const char *sign_suffix;
1584
1585         assert(!mode_is_float(smaller_mode));
1586
1587         sign_suffix = signed_mode ? "s" : "z";
1588         ia32_emitf(node, "\tmov%s%Ml %#AS3, %D0\n", sign_suffix);
1589 }
1590
1591 /**
1592  * Emits a call
1593  */
1594 static void emit_ia32_Call(const ir_node *node)
1595 {
1596         /* Special case: Call must not have its immediates prefixed by $, instead
1597          * address mode is prefixed by *. */
1598         ia32_emitf(node, "\tcall %*AS3\n");
1599 }
1600
1601
1602 /**
1603  * Emits code to increase stack pointer.
1604  */
1605 static void emit_be_IncSP(const ir_node *node)
1606 {
1607         int offs = be_get_IncSP_offset(node);
1608
1609         if (offs == 0)
1610                 return;
1611
1612         if (offs > 0) {
1613                 ia32_emitf(node, "\tsubl $%u, %D0\n", offs);
1614         } else {
1615                 ia32_emitf(node, "\taddl $%u, %D0\n", -offs);
1616         }
1617 }
1618
1619 /**
1620  * Emits code for Copy/CopyKeep.
1621  */
1622 static void Copy_emitter(const ir_node *node, const ir_node *op)
1623 {
1624         const arch_register_t *in  = arch_get_irn_register(op);
1625         const arch_register_t *out = arch_get_irn_register(node);
1626
1627         if (in == out) {
1628                 return;
1629         }
1630         /* copies of vf nodes aren't real... */
1631         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1632                 return;
1633
1634         if (get_irn_mode(node) == mode_E) {
1635                 ia32_emitf(node, "\tmovsd %R, %R\n", in, out);
1636         } else {
1637                 ia32_emitf(node, "\tmovl %R, %R\n", in, out);
1638         }
1639 }
1640
1641 static void emit_be_Copy(const ir_node *node)
1642 {
1643         Copy_emitter(node, be_get_Copy_op(node));
1644 }
1645
1646 static void emit_be_CopyKeep(const ir_node *node)
1647 {
1648         Copy_emitter(node, be_get_CopyKeep_op(node));
1649 }
1650
1651 /**
1652  * Emits code for exchange.
1653  */
1654 static void emit_be_Perm(const ir_node *node)
1655 {
1656         const arch_register_t *in0, *in1;
1657         const arch_register_class_t *cls0, *cls1;
1658
1659         in0 = arch_get_irn_register(get_irn_n(node, 0));
1660         in1 = arch_get_irn_register(get_irn_n(node, 1));
1661
1662         cls0 = arch_register_get_class(in0);
1663         cls1 = arch_register_get_class(in1);
1664
1665         assert(cls0 == cls1 && "Register class mismatch at Perm");
1666
1667         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1668                 ia32_emitf(node, "\txchg %R, %R\n", in1, in0);
1669         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1670                 ia32_emitf(NULL, "\txorpd %R, %R\n", in1, in0);
1671                 ia32_emitf(NULL, "\txorpd %R, %R\n", in0, in1);
1672                 ia32_emitf(node, "\txorpd %R, %R\n", in1, in0);
1673         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1674                 /* is a NOP */
1675         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1676                 /* is a NOP */
1677         } else {
1678                 panic("unexpected register class in be_Perm (%+F)", node);
1679         }
1680 }
1681
1682 /**
1683  * Emits code for Constant loading.
1684  */
1685 static void emit_ia32_Const(const ir_node *node)
1686 {
1687         ia32_emitf(node, "\tmovl %I, %D0\n");
1688 }
1689
1690 /**
1691  * Emits code to load the TLS base
1692  */
1693 static void emit_ia32_LdTls(const ir_node *node)
1694 {
1695         ia32_emitf(node, "\tmovl %%gs:0, %D0\n");
1696 }
1697
1698 /* helper function for emit_ia32_Minus64Bit */
1699 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1700 {
1701         ia32_emitf(node, "\tmovl %R, %R\n", src, dst);
1702 }
1703
1704 /* helper function for emit_ia32_Minus64Bit */
1705 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1706 {
1707         ia32_emitf(node, "\tnegl %R\n", reg);
1708 }
1709
1710 /* helper function for emit_ia32_Minus64Bit */
1711 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1712 {
1713         ia32_emitf(node, "\tsbbl $0, %R\n", reg);
1714 }
1715
1716 /* helper function for emit_ia32_Minus64Bit */
1717 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1718 {
1719         ia32_emitf(node, "\tsbbl %R, %R\n", src, dst);
1720 }
1721
1722 /* helper function for emit_ia32_Minus64Bit */
1723 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1724 {
1725         ia32_emitf(node, "\txchgl %R, %R\n", src, dst);
1726 }
1727
1728 /* helper function for emit_ia32_Minus64Bit */
1729 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1730 {
1731         ia32_emitf(node, "\txorl %R, %R\n", reg, reg);
1732 }
1733
1734 static void emit_ia32_Minus64Bit(const ir_node *node)
1735 {
1736         const arch_register_t *in_lo  = get_in_reg(node, 0);
1737         const arch_register_t *in_hi  = get_in_reg(node, 1);
1738         const arch_register_t *out_lo = get_out_reg(node, 0);
1739         const arch_register_t *out_hi = get_out_reg(node, 1);
1740
1741         if (out_lo == in_lo) {
1742                 if (out_hi != in_hi) {
1743                         /* a -> a, b -> d */
1744                         goto zero_neg;
1745                 } else {
1746                         /* a -> a, b -> b */
1747                         goto normal_neg;
1748                 }
1749         } else if (out_lo == in_hi) {
1750                 if (out_hi == in_lo) {
1751                         /* a -> b, b -> a */
1752                         emit_xchg(node, in_lo, in_hi);
1753                         goto normal_neg;
1754                 } else {
1755                         /* a -> b, b -> d */
1756                         emit_mov(node, in_hi, out_hi);
1757                         emit_mov(node, in_lo, out_lo);
1758                         goto normal_neg;
1759                 }
1760         } else {
1761                 if (out_hi == in_lo) {
1762                         /* a -> c, b -> a */
1763                         emit_mov(node, in_lo, out_lo);
1764                         goto zero_neg;
1765                 } else if (out_hi == in_hi) {
1766                         /* a -> c, b -> b */
1767                         emit_mov(node, in_lo, out_lo);
1768                         goto normal_neg;
1769                 } else {
1770                         /* a -> c, b -> d */
1771                         emit_mov(node, in_lo, out_lo);
1772                         goto zero_neg;
1773                 }
1774         }
1775
1776 normal_neg:
1777         emit_neg( node, out_hi);
1778         emit_neg( node, out_lo);
1779         emit_sbb0(node, out_hi);
1780         return;
1781
1782 zero_neg:
1783         emit_zero(node, out_hi);
1784         emit_neg( node, out_lo);
1785         emit_sbb( node, in_hi, out_hi);
1786 }
1787
1788 static void emit_ia32_GetEIP(const ir_node *node)
1789 {
1790         ia32_emitf(node, "\tcall %s\n", pic_base_label);
1791         ia32_emitf(NULL, "%s:\n", pic_base_label);
1792         ia32_emitf(node, "\tpopl %D0\n");
1793 }
1794
1795 static void emit_ia32_ClimbFrame(const ir_node *node)
1796 {
1797         const ia32_climbframe_attr_t *attr = get_ia32_climbframe_attr_const(node);
1798
1799         ia32_emitf(node, "\tmovl %S0, %D0\n");
1800         ia32_emitf(node, "\tmovl $%u, %S1\n", attr->count);
1801         be_gas_emit_block_name(node);
1802         be_emit_cstring(":\n");
1803         be_emit_write_line();
1804         ia32_emitf(node, "\tmovl (%D0), %D0\n");
1805         ia32_emitf(node, "\tdec %S1\n");
1806         be_emit_cstring("\tjnz ");
1807         be_gas_emit_block_name(node);
1808         be_emit_finish_line_gas(node);
1809 }
1810
1811 static void emit_be_Return(const ir_node *node)
1812 {
1813         unsigned pop = be_Return_get_pop(node);
1814
1815         if (pop > 0 || be_Return_get_emit_pop(node)) {
1816                 ia32_emitf(node, "\tret $%u\n", pop);
1817         } else {
1818                 ia32_emitf(node, "\tret\n");
1819         }
1820 }
1821
1822 static void emit_Nothing(const ir_node *node)
1823 {
1824         (void) node;
1825 }
1826
1827
1828 /**
1829  * Enters the emitter functions for handled nodes into the generic
1830  * pointer of an opcode.
1831  */
1832 static void ia32_register_emitters(void)
1833 {
1834 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1835 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1836 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1837 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1838 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1839 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1840
1841         /* first clear the generic function pointer for all ops */
1842         clear_irp_opcodes_generic_func();
1843
1844         /* register all emitter functions defined in spec */
1845         ia32_register_spec_emitters();
1846
1847         /* other ia32 emitter functions */
1848         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1849         IA32_EMIT(Asm);
1850         IA32_EMIT(CMovcc);
1851         IA32_EMIT(Call);
1852         IA32_EMIT(Const);
1853         IA32_EMIT(Conv_FP2FP);
1854         IA32_EMIT(Conv_FP2I);
1855         IA32_EMIT(Conv_I2FP);
1856         IA32_EMIT(Conv_I2I);
1857         IA32_EMIT(CopyB);
1858         IA32_EMIT(CopyB_i);
1859         IA32_EMIT(GetEIP);
1860         IA32_EMIT(IMul);
1861         IA32_EMIT(Jcc);
1862         IA32_EMIT(Setcc);
1863         IA32_EMIT(LdTls);
1864         IA32_EMIT(Minus64Bit);
1865         IA32_EMIT(SwitchJmp);
1866         IA32_EMIT(ClimbFrame);
1867         IA32_EMIT(Jmp);
1868
1869         /* benode emitter */
1870         BE_EMIT(Copy);
1871         BE_EMIT(CopyKeep);
1872         BE_EMIT(IncSP);
1873         BE_EMIT(Perm);
1874         BE_EMIT(Return);
1875
1876         BE_IGN(Barrier);
1877         BE_IGN(Keep);
1878         BE_IGN(Start);
1879
1880         /* firm emitter */
1881         IGN(Phi);
1882
1883 #undef BE_EMIT
1884 #undef EMIT
1885 #undef IGN
1886 #undef IA32_EMIT2
1887 #undef IA32_EMIT
1888 }
1889
1890 typedef void (*emit_func_ptr) (const ir_node *);
1891
1892 /**
1893  * Assign and emit an exception label if the current instruction can fail.
1894  */
1895 static void ia32_assign_exc_label(ir_node *node)
1896 {
1897         /* assign a new ID to the instruction */
1898         set_ia32_exc_label_id(node, ++exc_label_id);
1899         /* print it */
1900         ia32_emit_exc_label(node);
1901         be_emit_char(':');
1902         be_emit_pad_comment();
1903         be_emit_cstring("/* exception to Block ");
1904         ia32_emit_cfop_target(node);
1905         be_emit_cstring(" */\n");
1906         be_emit_write_line();
1907 }
1908
1909 /**
1910  * Emits code for a node.
1911  */
1912 static void ia32_emit_node(ir_node *node)
1913 {
1914         ir_op *op = get_irn_op(node);
1915
1916         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1917
1918         if (is_ia32_irn(node)) {
1919                 if (get_ia32_exc_label(node)) {
1920                         /* emit the exception label of this instruction */
1921                         ia32_assign_exc_label(node);
1922                 }
1923                 if (mark_spill_reload) {
1924                         if (is_ia32_is_spill(node)) {
1925                                 ia32_emitf(NULL, "\txchg %ebx, %ebx        /* spill mark */\n");
1926                         }
1927                         if (is_ia32_is_reload(node)) {
1928                                 ia32_emitf(NULL, "\txchg %edx, %edx        /* reload mark */\n");
1929                         }
1930                         if (is_ia32_is_remat(node)) {
1931                                 ia32_emitf(NULL, "\txchg %ecx, %ecx        /* remat mark */\n");
1932                         }
1933                 }
1934         }
1935         if (op->ops.generic) {
1936                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1937
1938                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1939
1940                 (*func) (node);
1941         } else {
1942                 emit_Nothing(node);
1943                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1944                 abort();
1945         }
1946 }
1947
1948 /**
1949  * Emits gas alignment directives
1950  */
1951 static void ia32_emit_alignment(unsigned align, unsigned skip)
1952 {
1953         ia32_emitf(NULL, "\t.p2align %u,,%u\n", align, skip);
1954 }
1955
1956 /**
1957  * Emits gas alignment directives for Labels depended on cpu architecture.
1958  */
1959 static void ia32_emit_align_label(void)
1960 {
1961         unsigned align        = ia32_cg_config.label_alignment;
1962         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
1963         ia32_emit_alignment(align, maximum_skip);
1964 }
1965
1966 /**
1967  * Test whether a block should be aligned.
1968  * For cpus in the P4/Athlon class it is useful to align jump labels to
1969  * 16 bytes. However we should only do that if the alignment nops before the
1970  * label aren't executed more often than we have jumps to the label.
1971  */
1972 static int should_align_block(const ir_node *block)
1973 {
1974         static const double DELTA = .0001;
1975         ir_exec_freq *exec_freq   = be_get_irg_exec_freq(cg->irg);
1976         ir_node      *prev        = get_prev_block_sched(block);
1977         double        block_freq;
1978         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
1979         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
1980         int           i, n_cfgpreds;
1981
1982         if (exec_freq == NULL)
1983                 return 0;
1984         if (ia32_cg_config.label_alignment_factor <= 0)
1985                 return 0;
1986
1987         block_freq = get_block_execfreq(exec_freq, block);
1988         if (block_freq < DELTA)
1989                 return 0;
1990
1991         n_cfgpreds = get_Block_n_cfgpreds(block);
1992         for (i = 0; i < n_cfgpreds; ++i) {
1993                 const ir_node *pred      = get_Block_cfgpred_block(block, i);
1994                 double         pred_freq = get_block_execfreq(exec_freq, pred);
1995
1996                 if (pred == prev) {
1997                         prev_freq += pred_freq;
1998                 } else {
1999                         jmp_freq  += pred_freq;
2000                 }
2001         }
2002
2003         if (prev_freq < DELTA && !(jmp_freq < DELTA))
2004                 return 1;
2005
2006         jmp_freq /= prev_freq;
2007
2008         return jmp_freq > ia32_cg_config.label_alignment_factor;
2009 }
2010
2011 /**
2012  * Emit the block header for a block.
2013  *
2014  * @param block       the block
2015  * @param prev_block  the previous block
2016  */
2017 static void ia32_emit_block_header(ir_node *block)
2018 {
2019         ir_graph     *irg = current_ir_graph;
2020         int           need_label = block_needs_label(block);
2021         int           i, arity;
2022         ir_exec_freq *exec_freq = be_get_irg_exec_freq(cg->irg);
2023
2024         if (block == get_irg_end_block(irg))
2025                 return;
2026
2027         if (ia32_cg_config.label_alignment > 0) {
2028                 /* align the current block if:
2029                  * a) if should be aligned due to its execution frequency
2030                  * b) there is no fall-through here
2031                  */
2032                 if (should_align_block(block)) {
2033                         ia32_emit_align_label();
2034                 } else {
2035                         /* if the predecessor block has no fall-through,
2036                            we can always align the label. */
2037                         int i;
2038                         int has_fallthrough = 0;
2039
2040                         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
2041                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2042                                 if (can_be_fallthrough(cfg_pred)) {
2043                                         has_fallthrough = 1;
2044                                         break;
2045                                 }
2046                         }
2047
2048                         if (!has_fallthrough)
2049                                 ia32_emit_align_label();
2050                 }
2051         }
2052
2053         if (need_label) {
2054                 be_gas_emit_block_name(block);
2055                 be_emit_char(':');
2056
2057                 be_emit_pad_comment();
2058                 be_emit_cstring("   /* ");
2059         } else {
2060                 be_emit_cstring("\t/* ");
2061                 be_gas_emit_block_name(block);
2062                 be_emit_cstring(": ");
2063         }
2064
2065         be_emit_cstring("preds:");
2066
2067         /* emit list of pred blocks in comment */
2068         arity = get_irn_arity(block);
2069         if (arity <= 0) {
2070                 be_emit_cstring(" none");
2071         } else {
2072                 for (i = 0; i < arity; ++i) {
2073                         ir_node *predblock = get_Block_cfgpred_block(block, i);
2074                         be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2075                 }
2076         }
2077         if (exec_freq != NULL) {
2078                 be_emit_irprintf(", freq: %f",
2079                                  get_block_execfreq(exec_freq, block));
2080         }
2081         be_emit_cstring(" */\n");
2082         be_emit_write_line();
2083 }
2084
2085 /**
2086  * Walks over the nodes in a block connected by scheduling edges
2087  * and emits code for each node.
2088  */
2089 static void ia32_gen_block(ir_node *block)
2090 {
2091         ir_node *node;
2092
2093         ia32_emit_block_header(block);
2094
2095         /* emit the contents of the block */
2096         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2097         sched_foreach(block, node) {
2098                 ia32_emit_node(node);
2099         }
2100 }
2101
2102 typedef struct exc_entry {
2103         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2104         ir_node *block;      /** The block to call then. */
2105 } exc_entry;
2106
2107 /**
2108  * Block-walker:
2109  * Sets labels for control flow nodes (jump target).
2110  * Links control predecessors to there destination blocks.
2111  */
2112 static void ia32_gen_labels(ir_node *block, void *data)
2113 {
2114         exc_entry **exc_list = data;
2115         ir_node *pred;
2116         int     n;
2117
2118         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2119                 pred = get_Block_cfgpred(block, n);
2120                 set_irn_link(pred, block);
2121
2122                 pred = skip_Proj(pred);
2123                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2124                         exc_entry e;
2125
2126                         e.exc_instr = pred;
2127                         e.block     = block;
2128                         ARR_APP1(exc_entry, *exc_list, e);
2129                         set_irn_link(pred, block);
2130                 }
2131         }
2132 }
2133
2134 /**
2135  * Compare two exception_entries.
2136  */
2137 static int cmp_exc_entry(const void *a, const void *b)
2138 {
2139         const exc_entry *ea = a;
2140         const exc_entry *eb = b;
2141
2142         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2143                 return -1;
2144         return +1;
2145 }
2146
2147 /**
2148  * Main driver. Emits the code for one routine.
2149  */
2150 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2151 {
2152         ir_entity *entity     = get_irg_entity(irg);
2153         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2154         int i, n;
2155
2156         cg       = ia32_cg;
2157         isa      = cg->isa;
2158         do_pic   = be_get_irg_options(cg->irg)->pic;
2159
2160         be_gas_elf_type_char = '@';
2161
2162         ia32_register_emitters();
2163
2164         get_unique_label(pic_base_label, sizeof(pic_base_label), "PIC_BASE");
2165
2166         be_dbg_method_begin(entity);
2167         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2168
2169         /* we use links to point to target blocks */
2170         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2171         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2172
2173         /* initialize next block links */
2174         n = ARR_LEN(cg->blk_sched);
2175         for (i = 0; i < n; ++i) {
2176                 ir_node *block = cg->blk_sched[i];
2177                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2178
2179                 set_irn_link(block, prev);
2180         }
2181
2182         for (i = 0; i < n; ++i) {
2183                 ir_node *block = cg->blk_sched[i];
2184
2185                 ia32_gen_block(block);
2186         }
2187
2188         be_gas_emit_function_epilog(entity);
2189         be_dbg_method_end();
2190         be_emit_char('\n');
2191         be_emit_write_line();
2192
2193         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2194
2195         /* Sort the exception table using the exception label id's.
2196            Those are ascending with ascending addresses. */
2197         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2198         {
2199                 int i;
2200
2201                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2202                         be_emit_cstring("\t.long ");
2203                         ia32_emit_exc_label(exc_list[i].exc_instr);
2204                         be_emit_char('\n');
2205                         be_emit_cstring("\t.long ");
2206                         be_gas_emit_block_name(exc_list[i].block);
2207                         be_emit_char('\n');
2208                 }
2209         }
2210         DEL_ARR_F(exc_list);
2211 }
2212
2213 static const lc_opt_table_entry_t ia32_emitter_options[] = {
2214         LC_OPT_ENT_BOOL("mark_spill_reload",   "mark spills and reloads with ud opcodes", &mark_spill_reload),
2215         LC_OPT_LAST
2216 };
2217
2218 /* ==== Experimental binary emitter ==== */
2219
2220 static unsigned char reg_gp_map[N_ia32_gp_REGS];
2221 //static unsigned char reg_mmx_map[N_ia32_mmx_REGS];
2222 //static unsigned char reg_sse_map[N_ia32_xmm_REGS];
2223 static unsigned char pnc_map_signed[8];
2224 static unsigned char pnc_map_unsigned[8];
2225
2226 static void build_reg_map(void)
2227 {
2228         reg_gp_map[REG_EAX] = 0x0;
2229         reg_gp_map[REG_ECX] = 0x1;
2230         reg_gp_map[REG_EDX] = 0x2;
2231         reg_gp_map[REG_EBX] = 0x3;
2232         reg_gp_map[REG_ESP] = 0x4;
2233         reg_gp_map[REG_EBP] = 0x5;
2234         reg_gp_map[REG_ESI] = 0x6;
2235         reg_gp_map[REG_EDI] = 0x7;
2236
2237         pnc_map_signed[pn_Cmp_Eq]    = 0x04;
2238         pnc_map_signed[pn_Cmp_Lt]    = 0x0C;
2239         pnc_map_signed[pn_Cmp_Le]    = 0x0E;
2240         pnc_map_signed[pn_Cmp_Gt]    = 0x0F;
2241         pnc_map_signed[pn_Cmp_Ge]    = 0x0D;
2242         pnc_map_signed[pn_Cmp_Lg]    = 0x05;
2243
2244         pnc_map_unsigned[pn_Cmp_Eq]    = 0x04;
2245         pnc_map_unsigned[pn_Cmp_Lt]    = 0x02;
2246         pnc_map_unsigned[pn_Cmp_Le]    = 0x06;
2247         pnc_map_unsigned[pn_Cmp_Gt]    = 0x07;
2248         pnc_map_unsigned[pn_Cmp_Ge]    = 0x03;
2249         pnc_map_unsigned[pn_Cmp_Lg]    = 0x05;
2250 }
2251
2252 /** Returns the encoding for a pnc field. */
2253 static unsigned char pnc2cc(int pnc)
2254 {
2255         unsigned char cc;
2256         if (pnc == ia32_pn_Cmp_parity) {
2257                 cc = 0x0A;
2258         } else if (pnc & ia32_pn_Cmp_float || pnc & ia32_pn_Cmp_unsigned) {
2259                 cc = pnc_map_unsigned[pnc & 0x07];
2260         } else {
2261                 cc = pnc_map_signed[pnc & 0x07];
2262         }
2263         assert(cc != 0);
2264         return cc;
2265 }
2266
2267 /** Sign extension bit values for binops */
2268 enum SignExt {
2269         UNSIGNED_IMM = 0,  /**< unsigned immediate */
2270         SIGNEXT_IMM  = 2,  /**< sign extended immediate */
2271 };
2272
2273 /** The mod encoding of the ModR/M */
2274 enum Mod {
2275         MOD_IND          = 0x00, /**< [reg1] */
2276         MOD_IND_BYTE_OFS = 0x40, /**< [reg1 + byte ofs] */
2277         MOD_IND_WORD_OFS = 0x80, /**< [reg1 + word ofs] */
2278         MOD_REG          = 0xC0  /**< reg1 */
2279 };
2280
2281 /** create R/M encoding for ModR/M */
2282 #define ENC_RM(x) (x)
2283 /** create REG encoding for ModR/M */
2284 #define ENC_REG(x) ((x) << 3)
2285
2286 /** create encoding for a SIB byte */
2287 #define ENC_SIB(scale, index, base) ((scale) << 6 | (index) << 3 | (base))
2288
2289 /* Node: The following routines are supposed to append bytes, words, dwords
2290    to the output stream.
2291    Currently the implementation is stupid in that it still creates output
2292    for an "assembler" in the form of .byte, .long
2293    We will change this when enough infrastructure is there to create complete
2294    machine code in memory/object files */
2295
2296 static void bemit8(const unsigned char byte)
2297 {
2298         be_emit_irprintf("\t.byte 0x%x\n", byte);
2299         be_emit_write_line();
2300 }
2301
2302 static void bemit16(const unsigned short u16)
2303 {
2304         be_emit_irprintf("\t.word 0x%x\n", u16);
2305         be_emit_write_line();
2306 }
2307
2308 static void bemit32(const unsigned u32)
2309 {
2310         be_emit_irprintf("\t.long 0x%x\n", u32);
2311         be_emit_write_line();
2312 }
2313
2314 /**
2315  * Emit address of an entity. If @p is_relative is true then a relative
2316  * offset from behind the address to the entity is created.
2317  */
2318 static void bemit_entity(ir_entity *entity, bool entity_sign, int offset,
2319                          bool is_relative)
2320 {
2321         if (entity == NULL) {
2322                 bemit32(offset);
2323                 return;
2324         }
2325
2326         /* the final version should remember the position in the bytestream
2327            and patch it with the correct address at linktime... */
2328         be_emit_cstring("\t.long ");
2329         if (entity_sign)
2330                 be_emit_char('-');
2331         be_gas_emit_entity(entity);
2332
2333         if (get_entity_owner(entity) == get_tls_type()) {
2334                 if (get_entity_visibility(entity) == ir_visibility_external) {
2335                         be_emit_cstring("@INDNTPOFF");
2336                 } else {
2337                         be_emit_cstring("@NTPOFF");
2338                 }
2339         }
2340
2341         if (is_relative) {
2342                 be_emit_cstring("-.");
2343                 offset -= 4;
2344         }
2345
2346         if (offset != 0) {
2347                 be_emit_irprintf("%+d", offset);
2348         }
2349         be_emit_char('\n');
2350         be_emit_write_line();
2351 }
2352
2353 static void bemit_jmp_destination(const ir_node *dest_block)
2354 {
2355         be_emit_cstring("\t.long ");
2356         be_gas_emit_block_name(dest_block);
2357         be_emit_cstring(" - . - 4\n");
2358         be_emit_write_line();
2359 }
2360
2361 /* end emit routines, all emitters following here should only use the functions
2362    above. */
2363
2364 typedef enum reg_modifier {
2365         REG_LOW  = 0,
2366         REG_HIGH = 1
2367 } reg_modifier_t;
2368
2369 /** Create a ModR/M byte for src1,src2 registers */
2370 static void bemit_modrr(const arch_register_t *src1,
2371                         const arch_register_t *src2)
2372 {
2373         unsigned char modrm = MOD_REG;
2374         modrm |= ENC_RM(reg_gp_map[src1->index]);
2375         modrm |= ENC_REG(reg_gp_map[src2->index]);
2376         bemit8(modrm);
2377 }
2378
2379 /** Create a ModR/M8 byte for src1,src2 registers */
2380 static void bemit_modrr8(reg_modifier_t high_part1, const arch_register_t *src1,
2381                                                  reg_modifier_t high_part2, const arch_register_t *src2)
2382 {
2383         unsigned char modrm = MOD_REG;
2384         modrm |= ENC_RM(reg_gp_map[src1->index] +  (high_part1 == REG_HIGH ? 4 : 0));
2385         modrm |= ENC_REG(reg_gp_map[src2->index] + (high_part2 == REG_HIGH ? 4 : 0));
2386         bemit8(modrm);
2387 }
2388
2389 /** Create a ModR/M byte for one register and extension */
2390 static void bemit_modru(const arch_register_t *reg, unsigned ext)
2391 {
2392         unsigned char modrm = MOD_REG;
2393         assert(ext <= 7);
2394         modrm |= ENC_RM(reg_gp_map[reg->index]);
2395         modrm |= ENC_REG(ext);
2396         bemit8(modrm);
2397 }
2398
2399 /** Create a ModR/M8 byte for one register */
2400 static void bemit_modrm8(reg_modifier_t high_part, const arch_register_t *reg)
2401 {
2402         unsigned char modrm = MOD_REG;
2403         assert(reg_gp_map[reg->index] < 4);
2404         modrm |= ENC_RM(reg_gp_map[reg->index] + (high_part == REG_HIGH ? 4 : 0));
2405         modrm |= MOD_REG;
2406         bemit8(modrm);
2407 }
2408
2409 /**
2410  * Calculate the size of an signed immediate in bytes.
2411  *
2412  * @param offset  an offset
2413  */
2414 static unsigned get_signed_imm_size(int offset)
2415 {
2416         if (-128 <= offset && offset < 128) {
2417                 return 1;
2418         } else if (-32768 <= offset && offset < 32768) {
2419                 return 2;
2420         } else {
2421                 return 4;
2422         }
2423 }
2424
2425 /**
2426  * Emit an address mode.
2427  *
2428  * @param reg   content of the reg field: either a register index or an opcode extension
2429  * @param node  the node
2430  */
2431 static void bemit_mod_am(unsigned reg, const ir_node *node)
2432 {
2433         ir_entity *ent       = get_ia32_am_sc(node);
2434         int        offs      = get_ia32_am_offs_int(node);
2435         ir_node   *base      = get_irn_n(node, n_ia32_base);
2436         int        has_base  = !is_ia32_NoReg_GP(base);
2437         ir_node   *index     = get_irn_n(node, n_ia32_index);
2438         int        has_index = !is_ia32_NoReg_GP(index);
2439         unsigned   modrm     = 0;
2440         unsigned   sib       = 0;
2441         unsigned   emitoffs  = 0;
2442         bool       emitsib   = false;
2443         unsigned   base_enc;
2444
2445         /* set the mod part depending on displacement */
2446         if (ent != NULL) {
2447                 modrm |= MOD_IND_WORD_OFS;
2448                 emitoffs = 32;
2449         } else if (offs == 0) {
2450                 modrm |= MOD_IND;
2451                 emitoffs = 0;
2452         } else if (-128 <= offs && offs < 128) {
2453                 modrm |= MOD_IND_BYTE_OFS;
2454                 emitoffs = 8;
2455         } else {
2456                 modrm |= MOD_IND_WORD_OFS;
2457                 emitoffs = 32;
2458         }
2459
2460         if (has_base) {
2461                 const arch_register_t *base_reg = arch_get_irn_register(base);
2462                 base_enc = reg_gp_map[base_reg->index];
2463         } else {
2464                 /* Use the EBP encoding + MOD_IND if NO base register. There is
2465                  * always a 32bit offset present in this case. */
2466                 modrm    = MOD_IND;
2467                 base_enc = 0x05;
2468                 emitoffs = 32;
2469         }
2470
2471         /* Determine if we need a SIB byte. */
2472         if (has_index) {
2473                 const arch_register_t *reg_index = arch_get_irn_register(index);
2474                 int                    scale     = get_ia32_am_scale(node);
2475                 assert(scale < 4);
2476                 /* R/M set to ESP means SIB in 32bit mode. */
2477                 modrm   |= ENC_RM(0x04);
2478                 sib      = ENC_SIB(scale, reg_gp_map[reg_index->index], base_enc);
2479                 emitsib = true;
2480         } else if (base_enc == 0x04) {
2481                 /* for the above reason we are forced to emit a SIB when base is ESP.
2482                  * Only the base is used, index must be ESP too, which means no index.
2483                  */
2484                 modrm   |= ENC_RM(0x04);
2485                 sib      = ENC_SIB(0, 0x04, 0x04);
2486                 emitsib  = true;
2487         } else {
2488                 modrm |= ENC_RM(base_enc);
2489         }
2490
2491         /* We are forced to emit an 8bit offset as EBP base without offset is a
2492          * special case for SIB without base register. */
2493         if (base_enc == 0x05 && emitoffs == 0) {
2494                 modrm    |= MOD_IND_BYTE_OFS;
2495                 emitoffs  = 8;
2496         }
2497
2498         modrm |= ENC_REG(reg);
2499
2500         bemit8(modrm);
2501         if (emitsib)
2502                 bemit8(sib);
2503
2504         /* emit displacement */
2505         if (emitoffs == 8) {
2506                 bemit8((unsigned) offs);
2507         } else if (emitoffs == 32) {
2508                 bemit_entity(ent, is_ia32_am_sc_sign(node), offs, false);
2509         }
2510 }
2511
2512 /**
2513  * Emit a binop with a immediate operand.
2514  *
2515  * @param node        the node to emit
2516  * @param opcode_eax  the opcode for the op eax, imm variant
2517  * @param opcode      the opcode for the reg, imm variant
2518  * @param ruval       the opcode extension for opcode
2519  */
2520 static void bemit_binop_with_imm(
2521         const ir_node *node,
2522         unsigned char opcode_ax,
2523         unsigned char opcode, unsigned char ruval)
2524 {
2525         /* Use in-reg, because some instructions (cmp, test) have no out-reg. */
2526         const ir_node               *op   = get_irn_n(node, n_ia32_binary_right);
2527         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(op);
2528         unsigned                     size;
2529
2530         /* Some instructions (test) have no short form with 32bit value + 8bit
2531          * immediate. */
2532         if (attr->symconst != NULL || opcode & SIGNEXT_IMM) {
2533                 size = 4;
2534         } else {
2535                 /* check for sign extension */
2536                 size = get_signed_imm_size(attr->offset);
2537         }
2538
2539         switch (size) {
2540         case 1:
2541                 bemit8(opcode | SIGNEXT_IMM);
2542                 /* cmp has this special mode */
2543                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
2544                         bemit_mod_am(ruval, node);
2545                 } else {
2546                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
2547                         bemit_modru(reg, ruval);
2548                 }
2549                 bemit8((unsigned char)attr->offset);
2550                 return;
2551         case 2:
2552         case 4:
2553                 /* check for eax variant: this variant is shorter for 32bit immediates only */
2554                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
2555                         bemit8(opcode);
2556                         bemit_mod_am(ruval, node);
2557                 } else {
2558                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
2559                         if (reg->index == REG_EAX) {
2560                                 bemit8(opcode_ax);
2561                         } else {
2562                                 bemit8(opcode);
2563                                 bemit_modru(reg, ruval);
2564                         }
2565                 }
2566                 bemit_entity(attr->symconst, attr->sc_sign, attr->offset, false);
2567                 return;
2568         }
2569         panic("invalid imm size?!?");
2570 }
2571
2572 /**
2573  * Emits a binop.
2574  */
2575 static void bemit_binop_2(const ir_node *node, unsigned code)
2576 {
2577         const arch_register_t *out = get_in_reg(node, n_ia32_binary_left);
2578         bemit8(code);
2579         if (get_ia32_op_type(node) == ia32_Normal) {
2580                 const arch_register_t *op2 = get_in_reg(node, n_ia32_binary_right);
2581                 bemit_modrr(op2, out);
2582         } else {
2583                 bemit_mod_am(reg_gp_map[out->index], node);
2584         }
2585 }
2586
2587 /**
2588  * Emit a binop.
2589  */
2590 static void bemit_binop(const ir_node *node, const unsigned char opcodes[4])
2591 {
2592         ir_node *right = get_irn_n(node, n_ia32_binary_right);
2593         if (is_ia32_Immediate(right)) {
2594                 bemit_binop_with_imm(node, opcodes[1], opcodes[2], opcodes[3]);
2595         } else {
2596                 bemit_binop_2(node, opcodes[0]);
2597         }
2598 }
2599
2600 /**
2601  * Emit an unop.
2602  */
2603 static void bemit_unop(const ir_node *node, unsigned char code, unsigned char ext, int input)
2604 {
2605         bemit8(code);
2606         if (get_ia32_op_type(node) == ia32_Normal) {
2607                 const arch_register_t *in = get_in_reg(node, input);
2608                 bemit_modru(in, ext);
2609         } else {
2610                 bemit_mod_am(ext, node);
2611         }
2612 }
2613
2614 static void bemit_unop_reg(const ir_node *node, unsigned char code, int input)
2615 {
2616         const arch_register_t *out = get_out_reg(node, 0);
2617         bemit_unop(node, code, reg_gp_map[out->index], input);
2618 }
2619
2620 static void bemit_unop_mem(const ir_node *node, unsigned char code, unsigned char ext)
2621 {
2622         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node));
2623         if (size == 16)
2624                 bemit8(0x66);
2625         bemit8(size == 8 ? code : code + 1);
2626         bemit_mod_am(ext, node);
2627 }
2628
2629 static void bemit_immediate(const ir_node *node, bool relative)
2630 {
2631         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
2632         bemit_entity(attr->symconst, attr->sc_sign, attr->offset, relative);
2633 }
2634
2635 static void bemit_copy(const ir_node *copy)
2636 {
2637         const arch_register_t *in  = get_in_reg(copy, 0);
2638         const arch_register_t *out = get_out_reg(copy, 0);
2639
2640         if (in == out)
2641                 return;
2642         /* copies of vf nodes aren't real... */
2643         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
2644                 return;
2645
2646         if (get_irn_mode(copy) == mode_E) {
2647                 panic("NIY");
2648         } else {
2649                 assert(arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_gp]);
2650                 bemit8(0x8B);
2651                 bemit_modrr(in, out);
2652         }
2653 }
2654
2655 static void bemit_perm(const ir_node *node)
2656 {
2657         const arch_register_t       *in0  = arch_get_irn_register(get_irn_n(node, 0));
2658         const arch_register_t       *in1  = arch_get_irn_register(get_irn_n(node, 1));
2659         const arch_register_class_t *cls0 = arch_register_get_class(in0);
2660
2661         assert(cls0 == arch_register_get_class(in1) && "Register class mismatch at Perm");
2662
2663         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
2664                 if (in0->index == REG_EAX) {
2665                         bemit8(0x90 + reg_gp_map[in1->index]);
2666                 } else if (in1->index == REG_EAX) {
2667                         bemit8(0x90 + reg_gp_map[in0->index]);
2668                 } else {
2669                         bemit8(0x87);
2670                         bemit_modrr(in0, in1);
2671                 }
2672         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
2673                 panic("unimplemented"); // TODO implement
2674                 //ia32_emitf(NULL, "\txorpd %R, %R\n", in1, in0);
2675                 //ia32_emitf(NULL, "\txorpd %R, %R\n", in0, in1);
2676                 //ia32_emitf(node, "\txorpd %R, %R\n", in1, in0);
2677         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
2678                 /* is a NOP */
2679         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
2680                 /* is a NOP */
2681         } else {
2682                 panic("unexpected register class in be_Perm (%+F)", node);
2683         }
2684 }
2685
2686 static void bemit_xor0(const ir_node *node)
2687 {
2688         const arch_register_t *out = get_out_reg(node, 0);
2689         bemit8(0x31);
2690         bemit_modrr(out, out);
2691 }
2692
2693 static void bemit_mov_const(const ir_node *node)
2694 {
2695         const arch_register_t *out = get_out_reg(node, 0);
2696         bemit8(0xB8 + reg_gp_map[out->index]);
2697         bemit_immediate(node, false);
2698 }
2699
2700 /**
2701  * Creates a function for a Binop with 3 possible encodings.
2702  */
2703 #define BINOP(op, op0, op1, op2, op2_ext)                                 \
2704 static void bemit_ ## op(const ir_node *node) {                           \
2705         static const unsigned char op ## _codes[] = {op0, op1, op2, op2_ext}; \
2706         bemit_binop(node, op ## _codes);                                      \
2707 }
2708
2709 /*    insn  def  eax,imm   imm */
2710 BINOP(add,  0x03, 0x05, 0x81, 0)
2711 BINOP(or,   0x0B, 0x0D, 0x81, 1)
2712 BINOP(adc,  0x13, 0x15, 0x81, 2)
2713 BINOP(sbb,  0x1B, 0x1D, 0x81, 3)
2714 BINOP(and,  0x23, 0x25, 0x81, 4)
2715 BINOP(sub,  0x2B, 0x2D, 0x81, 5)
2716 BINOP(xor,  0x33, 0x35, 0x81, 6)
2717 BINOP(test, 0x85, 0xA9, 0xF7, 0)
2718
2719 #define BINOPMEM(op, ext) \
2720 static void bemit_##op(const ir_node *node) \
2721 { \
2722         ir_node *val; \
2723         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node)); \
2724         if (size == 16) \
2725                 bemit8(0x66); \
2726         val = get_irn_n(node, n_ia32_unary_op); \
2727         if (is_ia32_Immediate(val)) { \
2728                 const ia32_immediate_attr_t *attr   = get_ia32_immediate_attr_const(val); \
2729                 int                          offset = attr->offset; \
2730                 if (attr->symconst == NULL && get_signed_imm_size(offset) == 1) { \
2731                         bemit8(0x83); \
2732                         bemit_mod_am(ext, node); \
2733                         bemit8(offset); \
2734                 } else { \
2735                         bemit8(0x81); \
2736                         bemit_mod_am(ext, node); \
2737                         if (size == 16) { \
2738                                 bemit16(offset); \
2739                         } else { \
2740                                 bemit_entity(attr->symconst, attr->sc_sign, offset, false); \
2741                         } \
2742                 } \
2743         } else { \
2744                 bemit8(ext << 3 | 1); \
2745                 bemit_mod_am(reg_gp_map[get_out_reg(val, 0)->index], node); \
2746         } \
2747 } \
2748  \
2749 static void bemit_##op##8bit(const ir_node *node) \
2750 { \
2751         ir_node *val = get_irn_n(node, n_ia32_unary_op); \
2752         if (is_ia32_Immediate(val)) { \
2753                 bemit8(0x80); \
2754                 bemit_mod_am(ext, node); \
2755                 bemit8(get_ia32_immediate_attr_const(val)->offset); \
2756         } else { \
2757                 bemit8(ext << 3); \
2758                 bemit_mod_am(reg_gp_map[get_out_reg(val, 0)->index], node); \
2759         } \
2760 }
2761
2762 BINOPMEM(addmem,  0)
2763 BINOPMEM(ormem,   1)
2764 BINOPMEM(andmem,  4)
2765 BINOPMEM(submem,  5)
2766 BINOPMEM(xormem,  6)
2767
2768
2769 /**
2770  * Creates a function for an Unop with code /ext encoding.
2771  */
2772 #define UNOP(op, code, ext, input)              \
2773 static void bemit_ ## op(const ir_node *node) { \
2774         bemit_unop(node, code, ext, input);         \
2775 }
2776
2777 UNOP(not,     0xF7, 2, n_ia32_Not_val)
2778 UNOP(neg,     0xF7, 3, n_ia32_Neg_val)
2779 UNOP(mul,     0xF7, 4, n_ia32_Mul_right)
2780 UNOP(imul1op, 0xF7, 5, n_ia32_IMul1OP_right)
2781 UNOP(div,     0xF7, 6, n_ia32_Div_divisor)
2782 UNOP(idiv,    0xF7, 7, n_ia32_IDiv_divisor)
2783
2784 /* TODO: am support for IJmp */
2785 UNOP(ijmp,    0xFF, 4, n_ia32_IJmp_target)
2786
2787 #define SHIFT(op, ext) \
2788 static void bemit_##op(const ir_node *node) \
2789 { \
2790         const arch_register_t *out   = get_out_reg(node, 0); \
2791         ir_node               *count = get_irn_n(node, 1); \
2792         if (is_ia32_Immediate(count)) { \
2793                 int offset = get_ia32_immediate_attr_const(count)->offset; \
2794                 if (offset == 1) { \
2795                         bemit8(0xD1); \
2796                         bemit_modru(out, ext); \
2797                 } else { \
2798                         bemit8(0xC1); \
2799                         bemit_modru(out, ext); \
2800                         bemit8(offset); \
2801                 } \
2802         } else { \
2803                 bemit8(0xD3); \
2804                 bemit_modru(out, ext); \
2805         } \
2806 } \
2807  \
2808 static void bemit_##op##mem(const ir_node *node) \
2809 { \
2810         ir_node *count; \
2811         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node)); \
2812         if (size == 16) \
2813                 bemit8(0x66); \
2814         count = get_irn_n(node, 1); \
2815         if (is_ia32_Immediate(count)) { \
2816                 int offset = get_ia32_immediate_attr_const(count)->offset; \
2817                 if (offset == 1) { \
2818                         bemit8(size == 8 ? 0xD0 : 0xD1); \
2819                         bemit_mod_am(ext, node); \
2820                 } else { \
2821                         bemit8(size == 8 ? 0xC0 : 0xC1); \
2822                         bemit_mod_am(ext, node); \
2823                         bemit8(offset); \
2824                 } \
2825         } else { \
2826                 bemit8(size == 8 ? 0xD2 : 0xD3); \
2827                 bemit_mod_am(ext, node); \
2828         } \
2829 }
2830
2831 SHIFT(rol, 0)
2832 SHIFT(ror, 1)
2833 SHIFT(shl, 4)
2834 SHIFT(shr, 5)
2835 SHIFT(sar, 7)
2836
2837 static void bemit_shld(const ir_node *node)
2838 {
2839         const arch_register_t *in  = get_in_reg(node, n_ia32_ShlD_val_low);
2840         const arch_register_t *out = get_out_reg(node, pn_ia32_ShlD_res);
2841         ir_node *count = get_irn_n(node, n_ia32_ShlD_count);
2842         bemit8(0x0F);
2843         if (is_ia32_Immediate(count)) {
2844                 bemit8(0xA4);
2845                 bemit_modrr(out, in);
2846                 bemit8(get_ia32_immediate_attr_const(count)->offset);
2847         } else {
2848                 bemit8(0xA5);
2849                 bemit_modrr(out, in);
2850         }
2851 }
2852
2853 static void bemit_shrd(const ir_node *node)
2854 {
2855         const arch_register_t *in  = get_in_reg(node, n_ia32_ShrD_val_low);
2856         const arch_register_t *out = get_out_reg(node, pn_ia32_ShrD_res);
2857         ir_node *count = get_irn_n(node, n_ia32_ShrD_count);
2858         bemit8(0x0F);
2859         if (is_ia32_Immediate(count)) {
2860                 bemit8(0xAC);
2861                 bemit_modrr(out, in);
2862                 bemit8(get_ia32_immediate_attr_const(count)->offset);
2863         } else {
2864                 bemit8(0xAD);
2865                 bemit_modrr(out, in);
2866         }
2867 }
2868
2869 /**
2870  * binary emitter for setcc.
2871  */
2872 static void bemit_setcc(const ir_node *node)
2873 {
2874         const arch_register_t *dreg = get_out_reg(node, pn_ia32_Setcc_res);
2875
2876         pn_Cmp pnc = get_ia32_condcode(node);
2877         pnc        = determine_final_pnc(node, n_ia32_Setcc_eflags, pnc);
2878         if (pnc & ia32_pn_Cmp_float) {
2879                 switch (pnc & 0x0f) {
2880                 case pn_Cmp_Uo:
2881                          /* setp <dreg */
2882                         bemit8(0x0F);
2883                         bemit8(0x9A);
2884                         bemit_modrm8(REG_LOW, dreg);
2885                         return;
2886
2887                 case pn_Cmp_Leg:
2888                          /* setnp <dreg*/
2889                         bemit8(0x0F);
2890                         bemit8(0x9B);
2891                         bemit_modrm8(REG_LOW, dreg);
2892                         return;
2893
2894                 case pn_Cmp_Eq:
2895                 case pn_Cmp_Lt:
2896                 case pn_Cmp_Le:
2897                          /* set%PNC <dreg */
2898                         bemit8(0x0F);
2899                         bemit8(0x90 | pnc2cc(pnc));
2900                         bemit_modrm8(REG_LOW, dreg);
2901
2902                         /* setnp >dreg */
2903                         bemit8(0x0F);
2904                         bemit8(0x9B);
2905                         bemit_modrm8(REG_HIGH, dreg);
2906
2907                         /* andb %>dreg, %<dreg */
2908                         bemit8(0x20);
2909                         bemit_modrr8(REG_LOW, dreg, REG_HIGH, dreg);
2910                         return;
2911
2912                 case pn_Cmp_Ug:
2913                 case pn_Cmp_Uge:
2914                 case pn_Cmp_Ne:
2915                         /* set%PNC <dreg */
2916                         bemit8(0x0F);
2917                         bemit8(0x90 | pnc2cc(pnc));
2918                         bemit_modrm8(REG_LOW, dreg);
2919
2920                         /* setp >dreg */
2921                         bemit8(0x0F);
2922                         bemit8(0x9A);
2923                         bemit_modrm8(REG_HIGH, dreg);
2924
2925                         /* orb %>dreg, %<dreg */
2926                         bemit8(0x08);
2927                         bemit_modrr8(REG_LOW, dreg, REG_HIGH, dreg);
2928                         return;
2929
2930                 default:
2931                         break;
2932                 }
2933         }
2934         /* set%PNC <dreg */
2935         bemit8(0x0F);
2936         bemit8(0x90 | pnc2cc(pnc));
2937         bemit_modrm8(REG_LOW, dreg);
2938 }
2939
2940 static void bemit_cmovcc(const ir_node *node)
2941 {
2942         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
2943         int                    ins_permuted = attr->data.ins_permuted;
2944         const arch_register_t *out          = arch_irn_get_register(node, pn_ia32_res);
2945         pn_Cmp                 pnc          = get_ia32_condcode(node);
2946         const arch_register_t *in_true;
2947         const arch_register_t *in_false;
2948
2949         pnc = determine_final_pnc(node, n_ia32_CMovcc_eflags, pnc);
2950
2951         in_true  = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_true));
2952         in_false = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_false));
2953
2954         /* should be same constraint fullfilled? */
2955         if (out == in_false) {
2956                 /* yes -> nothing to do */
2957         } else if (out == in_true) {
2958                 assert(get_ia32_op_type(node) == ia32_Normal);
2959                 ins_permuted = !ins_permuted;
2960                 in_true      = in_false;
2961         } else {
2962                 /* we need a mov */
2963                 bemit8(0x8B); // mov %in_false, %out
2964                 bemit_modrr(in_false, out);
2965         }
2966
2967         if (ins_permuted)
2968                 pnc = ia32_get_negated_pnc(pnc);
2969
2970         /* TODO: handling of Nans isn't correct yet */
2971
2972         bemit8(0x0F);
2973         bemit8(0x40 | pnc2cc(pnc));
2974         if (get_ia32_op_type(node) == ia32_Normal) {
2975                 bemit_modrr(in_true, out);
2976         } else {
2977                 bemit_mod_am(reg_gp_map[out->index], node);
2978         }
2979 }
2980
2981 static void bemit_cmp(const ir_node *node)
2982 {
2983         unsigned  ls_size = get_mode_size_bits(get_ia32_ls_mode(node));
2984         ir_node  *right;
2985
2986         if (ls_size == 16)
2987                 bemit8(0x66);
2988
2989         right = get_irn_n(node, n_ia32_binary_right);
2990         if (is_ia32_Immediate(right)) {
2991                 /* Use in-reg, because some instructions (cmp, test) have no out-reg. */
2992                 const ir_node               *op   = get_irn_n(node, n_ia32_binary_right);
2993                 const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(op);
2994                 unsigned                     size;
2995
2996                 if (attr->symconst != NULL) {
2997                         size = 4;
2998                 } else {
2999                         /* check for sign extension */
3000                         size = get_signed_imm_size(attr->offset);
3001                 }
3002
3003                 switch (size) {
3004                         case 1:
3005                                 bemit8(0x81 | SIGNEXT_IMM);
3006                                 /* cmp has this special mode */
3007                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
3008                                         bemit_mod_am(7, node);
3009                                 } else {
3010                                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
3011                                         bemit_modru(reg, 7);
3012                                 }
3013                                 bemit8((unsigned char)attr->offset);
3014                                 return;
3015                         case 2:
3016                         case 4:
3017                                 /* check for eax variant: this variant is shorter for 32bit immediates only */
3018                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
3019                                         bemit8(0x81);
3020                                         bemit_mod_am(7, node);
3021                                 } else {
3022                                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
3023                                         if (reg->index == REG_EAX) {
3024                                                 bemit8(0x3D);
3025                                         } else {
3026                                                 bemit8(0x81);
3027                                                 bemit_modru(reg, 7);
3028                                         }
3029                                 }
3030                                 if (ls_size == 16) {
3031                                         bemit16(attr->offset);
3032                                 } else {
3033                                         bemit_entity(attr->symconst, attr->sc_sign, attr->offset, false);
3034                                 }
3035                                 return;
3036                 }
3037                 panic("invalid imm size?!?");
3038         } else {
3039                 const arch_register_t *out = get_in_reg(node, n_ia32_binary_left);
3040                 bemit8(0x3B);
3041                 if (get_ia32_op_type(node) == ia32_Normal) {
3042                         const arch_register_t *op2 = get_in_reg(node, n_ia32_binary_right);
3043                         bemit_modrr(op2, out);
3044                 } else {
3045                         bemit_mod_am(reg_gp_map[out->index], node);
3046                 }
3047         }
3048 }
3049
3050 static void bemit_cmp8bit(const ir_node *node)
3051 {
3052         ir_node *right = get_irn_n(node, n_ia32_binary_right);
3053         if (is_ia32_Immediate(right)) {
3054                 if (get_ia32_op_type(node) == ia32_Normal) {
3055                         const arch_register_t *out = get_in_reg(node, n_ia32_Cmp_left);
3056                         if (out->index == REG_EAX) {
3057                                 bemit8(0x3C);
3058                         } else {
3059                                 bemit8(0x80);
3060                                 bemit_modru(out, 7);
3061                         }
3062                 } else {
3063                         bemit8(0x80);
3064                         bemit_mod_am(7, node);
3065                 }
3066                 bemit8(get_ia32_immediate_attr_const(right)->offset);
3067         } else {
3068                 const arch_register_t *out = get_in_reg(node, n_ia32_Cmp_left);
3069                 bemit8(0x3A);
3070                 if (get_ia32_op_type(node) == ia32_Normal) {
3071                         const arch_register_t *in = get_in_reg(node, n_ia32_Cmp_right);
3072                         bemit_modrr(out, in);
3073                 } else {
3074                         bemit_mod_am(reg_gp_map[out->index], node);
3075                 }
3076         }
3077 }
3078
3079 static void bemit_test8bit(const ir_node *node)
3080 {
3081         ir_node *right = get_irn_n(node, n_ia32_Test8Bit_right);
3082         if (is_ia32_Immediate(right)) {
3083                 if (get_ia32_op_type(node) == ia32_Normal) {
3084                         const arch_register_t *out = get_in_reg(node, n_ia32_Test8Bit_left);
3085                         if (out->index == REG_EAX) {
3086                                 bemit8(0xA8);
3087                         } else {
3088                                 bemit8(0xF6);
3089                                 bemit_modru(out, 0);
3090                         }
3091                 } else {
3092                         bemit8(0xF6);
3093                         bemit_mod_am(0, node);
3094                 }
3095                 bemit8(get_ia32_immediate_attr_const(right)->offset);
3096         } else {
3097                 const arch_register_t *out = get_in_reg(node, n_ia32_Test8Bit_left);
3098                 bemit8(0x84);
3099                 if (get_ia32_op_type(node) == ia32_Normal) {
3100                         const arch_register_t *in = get_in_reg(node, n_ia32_Test8Bit_right);
3101                         bemit_modrr(out, in);
3102                 } else {
3103                         bemit_mod_am(reg_gp_map[out->index], node);
3104                 }
3105         }
3106 }
3107
3108 static void bemit_imul(const ir_node *node)
3109 {
3110         ir_node *right = get_irn_n(node, n_ia32_IMul_right);
3111         /* Do we need the immediate form? */
3112         if (is_ia32_Immediate(right)) {
3113                 int imm = get_ia32_immediate_attr_const(right)->offset;
3114                 if (get_signed_imm_size(imm) == 1) {
3115                         bemit_unop_reg(node, 0x6B, n_ia32_IMul_left);
3116                         bemit8(imm);
3117                 } else {
3118                         bemit_unop_reg(node, 0x69, n_ia32_IMul_left);
3119                         bemit32(imm);
3120                 }
3121         } else {
3122                 bemit8(0x0F);
3123                 bemit_unop_reg(node, 0xAF, n_ia32_IMul_right);
3124         }
3125 }
3126
3127 static void bemit_dec(const ir_node *node)
3128 {
3129         const arch_register_t *out = get_out_reg(node, pn_ia32_Dec_res);
3130         bemit8(0x48 + reg_gp_map[out->index]);
3131 }
3132
3133 static void bemit_inc(const ir_node *node)
3134 {
3135         const arch_register_t *out = get_out_reg(node, pn_ia32_Inc_res);
3136         bemit8(0x40 + reg_gp_map[out->index]);
3137 }
3138
3139 #define UNOPMEM(op, code, ext) \
3140 static void bemit_##op(const ir_node *node) \
3141 { \
3142         bemit_unop_mem(node, code, ext); \
3143 }
3144
3145 UNOPMEM(notmem, 0xF6, 2)
3146 UNOPMEM(negmem, 0xF6, 3)
3147 UNOPMEM(incmem, 0xFE, 0)
3148 UNOPMEM(decmem, 0xFE, 1)
3149
3150 static void bemit_ldtls(const ir_node *node)
3151 {
3152         const arch_register_t *out = get_out_reg(node, 0);
3153
3154         bemit8(0x65); // gs:
3155         if (out->index == REG_EAX) {
3156                 bemit8(0xA1); // movl 0, %eax
3157         } else {
3158                 bemit8(0x8B); // movl 0, %reg
3159                 bemit8(MOD_IND | ENC_REG(reg_gp_map[out->index]) | ENC_RM(0x05));
3160         }
3161         bemit32(0);
3162 }
3163
3164 /**
3165  * Emit a Lea.
3166  */
3167 static void bemit_lea(const ir_node *node)
3168 {
3169         const arch_register_t *out = get_out_reg(node, 0);
3170         bemit8(0x8D);
3171         bemit_mod_am(reg_gp_map[out->index], node);
3172 }
3173
3174 /* helper function for bemit_minus64bit */
3175 static void bemit_helper_mov(const arch_register_t *src, const arch_register_t *dst)
3176 {
3177         bemit8(0x8B); // movl %src, %dst
3178         bemit_modrr(src, dst);
3179 }
3180
3181 /* helper function for bemit_minus64bit */
3182 static void bemit_helper_neg(const arch_register_t *reg)
3183 {
3184         bemit8(0xF7); // negl %reg
3185         bemit_modru(reg, 3);
3186 }
3187
3188 /* helper function for bemit_minus64bit */
3189 static void bemit_helper_sbb0(const arch_register_t *reg)
3190 {
3191         bemit8(0x83); // sbbl $0, %reg
3192         bemit_modru(reg, 3);
3193         bemit8(0);
3194 }
3195
3196 /* helper function for bemit_minus64bit */
3197 static void bemit_helper_sbb(const arch_register_t *src, const arch_register_t *dst)
3198 {
3199         bemit8(0x1B); // sbbl %src, %dst
3200         bemit_modrr(src, dst);
3201 }
3202
3203 /* helper function for bemit_minus64bit */
3204 static void bemit_helper_xchg(const arch_register_t *src, const arch_register_t *dst)
3205 {
3206         if (src->index == REG_EAX) {
3207                 bemit8(0x90 + reg_gp_map[dst->index]); // xchgl %eax, %dst
3208         } else if (dst->index == REG_EAX) {
3209                 bemit8(0x90 + reg_gp_map[src->index]); // xchgl %src, %eax
3210         } else {
3211                 bemit8(0x87); // xchgl %src, %dst
3212                 bemit_modrr(src, dst);
3213         }
3214 }
3215
3216 /* helper function for bemit_minus64bit */
3217 static void bemit_helper_zero(const arch_register_t *reg)
3218 {
3219         bemit8(0x33); // xorl %reg, %reg
3220         bemit_modrr(reg, reg);
3221 }
3222
3223 static void bemit_minus64bit(const ir_node *node)
3224 {
3225         const arch_register_t *in_lo  = get_in_reg(node, 0);
3226         const arch_register_t *in_hi  = get_in_reg(node, 1);
3227         const arch_register_t *out_lo = get_out_reg(node, 0);
3228         const arch_register_t *out_hi = get_out_reg(node, 1);
3229
3230         if (out_lo == in_lo) {
3231                 if (out_hi != in_hi) {
3232                         /* a -> a, b -> d */
3233                         goto zero_neg;
3234                 } else {
3235                         /* a -> a, b -> b */
3236                         goto normal_neg;
3237                 }
3238         } else if (out_lo == in_hi) {
3239                 if (out_hi == in_lo) {
3240                         /* a -> b, b -> a */
3241                         bemit_helper_xchg(in_lo, in_hi);
3242                         goto normal_neg;
3243                 } else {
3244                         /* a -> b, b -> d */
3245                         bemit_helper_mov(in_hi, out_hi);
3246                         bemit_helper_mov(in_lo, out_lo);
3247                         goto normal_neg;
3248                 }
3249         } else {
3250                 if (out_hi == in_lo) {
3251                         /* a -> c, b -> a */
3252                         bemit_helper_mov(in_lo, out_lo);
3253                         goto zero_neg;
3254                 } else if (out_hi == in_hi) {
3255                         /* a -> c, b -> b */
3256                         bemit_helper_mov(in_lo, out_lo);
3257                         goto normal_neg;
3258                 } else {
3259                         /* a -> c, b -> d */
3260                         bemit_helper_mov(in_lo, out_lo);
3261                         goto zero_neg;
3262                 }
3263         }
3264
3265 normal_neg:
3266         bemit_helper_neg( out_hi);
3267         bemit_helper_neg( out_lo);
3268         bemit_helper_sbb0(out_hi);
3269         return;
3270
3271 zero_neg:
3272         bemit_helper_zero(out_hi);
3273         bemit_helper_neg( out_lo);
3274         bemit_helper_sbb( in_hi, out_hi);
3275 }
3276
3277 /**
3278  * Emit a single opcode.
3279  */
3280 #define EMIT_SINGLEOP(op, code)                 \
3281 static void bemit_ ## op(const ir_node *node) { \
3282         (void) node;                                \
3283         bemit8(code);                               \
3284 }
3285
3286 //EMIT_SINGLEOP(daa,  0x27)
3287 //EMIT_SINGLEOP(das,  0x2F)
3288 //EMIT_SINGLEOP(aaa,  0x37)
3289 //EMIT_SINGLEOP(aas,  0x3F)
3290 //EMIT_SINGLEOP(nop,  0x90)
3291 EMIT_SINGLEOP(cwtl,  0x98)
3292 EMIT_SINGLEOP(cltd,  0x99)
3293 //EMIT_SINGLEOP(fwait, 0x9B)
3294 EMIT_SINGLEOP(sahf,  0x9E)
3295 //EMIT_SINGLEOP(popf, 0x9D)
3296 EMIT_SINGLEOP(leave, 0xC9)
3297 EMIT_SINGLEOP(int3,  0xCC)
3298 //EMIT_SINGLEOP(iret, 0xCF)
3299 //EMIT_SINGLEOP(xlat, 0xD7)
3300 //EMIT_SINGLEOP(lock, 0xF0)
3301 EMIT_SINGLEOP(rep,   0xF3)
3302 //EMIT_SINGLEOP(halt, 0xF4)
3303 EMIT_SINGLEOP(cmc,   0xF5)
3304 EMIT_SINGLEOP(stc,   0xF9)
3305 //EMIT_SINGLEOP(cli,  0xFA)
3306 //EMIT_SINGLEOP(sti,  0xFB)
3307 //EMIT_SINGLEOP(std,  0xFD)
3308
3309 /**
3310  * Emits a MOV out, [MEM].
3311  */
3312 static void bemit_load(const ir_node *node)
3313 {
3314         const arch_register_t *out = get_out_reg(node, 0);
3315
3316         if (out->index == REG_EAX) {
3317                 ir_node   *base      = get_irn_n(node, n_ia32_base);
3318                 int        has_base  = !is_ia32_NoReg_GP(base);
3319                 ir_node   *index     = get_irn_n(node, n_ia32_index);
3320                 int        has_index = !is_ia32_NoReg_GP(index);
3321                 if (!has_base && !has_index) {
3322                         ir_entity *ent  = get_ia32_am_sc(node);
3323                         int        offs = get_ia32_am_offs_int(node);
3324                         /* load from constant address to EAX can be encoded
3325                            as 0xA1 [offset] */
3326                         bemit8(0xA1);
3327                         bemit_entity(ent, 0, offs, false);
3328                         return;
3329                 }
3330         }
3331         bemit8(0x8B);
3332         bemit_mod_am(reg_gp_map[out->index], node);
3333 }
3334
3335 /**
3336  * Emits a MOV [mem], in.
3337  */
3338 static void bemit_store(const ir_node *node)
3339 {
3340         const ir_node *value = get_irn_n(node, n_ia32_Store_val);
3341         unsigned       size  = get_mode_size_bits(get_ia32_ls_mode(node));
3342
3343         if (is_ia32_Immediate(value)) {
3344                 if (size == 8) {
3345                         bemit8(0xC6);
3346                         bemit_mod_am(0, node);
3347                         bemit8(get_ia32_immediate_attr_const(value)->offset);
3348                 } else if (size == 16) {
3349                         bemit8(0x66);
3350                         bemit8(0xC7);
3351                         bemit_mod_am(0, node);
3352                         bemit16(get_ia32_immediate_attr_const(value)->offset);
3353                 } else {
3354                         bemit8(0xC7);
3355                         bemit_mod_am(0, node);
3356                         bemit_immediate(value, false);
3357                 }
3358         } else {
3359                 const arch_register_t *in = get_in_reg(node, n_ia32_Store_val);
3360
3361                 if (in->index == REG_EAX) {
3362                         ir_node   *base      = get_irn_n(node, n_ia32_base);
3363                         int        has_base  = !is_ia32_NoReg_GP(base);
3364                         ir_node   *index     = get_irn_n(node, n_ia32_index);
3365                         int        has_index = !is_ia32_NoReg_GP(index);
3366                         if (!has_base && !has_index) {
3367                                 ir_entity *ent  = get_ia32_am_sc(node);
3368                                 int        offs = get_ia32_am_offs_int(node);
3369                                 /* store to constant address from EAX can be encoded as
3370                                  * 0xA2/0xA3 [offset]*/
3371                                 if (size == 8) {
3372                                         bemit8(0xA2);
3373                                 } else {
3374                                         if (size == 16)
3375                                                 bemit8(0x66);
3376                                         bemit8(0xA3);
3377                                 }
3378                                 bemit_entity(ent, 0, offs, false);
3379                                 return;
3380                         }
3381                 }
3382
3383                 if (size == 8) {
3384                         bemit8(0x88);
3385                 } else {
3386                         if (size == 16)
3387                                 bemit8(0x66);
3388                         bemit8(0x89);
3389                 }
3390                 bemit_mod_am(reg_gp_map[in->index], node);
3391         }
3392 }
3393
3394 static void bemit_conv_i2i(const ir_node *node)
3395 {
3396         ir_mode  *smaller_mode = get_ia32_ls_mode(node);
3397         unsigned  opcode;
3398
3399         bemit8(0x0F);
3400         /*        8 16 bit source
3401          * movzx B6 B7
3402          * movsx BE BF
3403          */
3404         opcode = 0xB6;
3405         if (mode_is_signed(smaller_mode))           opcode |= 0x08;
3406         if (get_mode_size_bits(smaller_mode) == 16) opcode |= 0x01;
3407         bemit_unop_reg(node, opcode, n_ia32_Conv_I2I_val);
3408 }
3409
3410 /**
3411  * Emit a Push.
3412  */
3413 static void bemit_push(const ir_node *node)
3414 {
3415         const ir_node *value = get_irn_n(node, n_ia32_Push_val);
3416
3417         if (is_ia32_Immediate(value)) {
3418                 const ia32_immediate_attr_t *attr
3419                         = get_ia32_immediate_attr_const(value);
3420                 unsigned size = get_signed_imm_size(attr->offset);
3421                 if (attr->symconst)
3422                         size = 4;
3423                 switch (size) {
3424                 case 1:
3425                         bemit8(0x6A);
3426                         bemit8((unsigned char)attr->offset);
3427                         break;
3428                 case 2:
3429                 case 4:
3430                         bemit8(0x68);
3431                         bemit_immediate(value, false);
3432                         break;
3433                 }
3434         } else if (is_ia32_NoReg_GP(value)) {
3435                 bemit8(0xFF);
3436                 bemit_mod_am(6, node);
3437         } else {
3438                 const arch_register_t *reg = get_in_reg(node, n_ia32_Push_val);
3439                 bemit8(0x50 + reg_gp_map[reg->index]);
3440         }
3441 }
3442
3443 /**
3444  * Emit a Pop.
3445  */
3446 static void bemit_pop(const ir_node *node)
3447 {
3448         const arch_register_t *reg = get_out_reg(node, pn_ia32_Pop_res);
3449         bemit8(0x58 + reg_gp_map[reg->index]);
3450 }
3451
3452 static void bemit_popmem(const ir_node *node)
3453 {
3454         bemit8(0x8F);
3455         bemit_mod_am(0, node);
3456 }
3457
3458 static void bemit_call(const ir_node *node)
3459 {
3460         ir_node *proc = get_irn_n(node, n_ia32_Call_addr);
3461
3462         if (is_ia32_Immediate(proc)) {
3463                 bemit8(0xE8);
3464                 bemit_immediate(proc, true);
3465         } else {
3466                 bemit_unop(node, 0xFF, 2, n_ia32_Call_addr);
3467         }
3468 }
3469
3470 static void bemit_jmp(const ir_node *dest_block)
3471 {
3472         bemit8(0xE9);
3473         bemit_jmp_destination(dest_block);
3474 }
3475
3476 static void bemit_jump(const ir_node *node)
3477 {
3478         if (can_be_fallthrough(node))
3479                 return;
3480
3481         bemit_jmp(get_cfop_target_block(node));
3482 }
3483
3484 static void bemit_jcc(int pnc, const ir_node *dest_block)
3485 {
3486         unsigned char cc = pnc2cc(pnc);
3487         bemit8(0x0F);
3488         bemit8(0x80 + cc);
3489         bemit_jmp_destination(dest_block);
3490 }
3491
3492 static void bemit_jp(bool odd, const ir_node *dest_block)
3493 {
3494         bemit8(0x0F);
3495         bemit8(0x8A + odd);
3496         bemit_jmp_destination(dest_block);
3497 }
3498
3499 static void bemit_ia32_jcc(const ir_node *node)
3500 {
3501         int            pnc = get_ia32_condcode(node);
3502         const ir_node *proj_true;
3503         const ir_node *proj_false;
3504         const ir_node *dest_true;
3505         const ir_node *dest_false;
3506         const ir_node *block;
3507
3508         pnc = determine_final_pnc(node, 0, pnc);
3509
3510         /* get both Projs */
3511         proj_true = get_proj(node, pn_ia32_Jcc_true);
3512         assert(proj_true && "Jcc without true Proj");
3513
3514         proj_false = get_proj(node, pn_ia32_Jcc_false);
3515         assert(proj_false && "Jcc without false Proj");
3516
3517         block = get_nodes_block(node);
3518
3519         if (can_be_fallthrough(proj_true)) {
3520                 /* exchange both proj's so the second one can be omitted */
3521                 const ir_node *t = proj_true;
3522
3523                 proj_true  = proj_false;
3524                 proj_false = t;
3525                 pnc        = ia32_get_negated_pnc(pnc);
3526         }
3527
3528         dest_true  = get_cfop_target_block(proj_true);
3529         dest_false = get_cfop_target_block(proj_false);
3530
3531         if (pnc & ia32_pn_Cmp_float) {
3532                 /* Some floating point comparisons require a test of the parity flag,
3533                  * which indicates that the result is unordered */
3534                 switch (pnc & 15) {
3535                         case pn_Cmp_Uo: {
3536                                 bemit_jp(false, dest_true);
3537                                 break;
3538                         }
3539
3540                         case pn_Cmp_Leg:
3541                                 bemit_jp(true, dest_true);
3542                                 break;
3543
3544                         case pn_Cmp_Eq:
3545                         case pn_Cmp_Lt:
3546                         case pn_Cmp_Le:
3547                                 /* we need a local label if the false proj is a fallthrough
3548                                  * as the falseblock might have no label emitted then */
3549                                 if (can_be_fallthrough(proj_false)) {
3550                                         bemit8(0x7A);
3551                                         bemit8(0x06);  // jp + 6
3552                                 } else {
3553                                         bemit_jp(false, dest_false);
3554                                 }
3555                                 goto emit_jcc;
3556
3557                         case pn_Cmp_Ug:
3558                         case pn_Cmp_Uge:
3559                         case pn_Cmp_Ne:
3560                                 bemit_jp(false, dest_true);
3561                                 goto emit_jcc;
3562
3563                         default:
3564                                 goto emit_jcc;
3565                 }
3566         } else {
3567 emit_jcc:
3568                 bemit_jcc(pnc, dest_true);
3569         }
3570
3571         /* the second Proj might be a fallthrough */
3572         if (can_be_fallthrough(proj_false)) {
3573                 /* it's a fallthrough */
3574         } else {
3575                 bemit_jmp(dest_false);
3576         }
3577 }
3578
3579 static void bemit_switchjmp(const ir_node *node)
3580 {
3581         unsigned long          interval;
3582         int                    last_value;
3583         int                    i;
3584         jmp_tbl_t              tbl;
3585         const arch_register_t *in;
3586
3587         /* fill the table structure */
3588         generate_jump_table(&tbl, node);
3589
3590         /* two-complement's magic make this work without overflow */
3591         interval = tbl.max_value - tbl.min_value;
3592
3593         in = get_in_reg(node, 0);
3594         /* emit the table */
3595         if (get_signed_imm_size(interval) == 1) {
3596                 bemit8(0x83); // cmpl $imm8, %in
3597                 bemit_modru(in, 7);
3598                 bemit8(interval);
3599         } else {
3600                 bemit8(0x81); // cmpl $imm32, %in
3601                 bemit_modru(in, 7);
3602                 bemit32(interval);
3603         }
3604         bemit8(0x0F); // ja tbl.defProj
3605         bemit8(0x87);
3606         ia32_emitf(tbl.defProj, ".long %L - . - 4\n");
3607
3608         if (tbl.num_branches > 1) {
3609                 /* create table */
3610                 bemit8(0xFF); // jmp *tbl.label(,%in,4)
3611                 bemit8(MOD_IND | ENC_REG(4) | ENC_RM(0x04));
3612                 bemit8(ENC_SIB(2, reg_gp_map[in->index], 0x05));
3613                 be_emit_irprintf("\t.long %s\n", tbl.label);
3614
3615                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
3616                 be_emit_cstring(".align 4\n");
3617                 be_emit_irprintf("%s:\n", tbl.label);
3618
3619                 last_value = tbl.branches[0].value;
3620                 for (i = 0; i != tbl.num_branches; ++i) {
3621                         while (last_value != tbl.branches[i].value) {
3622                                 ia32_emitf(tbl.defProj, ".long %L\n");
3623                                 ++last_value;
3624                         }
3625                         ia32_emitf(tbl.branches[i].target, ".long %L\n");
3626                         ++last_value;
3627                 }
3628                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
3629         } else {
3630                 /* one jump is enough */
3631                 panic("switch only has one case");
3632                 //ia32_emitf(tbl.branches[0].target, "\tjmp %L\n");
3633         }
3634
3635         be_emit_write_line();
3636
3637         free(tbl.branches);
3638 }
3639
3640 /**
3641  * Emits a return.
3642  */
3643 static void bemit_return(const ir_node *node)
3644 {
3645         unsigned pop = be_Return_get_pop(node);
3646         if (pop > 0 || be_Return_get_emit_pop(node)) {
3647                 bemit8(0xC2);
3648                 assert(pop <= 0xffff);
3649                 bemit16(pop);
3650         } else {
3651                 bemit8(0xC3);
3652         }
3653 }
3654
3655 static void bemit_subsp(const ir_node *node)
3656 {
3657         const arch_register_t *out;
3658         /* sub %in, %esp */
3659         bemit_sub(node);
3660         /* mov %esp, %out */
3661         bemit8(0x8B);
3662         out = get_out_reg(node, 1);
3663         bemit8(MOD_REG | ENC_REG(reg_gp_map[out->index]) | ENC_RM(0x04));
3664 }
3665
3666 static void bemit_incsp(const ir_node *node)
3667 {
3668         int                    offs;
3669         const arch_register_t *reg;
3670         unsigned               size;
3671         unsigned               ext;
3672
3673         offs = be_get_IncSP_offset(node);
3674         if (offs == 0)
3675                 return;
3676
3677         if (offs > 0) {
3678                 ext = 5; /* sub */
3679         } else {
3680                 ext = 0; /* add */
3681                 offs = -offs;
3682         }
3683
3684         size = get_signed_imm_size(offs);
3685         bemit8(size == 1 ? 0x83 : 0x81);
3686
3687         reg  = get_out_reg(node, 0);
3688         bemit_modru(reg, ext);
3689
3690         if (size == 1) {
3691                 bemit8(offs);
3692         } else {
3693                 bemit32(offs);
3694         }
3695 }
3696
3697 static void bemit_copybi(const ir_node *node)
3698 {
3699         unsigned size = get_ia32_copyb_size(node);
3700         if (size & 1)
3701                 bemit8(0xA4); // movsb
3702         if (size & 2) {
3703                 bemit8(0x66);
3704                 bemit8(0xA5); // movsw
3705         }
3706         size >>= 2;
3707         while (size--) {
3708                 bemit8(0xA5); // movsl
3709         }
3710 }
3711
3712 static void bemit_fbinop(const ir_node *node, unsigned code, unsigned code_to)
3713 {
3714         if (get_ia32_op_type(node) == ia32_Normal) {
3715                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
3716                 const arch_register_t *in1      = x87_attr->x87[0];
3717                 const arch_register_t *in       = x87_attr->x87[1];
3718                 const arch_register_t *out      = x87_attr->x87[2];
3719
3720                 if (out == NULL) {
3721                         out = in1;
3722                 } else if (out == in) {
3723                         in = in1;
3724                 }
3725
3726                 if (out->index == 0) {
3727                         bemit8(0xD8);
3728                         bemit8(MOD_REG | ENC_REG(code) | ENC_RM(in->index));
3729                 } else {
3730                         bemit8(0xDC);
3731                         bemit8(MOD_REG | ENC_REG(code_to) | ENC_RM(out->index));
3732                 }
3733         } else {
3734                 if (get_mode_size_bits(get_ia32_ls_mode(node)) == 32) {
3735                         bemit8(0xD8);
3736                 } else {
3737                         bemit8(0xDC);
3738                 }
3739                 bemit_mod_am(code, node);
3740         }
3741 }
3742
3743 static void bemit_fbinopp(const ir_node *node, unsigned const code)
3744 {
3745         const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
3746         const arch_register_t *out      = x87_attr->x87[2];
3747         bemit8(0xDE);
3748         bemit8(code + out->index);
3749 }
3750
3751 static void bemit_fabs(const ir_node *node)
3752 {
3753         (void)node;
3754
3755         bemit8(0xD9);
3756         bemit8(0xE1);
3757 }
3758
3759 static void bemit_fadd(const ir_node *node)
3760 {
3761         bemit_fbinop(node, 0, 0);
3762 }
3763
3764 static void bemit_faddp(const ir_node *node)
3765 {
3766         bemit_fbinopp(node, 0xC0);
3767 }
3768
3769 static void bemit_fchs(const ir_node *node)
3770 {
3771         (void)node;
3772
3773         bemit8(0xD9);
3774         bemit8(0xE0);
3775 }
3776
3777 static void bemit_fdiv(const ir_node *node)
3778 {
3779         bemit_fbinop(node, 6, 7);
3780 }
3781
3782 static void bemit_fdivp(const ir_node *node)
3783 {
3784         bemit_fbinopp(node, 0xF8);
3785 }
3786
3787 static void bemit_fdivr(const ir_node *node)
3788 {
3789         bemit_fbinop(node, 7, 6);
3790 }
3791
3792 static void bemit_fdivrp(const ir_node *node)
3793 {
3794         bemit_fbinopp(node, 0xF0);
3795 }
3796
3797 static void bemit_fild(const ir_node *node)
3798 {
3799         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3800                 case 16:
3801                         bemit8(0xDF); // filds
3802                         bemit_mod_am(0, node);
3803                         return;
3804
3805                 case 32:
3806                         bemit8(0xDB); // fildl
3807                         bemit_mod_am(0, node);
3808                         return;
3809
3810                 case 64:
3811                         bemit8(0xDF); // fildll
3812                         bemit_mod_am(5, node);
3813                         return;
3814
3815                 default:
3816                         panic("invalid mode size");
3817         }
3818 }
3819
3820 static void bemit_fist(const ir_node *node)
3821 {
3822         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3823                 case 16:
3824                         bemit8(0xDF); // fists
3825                         break;
3826
3827                 case 32:
3828                         bemit8(0xDB); // fistl
3829                         break;
3830
3831                 default:
3832                         panic("invalid mode size");
3833         }
3834         bemit_mod_am(2, node);
3835 }
3836
3837 static void bemit_fistp(const ir_node *node)
3838 {
3839         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3840                 case 16:
3841                         bemit8(0xDF); // fistps
3842                         bemit_mod_am(3, node);
3843                         return;
3844
3845                 case 32:
3846                         bemit8(0xDB); // fistpl
3847                         bemit_mod_am(3, node);
3848                         return;
3849
3850                 case 64:
3851                         bemit8(0xDF); // fistpll
3852                         bemit_mod_am(7, node);
3853                         return;
3854
3855                 default:
3856                         panic("invalid mode size");
3857         }
3858 }
3859
3860 static void bemit_fld(const ir_node *node)
3861 {
3862         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3863                 case 32:
3864                         bemit8(0xD9); // flds
3865                         bemit_mod_am(0, node);
3866                         return;
3867
3868                 case 64:
3869                         bemit8(0xDD); // fldl
3870                         bemit_mod_am(0, node);
3871                         return;
3872
3873                 case 80:
3874                 case 96:
3875                         bemit8(0xDB); // fldt
3876                         bemit_mod_am(5, node);
3877                         return;
3878
3879                 default:
3880                         panic("invalid mode size");
3881         }
3882 }
3883
3884 static void bemit_fld1(const ir_node *node)
3885 {
3886         (void)node;
3887         bemit8(0xD9);
3888         bemit8(0xE8); // fld1
3889 }
3890
3891 static void bemit_fldcw(const ir_node *node)
3892 {
3893         bemit8(0xD9); // fldcw
3894         bemit_mod_am(5, node);
3895 }
3896
3897 static void bemit_fldz(const ir_node *node)
3898 {
3899         (void)node;
3900         bemit8(0xD9);
3901         bemit8(0xEE); // fldz
3902 }
3903
3904 static void bemit_fmul(const ir_node *node)
3905 {
3906         bemit_fbinop(node, 1, 1);
3907 }
3908
3909 static void bemit_fmulp(const ir_node *node)
3910 {
3911         bemit_fbinopp(node, 0xC8);
3912 }
3913
3914 static void bemit_fpop(const ir_node *node)
3915 {
3916         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
3917         bemit8(0xDD);
3918         bemit8(0xD8 + attr->x87[0]->index);
3919 }
3920
3921 static void bemit_fpush(const ir_node *node)
3922 {
3923         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
3924         bemit8(0xD9);
3925         bemit8(0xC0 + attr->x87[0]->index);
3926 }
3927
3928 static void bemit_fpushcopy(const ir_node *node)
3929 {
3930         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
3931         bemit8(0xD9);
3932         bemit8(0xC0 + attr->x87[0]->index);
3933 }
3934
3935 static void bemit_fst(const ir_node *node)
3936 {
3937         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3938                 case 32:
3939                         bemit8(0xD9); // fsts
3940                         break;
3941
3942                 case 64:
3943                         bemit8(0xDD); // fstl
3944                         break;
3945
3946                 default:
3947                         panic("invalid mode size");
3948         }
3949         bemit_mod_am(2, node);
3950 }
3951
3952 static void bemit_fstp(const ir_node *node)
3953 {
3954         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3955                 case 32:
3956                         bemit8(0xD9); // fstps
3957                         bemit_mod_am(3, node);
3958                         return;
3959
3960                 case 64:
3961                         bemit8(0xDD); // fstpl
3962                         bemit_mod_am(3, node);
3963                         return;
3964
3965                 case 80:
3966                 case 96:
3967                         bemit8(0xDB); // fstpt
3968                         bemit_mod_am(7, node);
3969                         return;
3970
3971                 default:
3972                         panic("invalid mode size");
3973         }
3974 }
3975
3976 static void bemit_fsub(const ir_node *node)
3977 {
3978         bemit_fbinop(node, 4, 5);
3979 }
3980
3981 static void bemit_fsubp(const ir_node *node)
3982 {
3983         bemit_fbinopp(node, 0xE8);
3984 }
3985
3986 static void bemit_fsubr(const ir_node *node)
3987 {
3988         bemit_fbinop(node, 5, 4);
3989 }
3990
3991 static void bemit_fsubrp(const ir_node *node)
3992 {
3993         bemit_fbinopp(node, 0xE0);
3994 }
3995
3996 static void bemit_fnstcw(const ir_node *node)
3997 {
3998         bemit8(0xD9); // fnstcw
3999         bemit_mod_am(7, node);
4000 }
4001
4002 static void bemit_fnstsw(void)
4003 {
4004         bemit8(0xDF); // fnstsw %ax
4005         bemit8(0xE0);
4006 }
4007
4008 static void bemit_ftstfnstsw(const ir_node *node)
4009 {
4010         (void)node;
4011
4012         bemit8(0xD9); // ftst
4013         bemit8(0xE4);
4014         bemit_fnstsw();
4015 }
4016
4017 static void bemit_fucomi(const ir_node *node)
4018 {
4019         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4020         bemit8(0xDB); // fucomi
4021         bemit8(0xE8 + attr->x87[1]->index);
4022 }
4023
4024 static void bemit_fucomip(const ir_node *node)
4025 {
4026         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4027         bemit8(0xDF); // fucomip
4028         bemit8(0xE8 + attr->x87[1]->index);
4029 }
4030
4031 static void bemit_fucomfnstsw(const ir_node *node)
4032 {
4033         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4034         bemit8(0xDD); // fucom
4035         bemit8(0xE0 + attr->x87[1]->index);
4036         bemit_fnstsw();
4037 }
4038
4039 static void bemit_fucompfnstsw(const ir_node *node)
4040 {
4041         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4042         bemit8(0xDD); // fucomp
4043         bemit8(0xE8 + attr->x87[1]->index);
4044         bemit_fnstsw();
4045 }
4046
4047 static void bemit_fucomppfnstsw(const ir_node *node)
4048 {
4049         (void)node;
4050
4051         bemit8(0xDA); // fucompp
4052         bemit8(0xE9);
4053         bemit_fnstsw();
4054 }
4055
4056 static void bemit_fxch(const ir_node *node)
4057 {
4058         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4059         bemit8(0xD9);
4060         bemit8(0xC8 + attr->x87[0]->index);
4061 }
4062
4063 /**
4064  * The type of a emitter function.
4065  */
4066 typedef void (*emit_func) (const ir_node *);
4067
4068 /**
4069  * Set a node emitter. Make it a bit more type safe.
4070  */
4071 static void register_emitter(ir_op *op, emit_func func)
4072 {
4073         op->ops.generic = (op_func) func;
4074 }
4075
4076 static void ia32_register_binary_emitters(void)
4077 {
4078         /* first clear the generic function pointer for all ops */
4079         clear_irp_opcodes_generic_func();
4080
4081         /* benode emitter */
4082         register_emitter(op_be_Copy,            bemit_copy);
4083         register_emitter(op_be_CopyKeep,        bemit_copy);
4084         register_emitter(op_be_IncSP,           bemit_incsp);
4085         register_emitter(op_be_Perm,            bemit_perm);
4086         register_emitter(op_be_Return,          bemit_return);
4087         register_emitter(op_ia32_Adc,           bemit_adc);
4088         register_emitter(op_ia32_Add,           bemit_add);
4089         register_emitter(op_ia32_AddMem,        bemit_addmem);
4090         register_emitter(op_ia32_AddMem8Bit,    bemit_addmem8bit);
4091         register_emitter(op_ia32_And,           bemit_and);
4092         register_emitter(op_ia32_AndMem,        bemit_andmem);
4093         register_emitter(op_ia32_AndMem8Bit,    bemit_andmem8bit);
4094         register_emitter(op_ia32_Breakpoint,    bemit_int3);
4095         register_emitter(op_ia32_CMovcc,        bemit_cmovcc);
4096         register_emitter(op_ia32_Call,          bemit_call);
4097         register_emitter(op_ia32_Cltd,          bemit_cltd);
4098         register_emitter(op_ia32_Cmc,           bemit_cmc);
4099         register_emitter(op_ia32_Cmp,           bemit_cmp);
4100         register_emitter(op_ia32_Cmp8Bit,       bemit_cmp8bit);
4101         register_emitter(op_ia32_Const,         bemit_mov_const);
4102         register_emitter(op_ia32_Conv_I2I,      bemit_conv_i2i);
4103         register_emitter(op_ia32_Conv_I2I8Bit,  bemit_conv_i2i);
4104         register_emitter(op_ia32_CopyB_i,       bemit_copybi);
4105         register_emitter(op_ia32_Cwtl,          bemit_cwtl);
4106         register_emitter(op_ia32_Dec,           bemit_dec);
4107         register_emitter(op_ia32_DecMem,        bemit_decmem);
4108         register_emitter(op_ia32_Div,           bemit_div);
4109         register_emitter(op_ia32_FldCW,         bemit_fldcw);
4110         register_emitter(op_ia32_FnstCW,        bemit_fnstcw);
4111         register_emitter(op_ia32_FtstFnstsw,    bemit_ftstfnstsw);
4112         register_emitter(op_ia32_FucomFnstsw,   bemit_fucomfnstsw);
4113         register_emitter(op_ia32_Fucomi,        bemit_fucomi);
4114         register_emitter(op_ia32_FucompFnstsw,  bemit_fucompfnstsw);
4115         register_emitter(op_ia32_Fucompi,       bemit_fucomip);
4116         register_emitter(op_ia32_FucomppFnstsw, bemit_fucomppfnstsw);
4117         register_emitter(op_ia32_IDiv,          bemit_idiv);
4118         register_emitter(op_ia32_IJmp,          bemit_ijmp);
4119         register_emitter(op_ia32_IMul,          bemit_imul);
4120         register_emitter(op_ia32_IMul1OP,       bemit_imul1op);
4121         register_emitter(op_ia32_Inc,           bemit_inc);
4122         register_emitter(op_ia32_IncMem,        bemit_incmem);
4123         register_emitter(op_ia32_Jcc,           bemit_ia32_jcc);
4124         register_emitter(op_ia32_Jmp,           bemit_jump);
4125         register_emitter(op_ia32_LdTls,         bemit_ldtls);
4126         register_emitter(op_ia32_Lea,           bemit_lea);
4127         register_emitter(op_ia32_Leave,         bemit_leave);
4128         register_emitter(op_ia32_Load,          bemit_load);
4129         register_emitter(op_ia32_Minus64Bit,    bemit_minus64bit);
4130         register_emitter(op_ia32_Mul,           bemit_mul);
4131         register_emitter(op_ia32_Neg,           bemit_neg);
4132         register_emitter(op_ia32_NegMem,        bemit_negmem);
4133         register_emitter(op_ia32_Not,           bemit_not);
4134         register_emitter(op_ia32_NotMem,        bemit_notmem);
4135         register_emitter(op_ia32_Or,            bemit_or);
4136         register_emitter(op_ia32_OrMem,         bemit_ormem);
4137         register_emitter(op_ia32_OrMem8Bit,     bemit_ormem8bit);
4138         register_emitter(op_ia32_Pop,           bemit_pop);
4139         register_emitter(op_ia32_PopEbp,        bemit_pop);
4140         register_emitter(op_ia32_PopMem,        bemit_popmem);
4141         register_emitter(op_ia32_Push,          bemit_push);
4142         register_emitter(op_ia32_RepPrefix,     bemit_rep);
4143         register_emitter(op_ia32_Rol,           bemit_rol);
4144         register_emitter(op_ia32_RolMem,        bemit_rolmem);
4145         register_emitter(op_ia32_Ror,           bemit_ror);
4146         register_emitter(op_ia32_RorMem,        bemit_rormem);
4147         register_emitter(op_ia32_Sahf,          bemit_sahf);
4148         register_emitter(op_ia32_Sar,           bemit_sar);
4149         register_emitter(op_ia32_SarMem,        bemit_sarmem);
4150         register_emitter(op_ia32_Sbb,           bemit_sbb);
4151         register_emitter(op_ia32_Setcc,         bemit_setcc);
4152         register_emitter(op_ia32_Shl,           bemit_shl);
4153         register_emitter(op_ia32_ShlD,          bemit_shld);
4154         register_emitter(op_ia32_ShlMem,        bemit_shlmem);
4155         register_emitter(op_ia32_Shr,           bemit_shr);
4156         register_emitter(op_ia32_ShrD,          bemit_shrd);
4157         register_emitter(op_ia32_ShrMem,        bemit_shrmem);
4158         register_emitter(op_ia32_Stc,           bemit_stc);
4159         register_emitter(op_ia32_Store,         bemit_store);
4160         register_emitter(op_ia32_Store8Bit,     bemit_store);
4161         register_emitter(op_ia32_Sub,           bemit_sub);
4162         register_emitter(op_ia32_SubMem,        bemit_submem);
4163         register_emitter(op_ia32_SubMem8Bit,    bemit_submem8bit);
4164         register_emitter(op_ia32_SubSP,         bemit_subsp);
4165         register_emitter(op_ia32_SwitchJmp,     bemit_switchjmp);
4166         register_emitter(op_ia32_Test,          bemit_test);
4167         register_emitter(op_ia32_Test8Bit,      bemit_test8bit);
4168         register_emitter(op_ia32_Xor,           bemit_xor);
4169         register_emitter(op_ia32_Xor0,          bemit_xor0);
4170         register_emitter(op_ia32_XorMem,        bemit_xormem);
4171         register_emitter(op_ia32_XorMem8Bit,    bemit_xormem8bit);
4172         register_emitter(op_ia32_fabs,          bemit_fabs);
4173         register_emitter(op_ia32_fadd,          bemit_fadd);
4174         register_emitter(op_ia32_faddp,         bemit_faddp);
4175         register_emitter(op_ia32_fchs,          bemit_fchs);
4176         register_emitter(op_ia32_fdiv,          bemit_fdiv);
4177         register_emitter(op_ia32_fdivp,         bemit_fdivp);
4178         register_emitter(op_ia32_fdivr,         bemit_fdivr);
4179         register_emitter(op_ia32_fdivrp,        bemit_fdivrp);
4180         register_emitter(op_ia32_fild,          bemit_fild);
4181         register_emitter(op_ia32_fist,          bemit_fist);
4182         register_emitter(op_ia32_fistp,         bemit_fistp);
4183         register_emitter(op_ia32_fld,           bemit_fld);
4184         register_emitter(op_ia32_fld1,          bemit_fld1);
4185         register_emitter(op_ia32_fldz,          bemit_fldz);
4186         register_emitter(op_ia32_fmul,          bemit_fmul);
4187         register_emitter(op_ia32_fmulp,         bemit_fmulp);
4188         register_emitter(op_ia32_fpop,          bemit_fpop);
4189         register_emitter(op_ia32_fpush,         bemit_fpush);
4190         register_emitter(op_ia32_fpushCopy,     bemit_fpushcopy);
4191         register_emitter(op_ia32_fst,           bemit_fst);
4192         register_emitter(op_ia32_fstp,          bemit_fstp);
4193         register_emitter(op_ia32_fsub,          bemit_fsub);
4194         register_emitter(op_ia32_fsubp,         bemit_fsubp);
4195         register_emitter(op_ia32_fsubr,         bemit_fsubr);
4196         register_emitter(op_ia32_fsubrp,        bemit_fsubrp);
4197         register_emitter(op_ia32_fxch,          bemit_fxch);
4198
4199         /* ignore the following nodes */
4200         register_emitter(op_ia32_ProduceVal,   emit_Nothing);
4201         register_emitter(op_be_Barrier,        emit_Nothing);
4202         register_emitter(op_be_Keep,           emit_Nothing);
4203         register_emitter(op_be_Start,          emit_Nothing);
4204         register_emitter(op_Phi,               emit_Nothing);
4205         register_emitter(op_Start,             emit_Nothing);
4206 }
4207
4208 static void gen_binary_block(ir_node *block)
4209 {
4210         ir_node *node;
4211
4212         ia32_emit_block_header(block);
4213
4214         /* emit the contents of the block */
4215         sched_foreach(block, node) {
4216                 ia32_emit_node(node);
4217         }
4218 }
4219
4220 void ia32_gen_binary_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
4221 {
4222         ir_entity *entity     = get_irg_entity(irg);
4223         int i, n;
4224
4225         cg  = ia32_cg;
4226         isa = cg->isa;
4227
4228         ia32_register_binary_emitters();
4229
4230         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
4231
4232         /* we use links to point to target blocks */
4233         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
4234         irg_block_walk_graph(irg, ia32_gen_labels, NULL, NULL);
4235
4236         /* initialize next block links */
4237         n = ARR_LEN(cg->blk_sched);
4238         for (i = 0; i < n; ++i) {
4239                 ir_node *block = cg->blk_sched[i];
4240                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
4241
4242                 set_irn_link(block, prev);
4243         }
4244
4245         for (i = 0; i < n; ++i) {
4246                 ir_node *block = cg->blk_sched[i];
4247                 gen_binary_block(block);
4248         }
4249
4250         be_gas_emit_function_epilog(entity);
4251         be_dbg_method_end();
4252         be_emit_char('\n');
4253         be_emit_write_line();
4254
4255         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
4256 }
4257
4258
4259
4260
4261 void ia32_init_emitter(void)
4262 {
4263         lc_opt_entry_t *be_grp;
4264         lc_opt_entry_t *ia32_grp;
4265
4266         be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
4267         ia32_grp = lc_opt_get_grp(be_grp, "ia32");
4268
4269         lc_opt_add_table(ia32_grp, ia32_emitter_options);
4270
4271         build_reg_map();
4272
4273         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
4274 }