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