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