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