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