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