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