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