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