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