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