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