Remove an unused arch_env pointer.
[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 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include <limits.h>
31
32 #include "xmalloc.h"
33 #include "tv.h"
34 #include "iredges.h"
35 #include "debug.h"
36 #include "irgwalk.h"
37 #include "irprintf.h"
38 #include "irop_t.h"
39 #include "irargs_t.h"
40 #include "irprog_t.h"
41 #include "iredges_t.h"
42 #include "execfreq.h"
43 #include "error.h"
44 #include "raw_bitset.h"
45 #include "dbginfo.h"
46
47 #include "../besched_t.h"
48 #include "../benode_t.h"
49 #include "../beabi.h"
50 #include "../be_dbgout.h"
51 #include "../beemitter.h"
52 #include "../begnuas.h"
53 #include "../beirg_t.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 int               do_pic;
74 static char              pic_base_label[128];
75 static ir_label_t        exc_label_id;
76 static int               mark_spill_reload = 0;
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 static int is_fallthrough(const ir_node *cfgpred)
85 {
86         ir_node *pred;
87
88         if (!is_Proj(cfgpred))
89                 return 1;
90         pred = get_Proj_pred(cfgpred);
91         if (is_ia32_SwitchJmp(pred))
92                 return 0;
93
94         return 1;
95 }
96
97 static int block_needs_label(const ir_node *block)
98 {
99         int need_label = 1;
100         int  n_cfgpreds = get_Block_n_cfgpreds(block);
101
102         if (n_cfgpreds == 0) {
103                 need_label = 0;
104         } else if (n_cfgpreds == 1) {
105                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
106                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
107
108                 if (get_prev_block_sched(block) == cfgpred_block
109                                 && is_fallthrough(cfgpred)) {
110                         need_label = 0;
111                 }
112         }
113
114         return need_label;
115 }
116
117 /**
118  * Returns the register at in position pos.
119  */
120 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
121 {
122         ir_node               *op;
123         const arch_register_t *reg = NULL;
124
125         assert(get_irn_arity(irn) > pos && "Invalid IN position");
126
127         /* The out register of the operator at position pos is the
128            in register we need. */
129         op = get_irn_n(irn, pos);
130
131         reg = arch_get_irn_register(op);
132
133         assert(reg && "no in register found");
134
135         if (reg == &ia32_gp_regs[REG_GP_NOREG])
136                 panic("trying to emit noreg for %+F input %d", irn, pos);
137
138         /* in case of unknown register: just return a valid register */
139         if (reg == &ia32_gp_regs[REG_GP_UKNWN]) {
140                 const arch_register_req_t *req = arch_get_register_req(irn, pos);
141
142                 if (arch_register_req_is(req, limited)) {
143                         /* in case of limited requirements: get the first allowed register */
144                         unsigned idx = rbitset_next(req->limited, 0, 1);
145                         reg = arch_register_for_index(req->cls, idx);
146                 } else {
147                         /* otherwise get first register in class */
148                         reg = arch_register_for_index(req->cls, 0);
149                 }
150         }
151
152         return reg;
153 }
154
155 /**
156  * Returns the register at out position pos.
157  */
158 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
159 {
160         ir_node               *proj;
161         const arch_register_t *reg = NULL;
162
163         /* 1st case: irn is not of mode_T, so it has only                 */
164         /*           one OUT register -> good                             */
165         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
166         /*           Proj with the corresponding projnum for the register */
167
168         if (get_irn_mode(irn) != mode_T) {
169                 assert(pos == 0);
170                 reg = arch_get_irn_register(irn);
171         } else if (is_ia32_irn(irn)) {
172                 reg = get_ia32_out_reg(irn, pos);
173         } else {
174                 const ir_edge_t *edge;
175
176                 foreach_out_edge(irn, edge) {
177                         proj = get_edge_src_irn(edge);
178                         assert(is_Proj(proj) && "non-Proj from mode_T node");
179                         if (get_Proj_proj(proj) == pos) {
180                                 reg = arch_get_irn_register(proj);
181                                 break;
182                         }
183                 }
184         }
185
186         assert(reg && "no out register found");
187         return reg;
188 }
189
190 /**
191  * Add a number to a prefix. This number will not be used a second time.
192  */
193 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
194 {
195         static unsigned long id = 0;
196         snprintf(buf, buflen, "%s%lu", prefix, ++id);
197         return buf;
198 }
199
200 /*************************************************************
201  *             _       _    __   _          _
202  *            (_)     | |  / _| | |        | |
203  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
204  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
205  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
206  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
207  * | |                                       | |
208  * |_|                                       |_|
209  *************************************************************/
210
211 static void emit_8bit_register(const arch_register_t *reg)
212 {
213         const char *reg_name = arch_register_get_name(reg);
214
215         be_emit_char('%');
216         be_emit_char(reg_name[1]);
217         be_emit_char('l');
218 }
219
220 static void emit_16bit_register(const arch_register_t *reg)
221 {
222         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
223
224         be_emit_char('%');
225         be_emit_string(reg_name);
226 }
227
228 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
229 {
230         const char *reg_name;
231
232         if (mode != NULL) {
233                 int size = get_mode_size_bits(mode);
234                 switch (size) {
235                         case  8: emit_8bit_register(reg);  return;
236                         case 16: emit_16bit_register(reg); return;
237                 }
238                 assert(mode_is_float(mode) || size == 32);
239         }
240
241         reg_name = arch_register_get_name(reg);
242
243         be_emit_char('%');
244         be_emit_string(reg_name);
245 }
246
247 void ia32_emit_source_register(const ir_node *node, int pos)
248 {
249         const arch_register_t *reg = get_in_reg(node, pos);
250
251         emit_register(reg, NULL);
252 }
253
254 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
255 {
256         ident *id;
257
258         set_entity_backend_marked(entity, 1);
259         id = get_entity_ld_ident(entity);
260         be_emit_ident(id);
261
262         if (get_entity_owner(entity) == get_tls_type()) {
263                 if (get_entity_visibility(entity) == visibility_external_allocated) {
264                         be_emit_cstring("@INDNTPOFF");
265                 } else {
266                         be_emit_cstring("@NTPOFF");
267                 }
268         }
269
270         if (!no_pic_adjust && do_pic) {
271                 /* TODO: only do this when necessary */
272                 be_emit_char('-');
273                 be_emit_string(pic_base_label);
274         }
275 }
276
277 static void emit_ia32_Immediate_no_prefix(const ir_node *node)
278 {
279         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
280
281         if (attr->symconst != NULL) {
282                 if (attr->sc_sign)
283                         be_emit_char('-');
284                 ia32_emit_entity(attr->symconst, 0);
285         }
286         if (attr->symconst == NULL || attr->offset != 0) {
287                 if (attr->symconst != NULL) {
288                         be_emit_irprintf("%+d", attr->offset);
289                 } else {
290                         be_emit_irprintf("0x%X", attr->offset);
291                 }
292         }
293 }
294
295 static void emit_ia32_Immediate(const ir_node *node)
296 {
297         be_emit_char('$');
298         emit_ia32_Immediate_no_prefix(node);
299 }
300
301 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
302 {
303         const arch_register_t *reg;
304         ir_node               *in = get_irn_n(node, pos);
305         if (is_ia32_Immediate(in)) {
306                 emit_ia32_Immediate(in);
307                 return;
308         }
309
310         reg = get_in_reg(node, pos);
311         emit_8bit_register(reg);
312 }
313
314 void ia32_emit_dest_register(const ir_node *node, int pos)
315 {
316         const arch_register_t *reg  = get_out_reg(node, pos);
317
318         emit_register(reg, NULL);
319 }
320
321 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
322 {
323         const arch_register_t *reg  = get_out_reg(node, pos);
324
325         emit_register(reg, mode_Bu);
326 }
327
328 void ia32_emit_x87_register(const ir_node *node, int pos)
329 {
330         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
331
332         assert(pos < 3);
333         be_emit_char('%');
334         be_emit_string(attr->x87[pos]->name);
335 }
336
337 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
338 {
339         assert(mode_is_int(mode) || mode_is_reference(mode));
340         switch (get_mode_size_bits(mode)) {
341                 case 8:  be_emit_char('b');     return;
342                 case 16: be_emit_char('w');     return;
343                 case 32: be_emit_char('l');     return;
344                 /* gas docu says q is the suffix but gcc, objdump and icc use ll
345                  * apparently */
346                 case 64: be_emit_cstring("ll"); return;
347         }
348         panic("Can't output mode_suffix for %+F", mode);
349 }
350
351 void ia32_emit_mode_suffix(const ir_node *node)
352 {
353         ir_mode *mode = get_ia32_ls_mode(node);
354         if (mode == NULL)
355                 mode = mode_Iu;
356
357         ia32_emit_mode_suffix_mode(mode);
358 }
359
360 void ia32_emit_x87_mode_suffix(const ir_node *node)
361 {
362         ir_mode *mode;
363
364         /* we only need to emit the mode on address mode */
365         if (get_ia32_op_type(node) == ia32_Normal)
366                 return;
367
368         mode = get_ia32_ls_mode(node);
369         assert(mode != NULL);
370
371         if (mode_is_float(mode)) {
372                 switch (get_mode_size_bits(mode)) {
373                         case 32: be_emit_char('s'); return;
374                         case 64: be_emit_char('l'); return;
375                         case 80:
376                         case 96: be_emit_char('t'); return;
377                 }
378         } else {
379                 assert(mode_is_int(mode));
380                 switch (get_mode_size_bits(mode)) {
381                         case 16: be_emit_char('s');     return;
382                         case 32: be_emit_char('l');     return;
383                         /* gas docu says q is the suffix but gcc, objdump and icc use ll
384                          * apparently */
385                         case 64: be_emit_cstring("ll"); return;
386                 }
387         }
388         panic("Can't output mode_suffix for %+F", mode);
389 }
390
391 static char get_xmm_mode_suffix(ir_mode *mode)
392 {
393         assert(mode_is_float(mode));
394         switch(get_mode_size_bits(mode)) {
395         case 32: return 's';
396         case 64: return 'd';
397         default: panic("Invalid XMM mode");
398         }
399 }
400
401 void ia32_emit_xmm_mode_suffix(const ir_node *node)
402 {
403         ir_mode *mode = get_ia32_ls_mode(node);
404         assert(mode != NULL);
405         be_emit_char('s');
406         be_emit_char(get_xmm_mode_suffix(mode));
407 }
408
409 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
410 {
411         ir_mode *mode = get_ia32_ls_mode(node);
412         assert(mode != NULL);
413         be_emit_char(get_xmm_mode_suffix(mode));
414 }
415
416 void ia32_emit_extend_suffix(const ir_mode *mode)
417 {
418         if (get_mode_size_bits(mode) == 32)
419                 return;
420         be_emit_char(mode_is_signed(mode) ? 's' : 'z');
421 }
422
423 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
424 {
425         ir_node *in = get_irn_n(node, pos);
426         if (is_ia32_Immediate(in)) {
427                 emit_ia32_Immediate(in);
428         } else {
429                 const ir_mode         *mode = get_ia32_ls_mode(node);
430                 const arch_register_t *reg  = get_in_reg(node, pos);
431                 emit_register(reg, mode);
432         }
433 }
434
435 /**
436  * Returns the target block for a control flow node.
437  */
438 static ir_node *get_cfop_target_block(const ir_node *irn)
439 {
440         assert(get_irn_mode(irn) == mode_X);
441         return get_irn_link(irn);
442 }
443
444 /**
445  * Emits a block label for the given block.
446  */
447 static void ia32_emit_block_name(const ir_node *block)
448 {
449         if (has_Block_label(block)) {
450                 be_emit_string(be_gas_block_label_prefix());
451                 be_emit_irprintf("%lu", get_Block_label(block));
452         } else {
453                 be_emit_cstring(BLOCK_PREFIX);
454                 be_emit_irprintf("%ld", get_irn_node_nr(block));
455         }
456 }
457
458 /**
459  * Emits the target label for a control flow node.
460  */
461 static void ia32_emit_cfop_target(const ir_node *node)
462 {
463         ir_node *block = get_cfop_target_block(node);
464         ia32_emit_block_name(block);
465 }
466
467 /*
468  * coding of conditions
469  */
470 struct cmp2conditon_t {
471         const char *name;
472         int         num;
473 };
474
475 /*
476  * positive conditions for signed compares
477  */
478 static const struct cmp2conditon_t cmp2condition_s[] = {
479         { NULL,              pn_Cmp_False },  /* always false */
480         { "e",               pn_Cmp_Eq },     /* == */
481         { "l",               pn_Cmp_Lt },     /* < */
482         { "le",              pn_Cmp_Le },     /* <= */
483         { "g",               pn_Cmp_Gt },     /* > */
484         { "ge",              pn_Cmp_Ge },     /* >= */
485         { "ne",              pn_Cmp_Lg },     /* != */
486         { NULL,              pn_Cmp_Leg},     /* always true */
487 };
488
489 /*
490  * positive conditions for unsigned compares
491  */
492 static const struct cmp2conditon_t cmp2condition_u[] = {
493         { NULL,              pn_Cmp_False },  /* always false */
494         { "e",               pn_Cmp_Eq },     /* == */
495         { "b",               pn_Cmp_Lt },     /* < */
496         { "be",              pn_Cmp_Le },     /* <= */
497         { "a",               pn_Cmp_Gt },     /* > */
498         { "ae",              pn_Cmp_Ge },     /* >= */
499         { "ne",              pn_Cmp_Lg },     /* != */
500         { NULL,              pn_Cmp_Leg },   /* always true  */
501 };
502
503 static void ia32_emit_cmp_suffix(int pnc)
504 {
505         const char *str;
506
507         if ((pnc & ia32_pn_Cmp_float) || (pnc & ia32_pn_Cmp_unsigned)) {
508                 pnc = pnc & 7;
509                 assert(cmp2condition_u[pnc].num == pnc);
510                 str = cmp2condition_u[pnc].name;
511         } else {
512                 pnc = pnc & 7;
513                 assert(cmp2condition_s[pnc].num == pnc);
514                 str = cmp2condition_s[pnc].name;
515         }
516
517         be_emit_string(str);
518 }
519
520 typedef enum ia32_emit_mod_t {
521         EMIT_RESPECT_LS   = 1U << 0,
522         EMIT_ALTERNATE_AM = 1U << 1
523 } ia32_emit_mod_t;
524
525 /**
526  * fmt  parameter               output
527  * ---- ----------------------  ---------------------------------------------
528  * %%                           %
529  * %AM  <node>                  address mode of the node
530  * %AR  const arch_register_t*  address mode of the node or register
531  * %ASx <node>                  address mode of the node or source register x
532  * %Dx  <node>                  destination register x
533  * %I   <node>                  immediate of the node
534  * %L   <node>                  control flow target of the node
535  * %M   <node>                  mode suffix of the node
536  * %P   int                     condition code
537  * %R   const arch_register_t*  register
538  * %Sx  <node>                  source register x
539  * %s   const char*             string
540  * %u   unsigned int            unsigned int
541  *
542  * x starts at 0
543  * # modifier for %ASx, %D and %S uses ls mode of node to alter register width
544  * * modifier does not prefix immediates with $, but AM with *
545  */
546 static void ia32_emitf(const ir_node *node, const char *fmt, ...)
547 {
548         va_list ap;
549         va_start(ap, fmt);
550
551         for (;;) {
552                 const char      *start = fmt;
553                 ia32_emit_mod_t  mod   = 0;
554
555                 while (*fmt != '%' && *fmt != '\n' && *fmt != '\0')
556                         ++fmt;
557                 if (fmt != start) {
558                         be_emit_string_len(start, fmt - start);
559                 }
560
561                 if (*fmt == '\n') {
562                         be_emit_finish_line_gas(node);
563                         ++fmt;
564                         if (*fmt == '\0')
565                                 break;
566                         continue;
567                 }
568
569                 if (*fmt == '\0')
570                         break;
571
572                 ++fmt;
573                 if (*fmt == '*') {
574                         mod |= EMIT_ALTERNATE_AM;
575                         ++fmt;
576                 }
577
578                 if (*fmt == '#') {
579                         mod |= EMIT_RESPECT_LS;
580                         ++fmt;
581                 }
582
583                 switch (*fmt++) {
584                         case '%':
585                                 be_emit_char('%');
586                                 break;
587
588                         case 'A': {
589                                 switch (*fmt++) {
590                                         case 'M':
591                                                 if (mod & EMIT_ALTERNATE_AM)
592                                                         be_emit_char('*');
593                                                 ia32_emit_am(node);
594                                                 break;
595
596                                         case 'R': {
597                                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
598                                                 if (mod & EMIT_ALTERNATE_AM)
599                                                         be_emit_char('*');
600                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
601                                                         ia32_emit_am(node);
602                                                 } else {
603                                                         emit_register(reg, NULL);
604                                                 }
605                                                 break;
606                                         }
607
608                                         case 'S':
609                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
610                                                         if (mod & EMIT_ALTERNATE_AM)
611                                                                 be_emit_char('*');
612                                                         ia32_emit_am(node);
613                                                         ++fmt;
614                                                 } else {
615                                                         assert(get_ia32_op_type(node) == ia32_Normal);
616                                                         goto emit_S;
617                                                 }
618                                                 break;
619
620                                         default: goto unknown;
621                                 }
622                                 break;
623                         }
624
625                         case 'D': {
626                                 unsigned               pos;
627                                 const arch_register_t *reg;
628
629                                 if (*fmt < '0' || '9' <= *fmt)
630                                         goto unknown;
631
632                                 pos = *fmt++ - '0';
633                                 reg = get_out_reg(node, pos);
634                                 emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
635                                 break;
636                         }
637
638                         case 'I':
639                                 if (!(mod & EMIT_ALTERNATE_AM))
640                                         be_emit_char('$');
641                                 emit_ia32_Immediate_no_prefix(node);
642                                 break;
643
644                         case 'L':
645                                 ia32_emit_cfop_target(node);
646                                 break;
647
648                         case 'M': {
649                                 ia32_emit_mode_suffix_mode(get_ia32_ls_mode(node));
650                                 break;
651                         }
652
653                         case 'P': {
654                                 int pnc = va_arg(ap, int);
655                                 ia32_emit_cmp_suffix(pnc);
656                                 break;
657                         }
658
659                         case 'R': {
660                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
661                                 emit_register(reg, NULL);
662                                 break;
663                         }
664
665 emit_S:
666                         case 'S': {
667                                 unsigned       pos;
668                                 const ir_node *in;
669
670                                 if (*fmt < '0' || '9' <= *fmt)
671                                         goto unknown;
672
673                                 pos = *fmt++ - '0';
674                                 in  = get_irn_n(node, pos);
675                                 if (is_ia32_Immediate(in)) {
676                                         if (!(mod & EMIT_ALTERNATE_AM))
677                                                 be_emit_char('$');
678                                         emit_ia32_Immediate_no_prefix(in);
679                                 } else {
680                                         const arch_register_t *reg;
681
682                                         if (mod & EMIT_ALTERNATE_AM)
683                                                 be_emit_char('*');
684                                         reg = get_in_reg(node, pos);
685                                         emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
686                                 }
687                                 break;
688                         }
689
690                         case 's': {
691                                 const char *str = va_arg(ap, const char*);
692                                 be_emit_string(str);
693                                 break;
694                         }
695
696                         case 'u': {
697                                 unsigned num = va_arg(ap, unsigned);
698                                 be_emit_irprintf("%u", num);
699                                 break;
700                         }
701
702                         default:
703 unknown:
704                                 panic("unknown conversion");
705                 }
706         }
707
708         va_end(ap);
709 }
710
711 /**
712  * Emits registers and/or address mode of a binary operation.
713  */
714 void ia32_emit_binop(const ir_node *node)
715 {
716         if (is_ia32_Immediate(get_irn_n(node, n_ia32_binary_right))) {
717                 ia32_emitf(node, "%#S4, %#AS3");
718         } else {
719                 ia32_emitf(node, "%#AS4, %#S3");
720         }
721 }
722
723 /**
724  * Emits registers and/or address mode of a binary operation.
725  */
726 void ia32_emit_x87_binop(const ir_node *node)
727 {
728         switch(get_ia32_op_type(node)) {
729                 case ia32_Normal:
730                         {
731                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
732                                 const arch_register_t *in1      = x87_attr->x87[0];
733                                 const arch_register_t *in       = x87_attr->x87[1];
734                                 const arch_register_t *out      = x87_attr->x87[2];
735
736                                 if (out == NULL) {
737                                         out = in1;
738                                 } else if (out == in) {
739                                         in = in1;
740                                 }
741
742                                 be_emit_char('%');
743                                 be_emit_string(arch_register_get_name(in));
744                                 be_emit_cstring(", %");
745                                 be_emit_string(arch_register_get_name(out));
746                         }
747                         break;
748                 case ia32_AddrModeS:
749                         ia32_emit_am(node);
750                         break;
751                 case ia32_AddrModeD:
752                 default:
753                         assert(0 && "unsupported op type");
754         }
755 }
756
757 /**
758  * Emits registers and/or address mode of a unary operation.
759  */
760 void ia32_emit_unop(const ir_node *node, int pos)
761 {
762         char fmt[] = "%ASx";
763         fmt[3] = '0' + pos;
764         ia32_emitf(node, fmt);
765 }
766
767 /**
768  * Emits address mode.
769  */
770 void ia32_emit_am(const ir_node *node)
771 {
772         ir_entity *ent       = get_ia32_am_sc(node);
773         int        offs      = get_ia32_am_offs_int(node);
774         ir_node   *base      = get_irn_n(node, n_ia32_base);
775         int        has_base  = !is_ia32_NoReg_GP(base);
776         ir_node   *index     = get_irn_n(node, n_ia32_index);
777         int        has_index = !is_ia32_NoReg_GP(index);
778
779         /* just to be sure... */
780         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
781
782         /* emit offset */
783         if (ent != NULL) {
784                 if (is_ia32_am_sc_sign(node))
785                         be_emit_char('-');
786                 ia32_emit_entity(ent, 0);
787         }
788
789         /* also handle special case if nothing is set */
790         if (offs != 0 || (ent == NULL && !has_base && !has_index)) {
791                 if (ent != NULL) {
792                         be_emit_irprintf("%+d", offs);
793                 } else {
794                         be_emit_irprintf("%d", offs);
795                 }
796         }
797
798         if (has_base || has_index) {
799                 be_emit_char('(');
800
801                 /* emit base */
802                 if (has_base) {
803                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
804                         emit_register(reg, NULL);
805                 }
806
807                 /* emit index + scale */
808                 if (has_index) {
809                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
810                         int scale;
811                         be_emit_char(',');
812                         emit_register(reg, NULL);
813
814                         scale = get_ia32_am_scale(node);
815                         if (scale > 0) {
816                                 be_emit_irprintf(",%d", 1 << scale);
817                         }
818                 }
819                 be_emit_char(')');
820         }
821 }
822
823 static void emit_ia32_IMul(const ir_node *node)
824 {
825         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
826         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
827
828         /* do we need the 3-address form? */
829         if (is_ia32_NoReg_GP(left) ||
830                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
831                 ia32_emitf(node, "\timul%M %#S4, %#AS3, %#D0\n");
832         } else {
833                 ia32_emitf(node, "\timul%M %#AS4, %#S3\n");
834         }
835 }
836
837 /**
838  * walks up a tree of copies/perms/spills/reloads to find the original value
839  * that is moved around
840  */
841 static ir_node *find_original_value(ir_node *node)
842 {
843         if (irn_visited(node))
844                 return NULL;
845
846         mark_irn_visited(node);
847         if (be_is_Copy(node)) {
848                 return find_original_value(be_get_Copy_op(node));
849         } else if (be_is_CopyKeep(node)) {
850                 return find_original_value(be_get_CopyKeep_op(node));
851         } else if (is_Proj(node)) {
852                 ir_node *pred = get_Proj_pred(node);
853                 if (be_is_Perm(pred)) {
854                         return find_original_value(get_irn_n(pred, get_Proj_proj(node)));
855                 } else if (be_is_MemPerm(pred)) {
856                         return find_original_value(get_irn_n(pred, get_Proj_proj(node) + 1));
857                 } else if (is_ia32_Load(pred)) {
858                         return find_original_value(get_irn_n(pred, n_ia32_Load_mem));
859                 } else {
860                         return node;
861                 }
862         } else if (is_ia32_Store(node)) {
863                 return find_original_value(get_irn_n(node, n_ia32_Store_val));
864         } else if (is_Phi(node)) {
865                 int i, arity;
866                 arity = get_irn_arity(node);
867                 for (i = 0; i < arity; ++i) {
868                         ir_node *in  = get_irn_n(node, i);
869                         ir_node *res = find_original_value(in);
870
871                         if (res != NULL)
872                                 return res;
873                 }
874                 return NULL;
875         } else {
876                 return node;
877         }
878 }
879
880 static int determine_final_pnc(const ir_node *node, int flags_pos,
881                                int pnc)
882 {
883         ir_node           *flags = get_irn_n(node, flags_pos);
884         const ia32_attr_t *flags_attr;
885         flags = skip_Proj(flags);
886
887         if (is_ia32_Sahf(flags)) {
888                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
889                 if (!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
890                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
891                         inc_irg_visited(current_ir_graph);
892                         cmp = find_original_value(cmp);
893                         assert(cmp != NULL);
894                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
895                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
896                 }
897
898                 flags_attr = get_ia32_attr_const(cmp);
899                 if (flags_attr->data.ins_permuted)
900                         pnc = get_mirrored_pnc(pnc);
901                 pnc |= ia32_pn_Cmp_float;
902         } else if (is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
903                         || is_ia32_Fucompi(flags)) {
904                 flags_attr = get_ia32_attr_const(flags);
905
906                 if (flags_attr->data.ins_permuted)
907                         pnc = get_mirrored_pnc(pnc);
908                 pnc |= ia32_pn_Cmp_float;
909         } else {
910                 flags_attr = get_ia32_attr_const(flags);
911
912                 if (flags_attr->data.ins_permuted)
913                         pnc = get_mirrored_pnc(pnc);
914                 if (flags_attr->data.cmp_unsigned)
915                         pnc |= ia32_pn_Cmp_unsigned;
916         }
917
918         return pnc;
919 }
920
921 void ia32_emit_cmp_suffix_node(const ir_node *node,
922                                int flags_pos)
923 {
924         const ia32_attr_t *attr = get_ia32_attr_const(node);
925
926         pn_Cmp pnc = get_ia32_condcode(node);
927
928         pnc = determine_final_pnc(node, flags_pos, pnc);
929         if (attr->data.ins_permuted) {
930                 if (pnc & ia32_pn_Cmp_float) {
931                         pnc = get_negated_pnc(pnc, mode_F);
932                 } else {
933                         pnc = get_negated_pnc(pnc, mode_Iu);
934                 }
935         }
936
937         ia32_emit_cmp_suffix(pnc);
938 }
939
940 /**
941  * Emits an exception label for a given node.
942  */
943 static void ia32_emit_exc_label(const ir_node *node)
944 {
945         be_emit_string(be_gas_insn_label_prefix());
946         be_emit_irprintf("%lu", get_ia32_exc_label_id(node));
947 }
948
949 /**
950  * Returns the Proj with projection number proj and NOT mode_M
951  */
952 static ir_node *get_proj(const ir_node *node, long proj)
953 {
954         const ir_edge_t *edge;
955         ir_node         *src;
956
957         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
958
959         foreach_out_edge(node, edge) {
960                 src = get_edge_src_irn(edge);
961
962                 assert(is_Proj(src) && "Proj expected");
963                 if (get_irn_mode(src) == mode_M)
964                         continue;
965
966                 if (get_Proj_proj(src) == proj)
967                         return src;
968         }
969         return NULL;
970 }
971
972 static int can_be_fallthrough(const ir_node *node)
973 {
974         ir_node *target_block = get_cfop_target_block(node);
975         ir_node *block        = get_nodes_block(node);
976         return get_prev_block_sched(target_block) == block;
977 }
978
979 /**
980  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
981  */
982 static void emit_ia32_Jcc(const ir_node *node)
983 {
984         int            need_parity_label = 0;
985         const ir_node *proj_true;
986         const ir_node *proj_false;
987         const ir_node *block;
988         pn_Cmp         pnc = get_ia32_condcode(node);
989
990         pnc = determine_final_pnc(node, 0, pnc);
991
992         /* get both Projs */
993         proj_true = get_proj(node, pn_ia32_Jcc_true);
994         assert(proj_true && "Jcc without true Proj");
995
996         proj_false = get_proj(node, pn_ia32_Jcc_false);
997         assert(proj_false && "Jcc without false Proj");
998
999         block      = get_nodes_block(node);
1000
1001         if (can_be_fallthrough(proj_true)) {
1002                 /* exchange both proj's so the second one can be omitted */
1003                 const ir_node *t = proj_true;
1004
1005                 proj_true  = proj_false;
1006                 proj_false = t;
1007                 if (pnc & ia32_pn_Cmp_float) {
1008                         pnc = get_negated_pnc(pnc, mode_F);
1009                 } else {
1010                         pnc = get_negated_pnc(pnc, mode_Iu);
1011                 }
1012         }
1013
1014         if (pnc & ia32_pn_Cmp_float) {
1015                 /* Some floating point comparisons require a test of the parity flag,
1016                  * which indicates that the result is unordered */
1017                 switch (pnc & 15) {
1018                         case pn_Cmp_Uo: {
1019                                 ia32_emitf(proj_true, "\tjp %L\n");
1020                                 break;
1021                         }
1022
1023                         case pn_Cmp_Leg:
1024                                 ia32_emitf(proj_true, "\tjnp %L\n");
1025                                 break;
1026
1027                         case pn_Cmp_Eq:
1028                         case pn_Cmp_Lt:
1029                         case pn_Cmp_Le:
1030                                 /* we need a local label if the false proj is a fallthrough
1031                                  * as the falseblock might have no label emitted then */
1032                                 if (can_be_fallthrough(proj_false)) {
1033                                         need_parity_label = 1;
1034                                         ia32_emitf(proj_false, "\tjp 1f\n");
1035                                 } else {
1036                                         ia32_emitf(proj_false, "\tjp %L\n");
1037                                 }
1038                                 goto emit_jcc;
1039
1040                         case pn_Cmp_Ug:
1041                         case pn_Cmp_Uge:
1042                         case pn_Cmp_Ne:
1043                                 ia32_emitf(proj_true, "\tjp %L\n");
1044                                 goto emit_jcc;
1045
1046                         default:
1047                                 goto emit_jcc;
1048                 }
1049         } else {
1050 emit_jcc:
1051                 ia32_emitf(proj_true, "\tj%P %L\n", pnc);
1052         }
1053
1054         if (need_parity_label) {
1055                 ia32_emitf(NULL, "1:\n");
1056         }
1057
1058         /* the second Proj might be a fallthrough */
1059         if (can_be_fallthrough(proj_false)) {
1060                 ia32_emitf(proj_false, "\t/* fallthrough to %L */\n");
1061         } else {
1062                 ia32_emitf(proj_false, "\tjmp %L\n");
1063         }
1064 }
1065
1066 static void emit_ia32_CMov(const ir_node *node)
1067 {
1068         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
1069         int                    ins_permuted = attr->data.ins_permuted;
1070         const arch_register_t *out          = arch_get_irn_register(node);
1071         pn_Cmp                 pnc          = get_ia32_condcode(node);
1072         const arch_register_t *in_true;
1073         const arch_register_t *in_false;
1074
1075         pnc = determine_final_pnc(node, n_ia32_CMov_eflags, pnc);
1076
1077         in_true  = arch_get_irn_register(get_irn_n(node, n_ia32_CMov_val_true));
1078         in_false = arch_get_irn_register(get_irn_n(node, n_ia32_CMov_val_false));
1079
1080         /* should be same constraint fullfilled? */
1081         if (out == in_false) {
1082                 /* yes -> nothing to do */
1083         } else if (out == in_true) {
1084                 const arch_register_t *tmp;
1085
1086                 assert(get_ia32_op_type(node) == ia32_Normal);
1087
1088                 ins_permuted = !ins_permuted;
1089
1090                 tmp      = in_true;
1091                 in_true  = in_false;
1092                 in_false = tmp;
1093         } else {
1094                 /* we need a mov */
1095                 ia32_emitf(node, "\tmovl %R, %R\n", in_false, out);
1096         }
1097
1098         if (ins_permuted) {
1099                 if (pnc & ia32_pn_Cmp_float) {
1100                         pnc = get_negated_pnc(pnc, mode_F);
1101                 } else {
1102                         pnc = get_negated_pnc(pnc, mode_Iu);
1103                 }
1104         }
1105
1106         /* TODO: handling of Nans isn't correct yet */
1107
1108         ia32_emitf(node, "\tcmov%P %AR, %#R\n", pnc, in_true, out);
1109 }
1110
1111 /*********************************************************
1112  *                 _ _       _
1113  *                (_) |     (_)
1114  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
1115  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
1116  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
1117  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
1118  *                         _/ |               | |
1119  *                        |__/                |_|
1120  *********************************************************/
1121
1122 /* jump table entry (target and corresponding number) */
1123 typedef struct _branch_t {
1124         ir_node *target;
1125         int      value;
1126 } branch_t;
1127
1128 /* jump table for switch generation */
1129 typedef struct _jmp_tbl_t {
1130         ir_node  *defProj;         /**< default target */
1131         long      min_value;       /**< smallest switch case */
1132         long      max_value;       /**< largest switch case */
1133         long      num_branches;    /**< number of jumps */
1134         char     *label;           /**< label of the jump table */
1135         branch_t *branches;        /**< jump array */
1136 } jmp_tbl_t;
1137
1138 /**
1139  * Compare two variables of type branch_t. Used to sort all switch cases
1140  */
1141 static int ia32_cmp_branch_t(const void *a, const void *b)
1142 {
1143         branch_t *b1 = (branch_t *)a;
1144         branch_t *b2 = (branch_t *)b;
1145
1146         if (b1->value <= b2->value)
1147                 return -1;
1148         else
1149                 return 1;
1150 }
1151
1152 /**
1153  * Emits code for a SwitchJmp (creates a jump table if
1154  * possible otherwise a cmp-jmp cascade). Port from
1155  * cggg ia32 backend
1156  */
1157 static void emit_ia32_SwitchJmp(const ir_node *node)
1158 {
1159         unsigned long       interval;
1160         int                 last_value, i;
1161         long                pnc;
1162         long                default_pn;
1163         jmp_tbl_t           tbl;
1164         ir_node            *proj;
1165         const ir_edge_t    *edge;
1166
1167         /* fill the table structure */
1168         tbl.label        = XMALLOCN(char, SNPRINTF_BUF_LEN);
1169         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, ".TBL_");
1170         tbl.defProj      = NULL;
1171         tbl.num_branches = get_irn_n_edges(node) - 1;
1172         tbl.branches     = XMALLOCNZ(branch_t, tbl.num_branches);
1173         tbl.min_value    = INT_MAX;
1174         tbl.max_value    = INT_MIN;
1175
1176         default_pn = get_ia32_condcode(node);
1177         i = 0;
1178         /* go over all proj's and collect them */
1179         foreach_out_edge(node, edge) {
1180                 proj = get_edge_src_irn(edge);
1181                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1182
1183                 pnc = get_Proj_proj(proj);
1184
1185                 /* check for default proj */
1186                 if (pnc == default_pn) {
1187                         assert(tbl.defProj == NULL && "found two default Projs at SwitchJmp");
1188                         tbl.defProj = proj;
1189                 } else {
1190                         tbl.min_value = pnc < tbl.min_value ? pnc : tbl.min_value;
1191                         tbl.max_value = pnc > tbl.max_value ? pnc : tbl.max_value;
1192
1193                         /* create branch entry */
1194                         tbl.branches[i].target = proj;
1195                         tbl.branches[i].value  = pnc;
1196                         ++i;
1197                 }
1198
1199         }
1200         assert(i == tbl.num_branches);
1201
1202         /* sort the branches by their number */
1203         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1204
1205         /* two-complement's magic make this work without overflow */
1206         interval = tbl.max_value - tbl.min_value;
1207
1208         /* emit the table */
1209         ia32_emitf(node,        "\tcmpl $%u, %S0\n", interval);
1210         ia32_emitf(tbl.defProj, "\tja %L\n");
1211
1212         if (tbl.num_branches > 1) {
1213                 /* create table */
1214                 ia32_emitf(node, "\tjmp *%s(,%S0,4)\n", tbl.label);
1215
1216                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1217                 ia32_emitf(NULL, "\t.align 4\n");
1218                 ia32_emitf(NULL, "%s:\n", tbl.label);
1219
1220                 last_value = tbl.branches[0].value;
1221                 for (i = 0; i != tbl.num_branches; ++i) {
1222                         while (last_value != tbl.branches[i].value) {
1223                                 ia32_emitf(tbl.defProj, ".long %L\n");
1224                                 ++last_value;
1225                         }
1226                         ia32_emitf(tbl.branches[i].target, ".long %L\n");
1227                         ++last_value;
1228                 }
1229                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1230         } else {
1231                 /* one jump is enough */
1232                 ia32_emitf(tbl.branches[0].target, "\tjmp %L\n");
1233         }
1234
1235         if (tbl.label)
1236                 free(tbl.label);
1237         if (tbl.branches)
1238                 free(tbl.branches);
1239 }
1240
1241 /**
1242  * Emits code for a unconditional jump.
1243  */
1244 static void emit_Jmp(const ir_node *node)
1245 {
1246         ir_node *block;
1247
1248         /* for now, the code works for scheduled and non-schedules blocks */
1249         block = get_nodes_block(node);
1250
1251         /* we have a block schedule */
1252         if (can_be_fallthrough(node)) {
1253                 ia32_emitf(node, "\t/* fallthrough to %L */\n");
1254         } else {
1255                 ia32_emitf(node, "\tjmp %L\n");
1256         }
1257 }
1258
1259 /**
1260  * Emit an inline assembler operand.
1261  *
1262  * @param node  the ia32_ASM node
1263  * @param s     points to the operand (a %c)
1264  *
1265  * @return  pointer to the first char in s NOT in the current operand
1266  */
1267 static const char* emit_asm_operand(const ir_node *node, const char *s)
1268 {
1269         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1270         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1271                                                             ia32_attr);
1272         const arch_register_t *reg;
1273         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1274         const ia32_asm_reg_t  *asm_reg;
1275         const char            *reg_name;
1276         char                   c;
1277         char                   modifier = 0;
1278         int                    num      = -1;
1279         int                    p;
1280
1281         assert(*s == '%');
1282         c = *(++s);
1283
1284         /* parse modifiers */
1285         switch(c) {
1286         case 0:
1287                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %\n", node);
1288                 be_emit_char('%');
1289                 return s + 1;
1290         case '%':
1291                 be_emit_char('%');
1292                 return s + 1;
1293         case 'w':
1294         case 'b':
1295         case 'h':
1296                 modifier = c;
1297                 ++s;
1298                 break;
1299         case '0':
1300         case '1':
1301         case '2':
1302         case '3':
1303         case '4':
1304         case '5':
1305         case '6':
1306         case '7':
1307         case '8':
1308         case '9':
1309                 break;
1310         default:
1311                 ir_fprintf(stderr, "Warning: asm text (%+F) contains unknown modifier "
1312                            "'%c' for asm op\n", node, c);
1313                 ++s;
1314                 break;
1315         }
1316
1317         /* parse number */
1318         sscanf(s, "%d%n", &num, &p);
1319         if (num < 0) {
1320                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1321                            node);
1322                 return s;
1323         } else {
1324                 s += p;
1325         }
1326
1327         if (num < 0 || num >= ARR_LEN(asm_regs)) {
1328                 ir_fprintf(stderr, "Error: Custom assembler references invalid "
1329                            "input/output (%+F)\n", node);
1330                 return s;
1331         }
1332         asm_reg = & asm_regs[num];
1333         assert(asm_reg->valid);
1334
1335         /* get register */
1336         if (asm_reg->use_input == 0) {
1337                 reg = get_out_reg(node, asm_reg->inout_pos);
1338         } else {
1339                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1340
1341                 /* might be an immediate value */
1342                 if (is_ia32_Immediate(pred)) {
1343                         emit_ia32_Immediate(pred);
1344                         return s;
1345                 }
1346                 reg = get_in_reg(node, asm_reg->inout_pos);
1347         }
1348         if (reg == NULL) {
1349                 ir_fprintf(stderr, "Warning: no register assigned for %d asm op "
1350                            "(%+F)\n", num, node);
1351                 return s;
1352         }
1353
1354         if (asm_reg->memory) {
1355                 be_emit_char('(');
1356         }
1357
1358         /* emit it */
1359         if (modifier != 0) {
1360                 be_emit_char('%');
1361                 switch(modifier) {
1362                 case 'b':
1363                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1364                         break;
1365                 case 'h':
1366                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1367                         break;
1368                 case 'w':
1369                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1370                         break;
1371                 default:
1372                         panic("Invalid asm op modifier");
1373                 }
1374                 be_emit_string(reg_name);
1375         } else {
1376                 emit_register(reg, asm_reg->mode);
1377         }
1378
1379         if (asm_reg->memory) {
1380                 be_emit_char(')');
1381         }
1382
1383         return s;
1384 }
1385
1386 /**
1387  * Emits code for an ASM pseudo op.
1388  */
1389 static void emit_ia32_Asm(const ir_node *node)
1390 {
1391         const void            *gen_attr = get_irn_generic_attr_const(node);
1392         const ia32_asm_attr_t *attr
1393                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1394         ident                 *asm_text = attr->asm_text;
1395         const char            *s        = get_id_str(asm_text);
1396
1397         ia32_emitf(node, "#APP\t\n");
1398
1399         if (s[0] != '\t')
1400                 be_emit_char('\t');
1401
1402         while(*s != 0) {
1403                 if (*s == '%') {
1404                         s = emit_asm_operand(node, s);
1405                 } else {
1406                         be_emit_char(*s++);
1407                 }
1408         }
1409
1410         ia32_emitf(NULL, "\n#NO_APP\n");
1411 }
1412
1413 /**********************************
1414  *   _____                  ____
1415  *  / ____|                |  _ \
1416  * | |     ___  _ __  _   _| |_) |
1417  * | |    / _ \| '_ \| | | |  _ <
1418  * | |___| (_) | |_) | |_| | |_) |
1419  *  \_____\___/| .__/ \__, |____/
1420  *             | |     __/ |
1421  *             |_|    |___/
1422  **********************************/
1423
1424 /**
1425  * Emit movsb/w instructions to make mov count divideable by 4
1426  */
1427 static void emit_CopyB_prolog(unsigned size)
1428 {
1429         if (size & 1)
1430                 ia32_emitf(NULL, "\tmovsb\n");
1431         if (size & 2)
1432                 ia32_emitf(NULL, "\tmovsw\n");
1433 }
1434
1435 /**
1436  * Emit rep movsd instruction for memcopy.
1437  */
1438 static void emit_ia32_CopyB(const ir_node *node)
1439 {
1440         unsigned size = get_ia32_copyb_size(node);
1441
1442         emit_CopyB_prolog(size);
1443         ia32_emitf(node, "\trep movsd\n");
1444 }
1445
1446 /**
1447  * Emits unrolled memcopy.
1448  */
1449 static void emit_ia32_CopyB_i(const ir_node *node)
1450 {
1451         unsigned size = get_ia32_copyb_size(node);
1452
1453         emit_CopyB_prolog(size);
1454
1455         size >>= 2;
1456         while (size--) {
1457                 ia32_emitf(NULL, "\tmovsd\n");
1458         }
1459 }
1460
1461
1462
1463 /***************************
1464  *   _____
1465  *  / ____|
1466  * | |     ___  _ ____   __
1467  * | |    / _ \| '_ \ \ / /
1468  * | |___| (_) | | | \ V /
1469  *  \_____\___/|_| |_|\_/
1470  *
1471  ***************************/
1472
1473 /**
1474  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1475  */
1476 static void emit_ia32_Conv_with_FP(const ir_node *node)
1477 {
1478         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1479         int                 ls_bits = get_mode_size_bits(ls_mode);
1480         const char         *conv;
1481
1482         if (is_ia32_Conv_I2FP(node)) {
1483                 if (ls_bits == 32) {
1484                         conv = "si2ss";
1485                 } else {
1486                         conv = "si2sd";
1487                 }
1488         } else if (is_ia32_Conv_FP2I(node)) {
1489                 if (ls_bits == 32) {
1490                         conv = "ss2si";
1491                 } else {
1492                         conv = "sd2si";
1493                 }
1494         } else {
1495                 assert(is_ia32_Conv_FP2FP(node));
1496                 if (ls_bits == 32) {
1497                         conv = "sd2ss";
1498                 } else {
1499                         conv = "ss2sd";
1500                 }
1501         }
1502
1503         ia32_emitf(node, "\tcvt%s %AS3, %D0\n", conv);
1504 }
1505
1506 static void emit_ia32_Conv_I2FP(const ir_node *node)
1507 {
1508         emit_ia32_Conv_with_FP(node);
1509 }
1510
1511 static void emit_ia32_Conv_FP2I(const ir_node *node)
1512 {
1513         emit_ia32_Conv_with_FP(node);
1514 }
1515
1516 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1517 {
1518         emit_ia32_Conv_with_FP(node);
1519 }
1520
1521 /**
1522  * Emits code for an Int conversion.
1523  */
1524 static void emit_ia32_Conv_I2I(const ir_node *node)
1525 {
1526         ir_mode *smaller_mode = get_ia32_ls_mode(node);
1527         int      smaller_bits = get_mode_size_bits(smaller_mode);
1528         int      signed_mode  = mode_is_signed(smaller_mode);
1529
1530         assert(!mode_is_float(smaller_mode));
1531         assert(smaller_bits == 8 || smaller_bits == 16);
1532
1533         if (signed_mode                                    &&
1534                         smaller_bits == 16                             &&
1535                         &ia32_gp_regs[REG_EAX] == get_out_reg(node, 0) &&
1536                         &ia32_gp_regs[REG_EAX] == arch_get_irn_register(get_irn_n(node, n_ia32_unary_op))) {
1537                 /* argument and result are both in EAX and signedness is ok: use the
1538                  * smaller cwtl opcode */
1539                 ia32_emitf(node, "\tcwtl\n");
1540         } else {
1541                 const char *sign_suffix = signed_mode ? "s" : "z";
1542                 ia32_emitf(node, "\tmov%s%Ml %#AS3, %D0\n", sign_suffix);
1543         }
1544 }
1545
1546 /**
1547  * Emits a call
1548  */
1549 static void emit_ia32_Call(const ir_node *node)
1550 {
1551         /* Special case: Call must not have its immediates prefixed by $, instead
1552          * address mode is prefixed by *. */
1553         ia32_emitf(node, "\tcall %*AS3\n");
1554 }
1555
1556
1557 /*******************************************
1558  *  _                          _
1559  * | |                        | |
1560  * | |__   ___ _ __   ___   __| | ___  ___
1561  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1562  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1563  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1564  *
1565  *******************************************/
1566
1567 /**
1568  * Emits code to increase stack pointer.
1569  */
1570 static void emit_be_IncSP(const ir_node *node)
1571 {
1572         int offs = be_get_IncSP_offset(node);
1573
1574         if (offs == 0)
1575                 return;
1576
1577         if (offs > 0) {
1578                 ia32_emitf(node, "\tsubl $%u, %D0\n", offs);
1579         } else {
1580                 ia32_emitf(node, "\taddl $%u, %D0\n", -offs);
1581         }
1582 }
1583
1584 /**
1585  * Emits code for Copy/CopyKeep.
1586  */
1587 static void Copy_emitter(const ir_node *node, const ir_node *op)
1588 {
1589         const arch_register_t *in  = arch_get_irn_register(op);
1590         const arch_register_t *out = arch_get_irn_register(node);
1591
1592         if (in == out) {
1593                 return;
1594         }
1595         if (is_unknown_reg(in))
1596                 return;
1597         /* copies of vf nodes aren't real... */
1598         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1599                 return;
1600
1601         if (get_irn_mode(node) == mode_E) {
1602                 ia32_emitf(node, "\tmovsd %R, %R\n", in, out);
1603         } else {
1604                 ia32_emitf(node, "\tmovl %R, %R\n", in, out);
1605         }
1606 }
1607
1608 static void emit_be_Copy(const ir_node *node)
1609 {
1610         Copy_emitter(node, be_get_Copy_op(node));
1611 }
1612
1613 static void emit_be_CopyKeep(const ir_node *node)
1614 {
1615         Copy_emitter(node, be_get_CopyKeep_op(node));
1616 }
1617
1618 /**
1619  * Emits code for exchange.
1620  */
1621 static void emit_be_Perm(const ir_node *node)
1622 {
1623         const arch_register_t *in0, *in1;
1624         const arch_register_class_t *cls0, *cls1;
1625
1626         in0 = arch_get_irn_register(get_irn_n(node, 0));
1627         in1 = arch_get_irn_register(get_irn_n(node, 1));
1628
1629         cls0 = arch_register_get_class(in0);
1630         cls1 = arch_register_get_class(in1);
1631
1632         assert(cls0 == cls1 && "Register class mismatch at Perm");
1633
1634         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1635                 ia32_emitf(node, "\txchg %R, %R\n", in1, in0);
1636         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1637                 ia32_emitf(NULL, "\txorpd %R, %R\n", in1, in0);
1638                 ia32_emitf(NULL, "\txorpd %R, %R\n", in0, in1);
1639                 ia32_emitf(node, "\txorpd %R, %R\n", in1, in0);
1640         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1641                 /* is a NOP */
1642         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1643                 /* is a NOP */
1644         } else {
1645                 panic("unexpected register class in be_Perm (%+F)", node);
1646         }
1647 }
1648
1649 /**
1650  * Emits code for Constant loading.
1651  */
1652 static void emit_ia32_Const(const ir_node *node)
1653 {
1654         ia32_emitf(node, "\tmovl %I, %D0\n");
1655 }
1656
1657 /**
1658  * Emits code to load the TLS base
1659  */
1660 static void emit_ia32_LdTls(const ir_node *node)
1661 {
1662         ia32_emitf(node, "\tmovl %%gs:0, %D0\n");
1663 }
1664
1665 /* helper function for emit_ia32_Minus64Bit */
1666 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1667 {
1668         ia32_emitf(node, "\tmovl %R, %R\n", src, dst);
1669 }
1670
1671 /* helper function for emit_ia32_Minus64Bit */
1672 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1673 {
1674         ia32_emitf(node, "\tnegl %R\n", reg);
1675 }
1676
1677 /* helper function for emit_ia32_Minus64Bit */
1678 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1679 {
1680         ia32_emitf(node, "\tsbbl $0, %R\n", reg);
1681 }
1682
1683 /* helper function for emit_ia32_Minus64Bit */
1684 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1685 {
1686         ia32_emitf(node, "\tsbbl %R, %R\n", src, dst);
1687 }
1688
1689 /* helper function for emit_ia32_Minus64Bit */
1690 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1691 {
1692         ia32_emitf(node, "\txchgl %R, %R\n", src, dst);
1693 }
1694
1695 /* helper function for emit_ia32_Minus64Bit */
1696 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1697 {
1698         ia32_emitf(node, "\txorl %R, %R\n", reg, reg);
1699 }
1700
1701 static void emit_ia32_Minus64Bit(const ir_node *node)
1702 {
1703         const arch_register_t *in_lo  = get_in_reg(node, 0);
1704         const arch_register_t *in_hi  = get_in_reg(node, 1);
1705         const arch_register_t *out_lo = get_out_reg(node, 0);
1706         const arch_register_t *out_hi = get_out_reg(node, 1);
1707
1708         if (out_lo == in_lo) {
1709                 if (out_hi != in_hi) {
1710                         /* a -> a, b -> d */
1711                         goto zero_neg;
1712                 } else {
1713                         /* a -> a, b -> b */
1714                         goto normal_neg;
1715                 }
1716         } else if (out_lo == in_hi) {
1717                 if (out_hi == in_lo) {
1718                         /* a -> b, b -> a */
1719                         emit_xchg(node, in_lo, in_hi);
1720                         goto normal_neg;
1721                 } else {
1722                         /* a -> b, b -> d */
1723                         emit_mov(node, in_hi, out_hi);
1724                         emit_mov(node, in_lo, out_lo);
1725                         goto normal_neg;
1726                 }
1727         } else {
1728                 if (out_hi == in_lo) {
1729                         /* a -> c, b -> a */
1730                         emit_mov(node, in_lo, out_lo);
1731                         goto zero_neg;
1732                 } else if (out_hi == in_hi) {
1733                         /* a -> c, b -> b */
1734                         emit_mov(node, in_lo, out_lo);
1735                         goto normal_neg;
1736                 } else {
1737                         /* a -> c, b -> d */
1738                         emit_mov(node, in_lo, out_lo);
1739                         goto zero_neg;
1740                 }
1741         }
1742
1743 normal_neg:
1744         emit_neg( node, out_hi);
1745         emit_neg( node, out_lo);
1746         emit_sbb0(node, out_hi);
1747         return;
1748
1749 zero_neg:
1750         emit_zero(node, out_hi);
1751         emit_neg( node, out_lo);
1752         emit_sbb( node, in_hi, out_hi);
1753 }
1754
1755 static void emit_ia32_GetEIP(const ir_node *node)
1756 {
1757         ia32_emitf(node, "\tcall %s\n", pic_base_label);
1758         ia32_emitf(NULL, "%s:\n", pic_base_label);
1759         ia32_emitf(node, "\tpopl %D0\n");
1760 }
1761
1762 static void emit_be_Return(const ir_node *node)
1763 {
1764         unsigned pop = be_Return_get_pop(node);
1765
1766         if (pop > 0 || be_Return_get_emit_pop(node)) {
1767                 ia32_emitf(node, "\tret $%u\n", pop);
1768         } else {
1769                 ia32_emitf(node, "\tret\n");
1770         }
1771 }
1772
1773 static void emit_Nothing(const ir_node *node)
1774 {
1775         (void) node;
1776 }
1777
1778
1779 /***********************************************************************************
1780  *                  _          __                                             _
1781  *                 (_)        / _|                                           | |
1782  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1783  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1784  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1785  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1786  *
1787  ***********************************************************************************/
1788
1789 /**
1790  * Enters the emitter functions for handled nodes into the generic
1791  * pointer of an opcode.
1792  */
1793 static void ia32_register_emitters(void)
1794 {
1795 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1796 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1797 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1798 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1799 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1800 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1801
1802         /* first clear the generic function pointer for all ops */
1803         clear_irp_opcodes_generic_func();
1804
1805         /* register all emitter functions defined in spec */
1806         ia32_register_spec_emitters();
1807
1808         /* other ia32 emitter functions */
1809         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1810         IA32_EMIT(Asm);
1811         IA32_EMIT(CMov);
1812         IA32_EMIT(Call);
1813         IA32_EMIT(Const);
1814         IA32_EMIT(Conv_FP2FP);
1815         IA32_EMIT(Conv_FP2I);
1816         IA32_EMIT(Conv_I2FP);
1817         IA32_EMIT(Conv_I2I);
1818         IA32_EMIT(CopyB);
1819         IA32_EMIT(CopyB_i);
1820         IA32_EMIT(GetEIP);
1821         IA32_EMIT(IMul);
1822         IA32_EMIT(Jcc);
1823         IA32_EMIT(LdTls);
1824         IA32_EMIT(Minus64Bit);
1825         IA32_EMIT(SwitchJmp);
1826
1827         /* benode emitter */
1828         BE_EMIT(Copy);
1829         BE_EMIT(CopyKeep);
1830         BE_EMIT(IncSP);
1831         BE_EMIT(Perm);
1832         BE_EMIT(Return);
1833
1834         BE_IGN(Barrier);
1835         BE_IGN(Keep);
1836         BE_IGN(RegParams);
1837
1838         /* firm emitter */
1839         EMIT(Jmp);
1840         IGN(Phi);
1841         IGN(Start);
1842
1843 #undef BE_EMIT
1844 #undef EMIT
1845 #undef IGN
1846 #undef IA32_EMIT2
1847 #undef IA32_EMIT
1848 }
1849
1850 typedef void (*emit_func_ptr) (const ir_node *);
1851
1852 /**
1853  * Assign and emit an exception label if the current instruction can fail.
1854  */
1855 static void ia32_assign_exc_label(ir_node *node)
1856 {
1857         /* assign a new ID to the instruction */
1858         set_ia32_exc_label_id(node, ++exc_label_id);
1859         /* print it */
1860         ia32_emit_exc_label(node);
1861         be_emit_char(':');
1862         be_emit_pad_comment();
1863         be_emit_cstring("/* exception to Block ");
1864         ia32_emit_cfop_target(node);
1865         be_emit_cstring(" */\n");
1866         be_emit_write_line();
1867 }
1868
1869 /**
1870  * Emits code for a node.
1871  */
1872 static void ia32_emit_node(ir_node *node)
1873 {
1874         ir_op *op = get_irn_op(node);
1875
1876         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1877
1878         if (is_ia32_irn(node)) {
1879                 if (get_ia32_exc_label(node)) {
1880                         /* emit the exception label of this instruction */
1881                         ia32_assign_exc_label(node);
1882                 }
1883                 if (mark_spill_reload) {
1884                         if (is_ia32_is_spill(node)) {
1885                                 ia32_emitf(NULL, "\txchg %ebx, %ebx        /* spill mark */\n");
1886                         }
1887                         if (is_ia32_is_reload(node)) {
1888                                 ia32_emitf(NULL, "\txchg %edx, %edx        /* reload mark */\n");
1889                         }
1890                         if (is_ia32_is_remat(node)) {
1891                                 ia32_emitf(NULL, "\txchg %ecx, %ecx        /* remat mark */\n");
1892                         }
1893                 }
1894         }
1895         if (op->ops.generic) {
1896                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1897
1898                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1899
1900                 (*func) (node);
1901         } else {
1902                 emit_Nothing(node);
1903                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1904                 abort();
1905         }
1906 }
1907
1908 /**
1909  * Emits gas alignment directives
1910  */
1911 static void ia32_emit_alignment(unsigned align, unsigned skip)
1912 {
1913         ia32_emitf(NULL, "\t.p2align %u,,%u\n", align, skip);
1914 }
1915
1916 /**
1917  * Emits gas alignment directives for Labels depended on cpu architecture.
1918  */
1919 static void ia32_emit_align_label(void)
1920 {
1921         unsigned align        = ia32_cg_config.label_alignment;
1922         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
1923         ia32_emit_alignment(align, maximum_skip);
1924 }
1925
1926 /**
1927  * Test whether a block should be aligned.
1928  * For cpus in the P4/Athlon class it is useful to align jump labels to
1929  * 16 bytes. However we should only do that if the alignment nops before the
1930  * label aren't executed more often than we have jumps to the label.
1931  */
1932 static int should_align_block(const ir_node *block)
1933 {
1934         static const double DELTA = .0001;
1935         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
1936         ir_node      *prev        = get_prev_block_sched(block);
1937         double        block_freq;
1938         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
1939         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
1940         int           i, n_cfgpreds;
1941
1942         if (exec_freq == NULL)
1943                 return 0;
1944         if (ia32_cg_config.label_alignment_factor <= 0)
1945                 return 0;
1946
1947         block_freq = get_block_execfreq(exec_freq, block);
1948         if (block_freq < DELTA)
1949                 return 0;
1950
1951         n_cfgpreds = get_Block_n_cfgpreds(block);
1952         for(i = 0; i < n_cfgpreds; ++i) {
1953                 const ir_node *pred      = get_Block_cfgpred_block(block, i);
1954                 double         pred_freq = get_block_execfreq(exec_freq, pred);
1955
1956                 if (pred == prev) {
1957                         prev_freq += pred_freq;
1958                 } else {
1959                         jmp_freq  += pred_freq;
1960                 }
1961         }
1962
1963         if (prev_freq < DELTA && !(jmp_freq < DELTA))
1964                 return 1;
1965
1966         jmp_freq /= prev_freq;
1967
1968         return jmp_freq > ia32_cg_config.label_alignment_factor;
1969 }
1970
1971 /**
1972  * Emit the block header for a block.
1973  *
1974  * @param block       the block
1975  * @param prev_block  the previous block
1976  */
1977 static void ia32_emit_block_header(ir_node *block)
1978 {
1979         ir_graph     *irg = current_ir_graph;
1980         int           need_label = block_needs_label(block);
1981         int           i, arity;
1982         ir_exec_freq *exec_freq = cg->birg->exec_freq;
1983
1984         if (block == get_irg_end_block(irg) || block == get_irg_start_block(irg))
1985                 return;
1986
1987         if (ia32_cg_config.label_alignment > 0) {
1988                 /* align the current block if:
1989                  * a) if should be aligned due to its execution frequency
1990                  * b) there is no fall-through here
1991                  */
1992                 if (should_align_block(block)) {
1993                         ia32_emit_align_label();
1994                 } else {
1995                         /* if the predecessor block has no fall-through,
1996                            we can always align the label. */
1997                         int i;
1998                         int has_fallthrough = 0;
1999
2000                         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
2001                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2002                                 if (can_be_fallthrough(cfg_pred)) {
2003                                         has_fallthrough = 1;
2004                                         break;
2005                                 }
2006                         }
2007
2008                         if (!has_fallthrough)
2009                                 ia32_emit_align_label();
2010                 }
2011         }
2012
2013         if (need_label || has_Block_label(block)) {
2014                 ia32_emit_block_name(block);
2015                 be_emit_char(':');
2016
2017                 be_emit_pad_comment();
2018                 be_emit_cstring("   /* ");
2019         } else {
2020                 be_emit_cstring("\t/* ");
2021                 ia32_emit_block_name(block);
2022                 be_emit_cstring(": ");
2023         }
2024
2025         be_emit_cstring("preds:");
2026
2027         /* emit list of pred blocks in comment */
2028         arity = get_irn_arity(block);
2029         for (i = 0; i < arity; ++i) {
2030                 ir_node *predblock = get_Block_cfgpred_block(block, i);
2031                 be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2032         }
2033         if (exec_freq != NULL) {
2034                 be_emit_irprintf(" freq: %f",
2035                                  get_block_execfreq(exec_freq, block));
2036         }
2037         be_emit_cstring(" */\n");
2038         be_emit_write_line();
2039 }
2040
2041 /**
2042  * Walks over the nodes in a block connected by scheduling edges
2043  * and emits code for each node.
2044  */
2045 static void ia32_gen_block(ir_node *block)
2046 {
2047         ir_node *node;
2048
2049         ia32_emit_block_header(block);
2050
2051         /* emit the contents of the block */
2052         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2053         sched_foreach(block, node) {
2054                 ia32_emit_node(node);
2055         }
2056 }
2057
2058 typedef struct exc_entry {
2059         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2060         ir_node *block;      /** The block to call then. */
2061 } exc_entry;
2062
2063 /**
2064  * Block-walker:
2065  * Sets labels for control flow nodes (jump target).
2066  * Links control predecessors to there destination blocks.
2067  */
2068 static void ia32_gen_labels(ir_node *block, void *data)
2069 {
2070         exc_entry **exc_list = data;
2071         ir_node *pred;
2072         int     n;
2073
2074         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2075                 pred = get_Block_cfgpred(block, n);
2076                 set_irn_link(pred, block);
2077
2078                 pred = skip_Proj(pred);
2079                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2080                         exc_entry e;
2081
2082                         e.exc_instr = pred;
2083                         e.block     = block;
2084                         ARR_APP1(exc_entry, *exc_list, e);
2085                         set_irn_link(pred, block);
2086                 }
2087         }
2088 }
2089
2090 /**
2091  * Compare two exception_entries.
2092  */
2093 static int cmp_exc_entry(const void *a, const void *b)
2094 {
2095         const exc_entry *ea = a;
2096         const exc_entry *eb = b;
2097
2098         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2099                 return -1;
2100         return +1;
2101 }
2102
2103 /**
2104  * Main driver. Emits the code for one routine.
2105  */
2106 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2107 {
2108         ir_entity *entity     = get_irg_entity(irg);
2109         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2110         int i, n;
2111
2112         cg       = ia32_cg;
2113         isa      = (const ia32_isa_t*) cg->arch_env;
2114         do_pic   = cg->birg->main_env->options->pic;
2115
2116         ia32_register_emitters();
2117
2118         get_unique_label(pic_base_label, sizeof(pic_base_label), ".PIC_BASE");
2119
2120         be_dbg_method_begin(entity, be_abi_get_stack_layout(cg->birg->abi));
2121         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2122
2123         /* we use links to point to target blocks */
2124         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2125         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2126
2127         /* initialize next block links */
2128         n = ARR_LEN(cg->blk_sched);
2129         for (i = 0; i < n; ++i) {
2130                 ir_node *block = cg->blk_sched[i];
2131                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2132
2133                 set_irn_link(block, prev);
2134         }
2135
2136         for (i = 0; i < n; ++i) {
2137                 ir_node *block = cg->blk_sched[i];
2138
2139                 ia32_gen_block(block);
2140         }
2141
2142         be_gas_emit_function_epilog(entity);
2143         be_dbg_method_end();
2144         be_emit_char('\n');
2145         be_emit_write_line();
2146
2147         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2148
2149         /* Sort the exception table using the exception label id's.
2150            Those are ascending with ascending addresses. */
2151         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2152         {
2153                 int i;
2154
2155                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2156                         be_emit_cstring("\t.long ");
2157                         ia32_emit_exc_label(exc_list[i].exc_instr);
2158                         be_emit_char('\n');
2159                         be_emit_cstring("\t.long ");
2160                         ia32_emit_block_name(exc_list[i].block);
2161                         be_emit_char('\n');
2162                 }
2163         }
2164         DEL_ARR_F(exc_list);
2165 }
2166
2167 static const lc_opt_table_entry_t ia32_emitter_options[] = {
2168         LC_OPT_ENT_BOOL("mark_spill_reload",   "mark spills and reloads with ud opcodes", &mark_spill_reload),
2169         LC_OPT_LAST
2170 };
2171
2172 void ia32_init_emitter(void)
2173 {
2174         lc_opt_entry_t *be_grp;
2175         lc_opt_entry_t *ia32_grp;
2176
2177         be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2178         ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2179
2180         lc_opt_add_table(ia32_grp, ia32_emitter_options);
2181
2182         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
2183 }