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