36768f81534540ffec3c3544d9614ef18ff31eba
[libfirm] / ir / be / sparc / sparc_emitter.c
1 /*
2  * Copyright (C) 1995-2010 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   emit assembler for a backend graph
23  * @author  Hannes Rapp, Matthias Braun
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <limits.h>
29
30 #include "bitfiddle.h"
31 #include "xmalloc.h"
32 #include "tv.h"
33 #include "iredges.h"
34 #include "debug.h"
35 #include "irgwalk.h"
36 #include "irprintf.h"
37 #include "irop_t.h"
38 #include "irargs_t.h"
39 #include "irprog.h"
40 #include "irargs_t.h"
41 #include "error.h"
42 #include "raw_bitset.h"
43 #include "dbginfo.h"
44 #include "heights.h"
45
46 #include "besched.h"
47 #include "beblocksched.h"
48 #include "beirg.h"
49 #include "begnuas.h"
50 #include "be_dbgout.h"
51 #include "benode.h"
52 #include "bestack.h"
53
54 #include "sparc_emitter.h"
55 #include "gen_sparc_emitter.h"
56 #include "sparc_nodes_attr.h"
57 #include "sparc_new_nodes.h"
58 #include "gen_sparc_regalloc_if.h"
59
60 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
61
62 static ir_heights_t  *heights;
63 static const ir_node *delay_slot_filler; /**< this node has been choosen to fill
64                                               the next delay slot */
65
66 static void sparc_emit_node(const ir_node *node);
67
68 void sparc_emit_immediate(const ir_node *node)
69 {
70         const sparc_attr_t *attr   = get_sparc_attr_const(node);
71         ir_entity          *entity = attr->immediate_value_entity;
72
73         if (entity == NULL) {
74                 int32_t value = attr->immediate_value;
75                 assert(sparc_is_value_imm_encodeable(value));
76                 be_emit_irprintf("%d", value);
77         } else {
78                 if (get_entity_owner(entity) == get_tls_type()) {
79                         be_emit_cstring("%tle_lox10(");
80                 } else {
81                         be_emit_cstring("%lo(");
82                 }
83                 be_gas_emit_entity(entity);
84                 if (attr->immediate_value != 0) {
85                         be_emit_irprintf("%+d", attr->immediate_value);
86                 }
87                 be_emit_char(')');
88         }
89 }
90
91 void sparc_emit_high_immediate(const ir_node *node)
92 {
93         const sparc_attr_t *attr   = get_sparc_attr_const(node);
94         ir_entity          *entity = attr->immediate_value_entity;
95
96         if (entity == NULL) {
97                 uint32_t value = (uint32_t) attr->immediate_value;
98                 be_emit_irprintf("%%hi(0x%X)", value);
99         } else {
100                 if (get_entity_owner(entity) == get_tls_type()) {
101                         be_emit_cstring("%tle_hix22(");
102                 } else {
103                         be_emit_cstring("%hi(");
104                 }
105                 be_gas_emit_entity(entity);
106                 if (attr->immediate_value != 0) {
107                         be_emit_irprintf("%+d", attr->immediate_value);
108                 }
109                 be_emit_char(')');
110         }
111 }
112
113 void sparc_emit_source_register(const ir_node *node, int pos)
114 {
115         const arch_register_t *reg = arch_get_irn_register_in(node, pos);
116         be_emit_char('%');
117         be_emit_string(arch_register_get_name(reg));
118 }
119
120 void sparc_emit_dest_register(const ir_node *node, int pos)
121 {
122         const arch_register_t *reg = arch_get_irn_register_out(node, pos);
123         be_emit_char('%');
124         be_emit_string(arch_register_get_name(reg));
125 }
126
127 /**
128  * Emits either a imm or register depending on arity of node
129  * @param node
130  * @param register no (-1 if no register)
131  */
132 void sparc_emit_reg_or_imm(const ir_node *node, int pos)
133 {
134         if (arch_get_irn_flags(node) & ((arch_irn_flags_t)sparc_arch_irn_flag_immediate_form)) {
135                 // we have a imm input
136                 sparc_emit_immediate(node);
137         } else {
138                 // we have reg input
139                 sparc_emit_source_register(node, pos);
140         }
141 }
142
143 /**
144  * emit SP offset
145  */
146 void sparc_emit_offset(const ir_node *node, int offset_node_pos)
147 {
148         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
149
150         if (attr->is_reg_reg) {
151                 assert(!attr->is_frame_entity);
152                 assert(attr->base.immediate_value == 0);
153                 assert(attr->base.immediate_value_entity == NULL);
154                 be_emit_char('+');
155                 sparc_emit_source_register(node, offset_node_pos);
156         } else if (attr->is_frame_entity) {
157                 int32_t offset = attr->base.immediate_value;
158                 if (offset != 0) {
159                         assert(sparc_is_value_imm_encodeable(offset));
160                         be_emit_irprintf("%+ld", offset);
161                 }
162         } else if (attr->base.immediate_value != 0
163                         || attr->base.immediate_value_entity != NULL) {
164                 be_emit_char('+');
165                 sparc_emit_immediate(node);
166         }
167 }
168
169 void sparc_emit_float_load_store_mode(const ir_node *node)
170 {
171         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
172         ir_mode *mode = attr->load_store_mode;
173         int      bits = get_mode_size_bits(mode);
174
175         assert(mode_is_float(mode));
176
177         switch (bits) {
178         case 32:  return;
179         case 64:  be_emit_char('d'); return;
180         case 128: be_emit_char('q'); return;
181         }
182         panic("invalid flaot load/store mode %+F", mode);
183 }
184
185 /**
186  *  Emit load mode char
187  */
188 void sparc_emit_load_mode(const ir_node *node)
189 {
190         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
191         ir_mode *mode      = attr->load_store_mode;
192         int      bits      = get_mode_size_bits(mode);
193         bool     is_signed = mode_is_signed(mode);
194
195         if (bits == 16) {
196                 be_emit_string(is_signed ? "sh" : "uh");
197         } else if (bits == 8) {
198                 be_emit_string(is_signed ? "sb" : "ub");
199         } else if (bits == 64) {
200                 be_emit_char('d');
201         } else {
202                 assert(bits == 32);
203         }
204 }
205
206 /**
207  * Emit store mode char
208  */
209 void sparc_emit_store_mode(const ir_node *node)
210 {
211         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
212         ir_mode *mode      = attr->load_store_mode;
213         int      bits      = get_mode_size_bits(mode);
214
215         if (bits == 16) {
216                 be_emit_string("h");
217         } else if (bits == 8) {
218                 be_emit_string("b");
219         } else if (bits == 64) {
220                 be_emit_char('d');
221         } else {
222                 assert(bits == 32);
223         }
224 }
225
226 static void emit_fp_suffix(const ir_mode *mode)
227 {
228         unsigned bits = get_mode_size_bits(mode);
229         assert(mode_is_float(mode));
230
231         if (bits == 32) {
232                 be_emit_char('s');
233         } else if (bits == 64) {
234                 be_emit_char('d');
235         } else if (bits == 128) {
236                 be_emit_char('q');
237         } else {
238                 panic("invalid FP mode");
239         }
240 }
241
242 void sparc_emit_fp_conv_source(const ir_node *node)
243 {
244         const sparc_fp_conv_attr_t *attr = get_sparc_fp_conv_attr_const(node);
245         emit_fp_suffix(attr->src_mode);
246 }
247
248 void sparc_emit_fp_conv_destination(const ir_node *node)
249 {
250         const sparc_fp_conv_attr_t *attr = get_sparc_fp_conv_attr_const(node);
251         emit_fp_suffix(attr->dest_mode);
252 }
253
254 /**
255  * emits the FP mode suffix char
256  */
257 void sparc_emit_fp_mode_suffix(const ir_node *node)
258 {
259         const sparc_fp_attr_t *attr = get_sparc_fp_attr_const(node);
260         emit_fp_suffix(attr->fp_mode);
261 }
262
263 static ir_node *get_jump_target(const ir_node *jump)
264 {
265         return (ir_node*)get_irn_link(jump);
266 }
267
268 /**
269  * Returns the target label for a control flow node.
270  */
271 static void sparc_emit_cfop_target(const ir_node *node)
272 {
273         ir_node *block = get_jump_target(node);
274         be_gas_emit_block_name(block);
275 }
276
277 static int get_sparc_Call_dest_addr_pos(const ir_node *node)
278 {
279         return get_irn_arity(node)-1;
280 }
281
282 static bool ba_is_fallthrough(const ir_node *node)
283 {
284         ir_node *block      = get_nodes_block(node);
285         ir_node *next_block = (ir_node*)get_irn_link(block);
286         return get_irn_link(node) == next_block;
287 }
288
289 static bool is_no_instruction(const ir_node *node)
290 {
291         /* copies are nops if src_reg == dest_reg */
292         if (be_is_Copy(node) || be_is_CopyKeep(node)) {
293                 const arch_register_t *src_reg  = arch_get_irn_register_in(node, 0);
294                 const arch_register_t *dest_reg = arch_get_irn_register_out(node, 0);
295
296                 if (src_reg == dest_reg)
297                         return true;
298         }
299         if (be_is_IncSP(node) && be_get_IncSP_offset(node) == 0)
300                 return true;
301         /* Ba is not emitted if it is a simple fallthrough */
302         if (is_sparc_Ba(node) && ba_is_fallthrough(node))
303                 return true;
304
305         return be_is_Keep(node) || be_is_Start(node) || is_Phi(node);
306 }
307
308 static bool has_delay_slot(const ir_node *node)
309 {
310         if (is_sparc_Ba(node)) {
311                 return !ba_is_fallthrough(node);
312         }
313
314         return arch_get_irn_flags(node) & sparc_arch_irn_flag_has_delay_slot;
315 }
316
317 /** returns true if the emitter for this sparc node can produce more than one
318  * actual sparc instruction.
319  * Usually it is a bad sign if we have to add instructions here. We should
320  * rather try to get them lowered down. So we can actually put them into
321  * delay slots and make them more accessible to the scheduler.
322  */
323 static bool emits_multiple_instructions(const ir_node *node)
324 {
325         if (has_delay_slot(node))
326                 return true;
327
328         if (is_sparc_Call(node)) {
329                 return arch_get_irn_flags(node) & sparc_arch_irn_flag_aggregate_return;
330         }
331
332         return is_sparc_SMulh(node) || is_sparc_UMulh(node)
333                 || is_sparc_SDiv(node) || is_sparc_UDiv(node)
334                 || be_is_MemPerm(node) || be_is_Perm(node);
335 }
336
337 /**
338  * search for an instruction that can fill the delay slot of @p node
339  */
340 static const ir_node *pick_delay_slot_for(const ir_node *node)
341 {
342         const ir_node *check      = node;
343         const ir_node *schedpoint = node;
344         unsigned       tries      = 0;
345         /* currently we don't track which registers are still alive, so we can't
346          * pick any other instructions other than the one directly preceding */
347         static const unsigned PICK_DELAY_SLOT_MAX_DISTANCE = 1;
348
349         assert(has_delay_slot(node));
350
351         if (is_sparc_Call(node)) {
352                 const sparc_attr_t *attr   = get_sparc_attr_const(node);
353                 ir_entity          *entity = attr->immediate_value_entity;
354                 if (entity != NULL) {
355                         check = NULL; /* pick any instruction, dependencies on Call
356                                          don't matter */
357                 } else {
358                         /* we only need to check the value for the call destination */
359                         check = get_irn_n(node, get_sparc_Call_dest_addr_pos(node));
360                 }
361
362                 /* the Call also destroys the value of %o7, but since this is currently
363                  * marked as ignore register in the backend, it should never be used by
364                  * the instruction in the delay slot. */
365         } else if (is_sparc_Return(node)) {
366                 /* we only have to check the jump destination value */
367                 int arity = get_irn_arity(node);
368                 int i;
369
370                 check = NULL;
371                 for (i = 0; i < arity; ++i) {
372                         ir_node               *in  = get_irn_n(node, i);
373                         const arch_register_t *reg = arch_get_irn_register(in);
374                         if (reg == &sparc_registers[REG_O7]) {
375                                 check = skip_Proj(in);
376                                 break;
377                         }
378                 }
379         } else {
380                 check = node;
381         }
382
383         while (sched_has_prev(schedpoint)) {
384                 schedpoint = sched_prev(schedpoint);
385
386                 if (has_delay_slot(schedpoint))
387                         break;
388
389                 /* skip things which don't really result in instructions */
390                 if (is_no_instruction(schedpoint))
391                         continue;
392
393                 if (tries++ >= PICK_DELAY_SLOT_MAX_DISTANCE)
394                         break;
395
396                 if (emits_multiple_instructions(schedpoint))
397                         continue;
398
399                 /* if check and schedpoint are not in the same block, give up. */
400                 if (check != NULL
401                                 && get_nodes_block(check) != get_nodes_block(schedpoint))
402                         break;
403
404                 /* allowed for delayslot: any instruction which is not necessary to
405                  * compute an input to the branch. */
406                 if (check != NULL
407                                 && heights_reachable_in_block(heights, check, schedpoint))
408                         continue;
409
410                 /* found something */
411                 return schedpoint;
412         }
413
414         return NULL;
415 }
416
417 /**
418  * Emits code for stack space management
419  */
420 static void emit_be_IncSP(const ir_node *irn)
421 {
422         int offset = be_get_IncSP_offset(irn);
423
424         if (offset == 0)
425                 return;
426
427         /* SPARC stack grows downwards */
428         if (offset < 0) {
429                 be_emit_cstring("\tsub ");
430                 offset = -offset;
431         } else {
432                 be_emit_cstring("\tadd ");
433         }
434
435         sparc_emit_source_register(irn, 0);
436         be_emit_irprintf(", %d", -offset);
437         be_emit_cstring(", ");
438         sparc_emit_dest_register(irn, 0);
439         be_emit_finish_line_gas(irn);
440 }
441
442 /**
443  * emits code for mulh
444  */
445 static void emit_sparc_Mulh(const ir_node *irn)
446 {
447         be_emit_cstring("\t");
448         if (is_sparc_UMulh(irn)) {
449                 be_emit_char('u');
450         } else {
451                 assert(is_sparc_SMulh(irn));
452                 be_emit_char('s');
453         }
454         be_emit_cstring("mul ");
455
456         sparc_emit_source_register(irn, 0);
457         be_emit_cstring(", ");
458         sparc_emit_reg_or_imm(irn, 1);
459         be_emit_cstring(", ");
460         sparc_emit_dest_register(irn, 0);
461         be_emit_finish_line_gas(irn);
462
463         // our result is in the y register now
464         // we just copy it to the assigned target reg
465         be_emit_cstring("\tmov %y, ");
466         sparc_emit_dest_register(irn, 0);
467         be_emit_finish_line_gas(irn);
468 }
469
470 static void fill_delay_slot(void)
471 {
472         if (delay_slot_filler != NULL) {
473                 sparc_emit_node(delay_slot_filler);
474                 delay_slot_filler = NULL;
475         } else {
476                 be_emit_cstring("\tnop\n");
477                 be_emit_write_line();
478         }
479 }
480
481 static void emit_sparc_Div(const ir_node *node, bool is_signed)
482 {
483         /* can we get the delay count of the wr instruction somewhere? */
484         unsigned wry_delay_count = 3;
485         unsigned i;
486
487         be_emit_cstring("\twr ");
488         sparc_emit_source_register(node, 0);
489         be_emit_cstring(", 0, %y");
490         be_emit_finish_line_gas(node);
491
492         for (i = 0; i < wry_delay_count; ++i) {
493                 fill_delay_slot();
494         }
495
496         be_emit_irprintf("\t%s ", is_signed ? "sdiv" : "udiv");
497         sparc_emit_source_register(node, 1);
498         be_emit_cstring(", ");
499         sparc_emit_reg_or_imm(node, 2);
500         be_emit_cstring(", ");
501         sparc_emit_dest_register(node, 0);
502         be_emit_finish_line_gas(node);
503 }
504
505 static void emit_sparc_SDiv(const ir_node *node)
506 {
507         emit_sparc_Div(node, true);
508 }
509
510 static void emit_sparc_UDiv(const ir_node *node)
511 {
512         emit_sparc_Div(node, false);
513 }
514
515 /**
516  * Emits code for Call node
517  */
518 static void emit_sparc_Call(const ir_node *node)
519 {
520         const sparc_attr_t *attr   = get_sparc_attr_const(node);
521         ir_entity          *entity = attr->immediate_value_entity;
522
523         be_emit_cstring("\tcall ");
524         if (entity != NULL) {
525             be_gas_emit_entity(entity);
526             if (attr->immediate_value != 0) {
527                         be_emit_irprintf("%+d", attr->immediate_value);
528                 }
529                 be_emit_cstring(", 0");
530         } else {
531                 int dest_addr = get_sparc_Call_dest_addr_pos(node);
532                 sparc_emit_source_register(node, dest_addr);
533         }
534         be_emit_finish_line_gas(node);
535
536         fill_delay_slot();
537
538         if (arch_get_irn_flags(node) & sparc_arch_irn_flag_aggregate_return) {
539                 be_emit_cstring("\tunimp 8\n");
540                 be_emit_write_line();
541         }
542 }
543
544 /**
545  * Emit code for Perm node
546  */
547 static void emit_be_Perm(const ir_node *irn)
548 {
549         be_emit_cstring("\txor ");
550         sparc_emit_source_register(irn, 1);
551         be_emit_cstring(", ");
552         sparc_emit_source_register(irn, 0);
553         be_emit_cstring(", ");
554         sparc_emit_source_register(irn, 0);
555         be_emit_finish_line_gas(NULL);
556
557         be_emit_cstring("\txor ");
558         sparc_emit_source_register(irn, 1);
559         be_emit_cstring(", ");
560         sparc_emit_source_register(irn, 0);
561         be_emit_cstring(", ");
562         sparc_emit_source_register(irn, 1);
563         be_emit_finish_line_gas(NULL);
564
565         be_emit_cstring("\txor ");
566         sparc_emit_source_register(irn, 1);
567         be_emit_cstring(", ");
568         sparc_emit_source_register(irn, 0);
569         be_emit_cstring(", ");
570         sparc_emit_source_register(irn, 0);
571         be_emit_finish_line_gas(irn);
572 }
573
574 /* The stack pointer must always be SPARC_STACK_ALIGNMENT bytes aligned, so get
575  * the next bigger integer that's evenly divisible by it. */
576 static unsigned get_aligned_sp_change(const unsigned num_regs)
577 {
578         const unsigned bytes = num_regs * SPARC_REGISTER_SIZE;
579         return round_up2(bytes, SPARC_STACK_ALIGNMENT);
580 }
581
582 /* Spill register l0 or both l0 and l1, depending on n_spilled and n_to_spill.*/
583 static void memperm_emit_spill_registers(const ir_node *node, int n_spilled,
584                                          int n_to_spill)
585 {
586         assert(n_spilled < n_to_spill);
587
588         if (n_spilled == 0) {
589                 /* We always reserve stack space for two registers because during copy
590                  * processing we don't know yet if we also need to handle a cycle which
591                  * needs two registers.  More complicated code in emit_MemPerm would
592                  * prevent wasting SPARC_REGISTER_SIZE bytes of stack space but
593                  * it is not worth the worse readability of emit_MemPerm. */
594
595                 /* Keep stack pointer aligned. */
596                 unsigned sp_change = get_aligned_sp_change(2);
597                 be_emit_irprintf("\tsub %%sp, %u, %%sp", sp_change);
598                 be_emit_finish_line_gas(node);
599
600                 /* Spill register l0. */
601                 be_emit_irprintf("\tst %%l0, [%%sp%+d]", SPARC_MIN_STACKSIZE);
602                 be_emit_finish_line_gas(node);
603         }
604
605         if (n_to_spill == 2) {
606                 /* Spill register l1. */
607                 be_emit_irprintf("\tst %%l1, [%%sp%+d]", SPARC_MIN_STACKSIZE + SPARC_REGISTER_SIZE);
608                 be_emit_finish_line_gas(node);
609         }
610 }
611
612 /* Restore register l0 or both l0 and l1, depending on n_spilled. */
613 static void memperm_emit_restore_registers(const ir_node *node, int n_spilled)
614 {
615         unsigned sp_change;
616
617         if (n_spilled == 2) {
618                 /* Restore register l1. */
619                 be_emit_irprintf("\tld [%%sp%+d], %%l1", SPARC_MIN_STACKSIZE + SPARC_REGISTER_SIZE);
620                 be_emit_finish_line_gas(node);
621         }
622
623         /* Restore register l0. */
624         be_emit_irprintf("\tld [%%sp%+d], %%l0", SPARC_MIN_STACKSIZE);
625         be_emit_finish_line_gas(node);
626
627         /* Restore stack pointer. */
628         sp_change = get_aligned_sp_change(2);
629         be_emit_irprintf("\tadd %%sp, %u, %%sp", sp_change);
630         be_emit_finish_line_gas(node);
631 }
632
633 /* Emit code to copy in_ent to out_ent.  Only uses l0. */
634 static void memperm_emit_copy(const ir_node *node, ir_entity *in_ent,
635                               ir_entity *out_ent)
636 {
637         ir_graph          *irg     = get_irn_irg(node);
638         be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
639         int                off_in  = be_get_stack_entity_offset(layout, in_ent, 0);
640         int                off_out = be_get_stack_entity_offset(layout, out_ent, 0);
641
642         /* Load from input entity. */
643         be_emit_irprintf("\tld [%%fp%+d], %%l0", off_in);
644         be_emit_finish_line_gas(node);
645
646         /* Store to output entity. */
647         be_emit_irprintf("\tst %%l0, [%%fp%+d]", off_out);
648         be_emit_finish_line_gas(node);
649 }
650
651 /* Emit code to swap ent1 and ent2.  Uses l0 and l1. */
652 static void memperm_emit_swap(const ir_node *node, ir_entity *ent1,
653                               ir_entity *ent2)
654 {
655         ir_graph          *irg     = get_irn_irg(node);
656         be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
657         int                off1    = be_get_stack_entity_offset(layout, ent1, 0);
658         int                off2    = be_get_stack_entity_offset(layout, ent2, 0);
659
660         /* Load from first input entity. */
661         be_emit_irprintf("\tld [%%fp%+d], %%l0", off1);
662         be_emit_finish_line_gas(node);
663
664         /* Load from second input entity. */
665         be_emit_irprintf("\tld [%%fp%+d], %%l1", off2);
666         be_emit_finish_line_gas(node);
667
668         /* Store first value to second output entity. */
669         be_emit_irprintf("\tst %%l0, [%%fp%+d]", off2);
670         be_emit_finish_line_gas(node);
671
672         /* Store second value to first output entity. */
673         be_emit_irprintf("\tst %%l1, [%%fp%+d]", off1);
674         be_emit_finish_line_gas(node);
675 }
676
677 /* Find the index of ent in ents or return -1 if not found. */
678 static int get_index(ir_entity **ents, int n, ir_entity *ent)
679 {
680         int i;
681
682         for (i = 0; i < n; ++i)
683                 if (ents[i] == ent)
684                         return i;
685
686         return -1;
687 }
688
689 /*
690  * Emit code for a MemPerm node.
691  *
692  * Analyze MemPerm for copy chains and cyclic swaps and resolve them using
693  * loads and stores.
694  * This function is conceptually very similar to permute_values in
695  * beprefalloc.c.
696  */
697 static void emit_be_MemPerm(const ir_node *node)
698 {
699         int         memperm_arity = be_get_MemPerm_entity_arity(node);
700         /* Upper limit for the number of participating entities is twice the
701          * arity, e.g., for a simple copying MemPerm node with one input/output. */
702         int         max_size      = 2 * memperm_arity;
703         ir_entity **entities      = ALLOCANZ(ir_entity *, max_size);
704         /* sourceof contains the input entity for each entity.  If an entity is
705          * never used as an output, its entry in sourceof is a fix point. */
706         int        *sourceof      = ALLOCANZ(int,         max_size);
707         /* n_users counts how many output entities use this entity as their input.*/
708         int        *n_users       = ALLOCANZ(int,         max_size);
709         /* n_spilled records the number of spilled registers, either 1 or 2. */
710         int         n_spilled     = 0;
711         int         i, n, oidx;
712
713         for (i = 0; i < max_size; ++i) {
714                 sourceof[i] = i;
715         }
716
717         for (i = n = 0; i < memperm_arity; ++i) {
718                 ir_entity *out  = be_get_MemPerm_out_entity(node, i);
719                 ir_entity *in   = be_get_MemPerm_in_entity(node, i);
720                 int              oidx; /* Out index */
721                 int              iidx; /* In index */
722
723                 /* Insert into entities to be able to operate on unique indices. */
724                 if (get_index(entities, n, out) == -1)
725                         entities[n++] = out;
726                 if (get_index(entities, n, in) == -1)
727                         entities[n++] = in;
728
729                 oidx = get_index(entities, n, out);
730                 iidx = get_index(entities, n, in);
731
732                 sourceof[oidx] = iidx; /* Remember the source. */
733                 ++n_users[iidx]; /* Increment number of users of this entity. */
734         }
735
736         /* First do all the copies. */
737         for (oidx = 0; oidx < n; /* empty */) {
738                 int iidx = sourceof[oidx];
739
740                 /* Nothing to do for fix points.
741                  * Also, if entities[oidx] is used as an input by another copy, we
742                  * can't overwrite entities[oidx] yet.*/
743                 if (iidx == oidx || n_users[oidx] > 0) {
744                         ++oidx;
745                         continue;
746                 }
747
748                 /* We found the end of a 'chain', so do the copy. */
749                 if (n_spilled == 0) {
750                         memperm_emit_spill_registers(node, n_spilled, /*n_to_spill=*/1);
751                         n_spilled = 1;
752                 }
753                 memperm_emit_copy(node, entities[iidx], entities[oidx]);
754
755                 /* Mark as done. */
756                 sourceof[oidx] = oidx;
757
758                 assert(n_users[iidx] > 0);
759                 /* Decrementing the number of users might enable us to do another
760                  * copy. */
761                 --n_users[iidx];
762
763                 if (iidx < oidx && n_users[iidx] == 0) {
764                         oidx = iidx;
765                 } else {
766                         ++oidx;
767                 }
768         }
769
770         /* The rest are cycles. */
771         for (oidx = 0; oidx < n; /* empty */) {
772                 int iidx = sourceof[oidx];
773                 int tidx;
774
775                 /* Nothing to do for fix points. */
776                 if (iidx == oidx) {
777                         ++oidx;
778                         continue;
779                 }
780
781                 assert(n_users[iidx] == 1);
782
783                 /* Swap the two values to resolve the cycle. */
784                 if (n_spilled < 2) {
785                         memperm_emit_spill_registers(node, n_spilled, /*n_to_spill=*/2);
786                         n_spilled = 2;
787                 }
788                 memperm_emit_swap(node, entities[iidx], entities[oidx]);
789
790                 tidx = sourceof[iidx];
791                 /* Mark as done. */
792                 sourceof[iidx] = iidx;
793
794                 /* The source of oidx is now the old source of iidx, because we swapped
795                  * the two entities. */
796                 sourceof[oidx] = tidx;
797         }
798
799 #ifdef DEBUG_libfirm
800         /* Only fix points should remain. */
801         for (i = 0; i < max_size; ++i) {
802                 assert(sourceof[i] == i);
803         }
804 #endif
805
806         assert(n_spilled > 0 && "Useless MemPerm node");
807
808         memperm_emit_restore_registers(node, n_spilled);
809 }
810
811 static void emit_sparc_Return(const ir_node *node)
812 {
813         ir_graph  *irg    = get_irn_irg(node);
814         ir_entity *entity = get_irg_entity(irg);
815         ir_type   *type   = get_entity_type(entity);
816
817         const char *destreg = "%o7";
818
819         /* hack: we don't explicitely model register changes because of the
820          * restore node. So we have to do it manually here */
821         if (delay_slot_filler != NULL &&
822                         (is_sparc_Restore(delay_slot_filler)
823                          || is_sparc_RestoreZero(delay_slot_filler))) {
824                 destreg = "%i7";
825         }
826         be_emit_cstring("\tjmp ");
827         be_emit_string(destreg);
828         if (get_method_calling_convention(type) & cc_compound_ret) {
829                 be_emit_cstring("+12");
830         } else {
831                 be_emit_cstring("+8");
832         }
833         be_emit_finish_line_gas(node);
834         fill_delay_slot();
835 }
836
837 static void emit_sparc_FrameAddr(const ir_node *node)
838 {
839         const sparc_attr_t *attr   = get_sparc_attr_const(node);
840         int32_t             offset = attr->immediate_value;
841
842         if (offset < 0) {
843                 be_emit_cstring("\tadd ");
844                 sparc_emit_source_register(node, 0);
845                 be_emit_cstring(", ");
846                 assert(sparc_is_value_imm_encodeable(offset));
847                 be_emit_irprintf("%ld", offset);
848         } else {
849                 be_emit_cstring("\tsub ");
850                 sparc_emit_source_register(node, 0);
851                 be_emit_cstring(", ");
852                 assert(sparc_is_value_imm_encodeable(-offset));
853                 be_emit_irprintf("%ld", -offset);
854         }
855
856         be_emit_cstring(", ");
857         sparc_emit_dest_register(node, 0);
858         be_emit_finish_line_gas(node);
859 }
860
861 static const char *get_icc_unsigned(ir_relation relation)
862 {
863         switch (relation & (ir_relation_less_equal_greater)) {
864         case ir_relation_false:              return "bn";
865         case ir_relation_equal:              return "be";
866         case ir_relation_less:               return "blu";
867         case ir_relation_less_equal:         return "bleu";
868         case ir_relation_greater:            return "bgu";
869         case ir_relation_greater_equal:      return "bgeu";
870         case ir_relation_less_greater:       return "bne";
871         case ir_relation_less_equal_greater: return "ba";
872         default: panic("Cmp has unsupported relation");
873         }
874 }
875
876 static const char *get_icc_signed(ir_relation relation)
877 {
878         switch (relation & (ir_relation_less_equal_greater)) {
879         case ir_relation_false:              return "bn";
880         case ir_relation_equal:              return "be";
881         case ir_relation_less:               return "bl";
882         case ir_relation_less_equal:         return "ble";
883         case ir_relation_greater:            return "bg";
884         case ir_relation_greater_equal:      return "bge";
885         case ir_relation_less_greater:       return "bne";
886         case ir_relation_less_equal_greater: return "ba";
887         default: panic("Cmp has unsupported relation");
888         }
889 }
890
891 static const char *get_fcc(ir_relation relation)
892 {
893         switch (relation) {
894         case ir_relation_false:                   return "fbn";
895         case ir_relation_equal:                   return "fbe";
896         case ir_relation_less:                    return "fbl";
897         case ir_relation_less_equal:              return "fble";
898         case ir_relation_greater:                 return "fbg";
899         case ir_relation_greater_equal:           return "fbge";
900         case ir_relation_less_greater:            return "fblg";
901         case ir_relation_less_equal_greater:      return "fbo";
902         case ir_relation_unordered:               return "fbu";
903         case ir_relation_unordered_equal:         return "fbue";
904         case ir_relation_unordered_less:          return "fbul";
905         case ir_relation_unordered_less_equal:    return "fbule";
906         case ir_relation_unordered_greater:       return "fbug";
907         case ir_relation_unordered_greater_equal: return "fbuge";
908         case ir_relation_unordered_less_greater:  return "fbne";
909         case ir_relation_true:                    return "fba";
910         }
911         panic("invalid relation");
912 }
913
914 typedef const char* (*get_cc_func)(ir_relation relation);
915
916 static void emit_sparc_branch(const ir_node *node, get_cc_func get_cc)
917 {
918         const sparc_jmp_cond_attr_t *attr = get_sparc_jmp_cond_attr_const(node);
919         ir_relation      relation    = attr->relation;
920         const ir_node   *proj_true   = NULL;
921         const ir_node   *proj_false  = NULL;
922         const ir_edge_t *edge;
923         const ir_node   *block;
924         const ir_node   *next_block;
925
926         foreach_out_edge(node, edge) {
927                 ir_node *proj = get_edge_src_irn(edge);
928                 long nr = get_Proj_proj(proj);
929                 if (nr == pn_Cond_true) {
930                         proj_true = proj;
931                 } else {
932                         proj_false = proj;
933                 }
934         }
935
936         /* for now, the code works for scheduled and non-schedules blocks */
937         block = get_nodes_block(node);
938
939         /* we have a block schedule */
940         next_block = (ir_node*)get_irn_link(block);
941
942         if (get_irn_link(proj_true) == next_block) {
943                 /* exchange both proj's so the second one can be omitted */
944                 const ir_node *t = proj_true;
945
946                 proj_true  = proj_false;
947                 proj_false = t;
948                 relation   = get_negated_relation(relation);
949         }
950
951         /* emit the true proj */
952         be_emit_cstring("\t");
953         be_emit_string(get_cc(relation));
954         be_emit_char(' ');
955         sparc_emit_cfop_target(proj_true);
956         be_emit_finish_line_gas(proj_true);
957
958         fill_delay_slot();
959
960         if (get_irn_link(proj_false) == next_block) {
961                 be_emit_cstring("\t/* fallthrough to ");
962                 sparc_emit_cfop_target(proj_false);
963                 be_emit_cstring(" */");
964                 be_emit_finish_line_gas(proj_false);
965         } else {
966                 be_emit_cstring("\tba ");
967                 sparc_emit_cfop_target(proj_false);
968                 be_emit_finish_line_gas(proj_false);
969                 fill_delay_slot();
970         }
971 }
972
973 static void emit_sparc_Bicc(const ir_node *node)
974 {
975         const sparc_jmp_cond_attr_t *attr = get_sparc_jmp_cond_attr_const(node);
976         bool             is_unsigned = attr->is_unsigned;
977         emit_sparc_branch(node, is_unsigned ? get_icc_unsigned : get_icc_signed);
978 }
979
980 static void emit_sparc_fbfcc(const ir_node *node)
981 {
982         /* if the flags producing node was immediately in front of us, emit
983          * a nop */
984         ir_node *flags = get_irn_n(node, n_sparc_fbfcc_flags);
985         ir_node *prev  = sched_prev(node);
986         if (is_Block(prev)) {
987                 /* TODO: when the flags come from another block, then we have to do
988                  * more complicated tests to see wether the flag producing node is
989                  * potentially in front of us (could happen for fallthroughs) */
990                 panic("TODO: fbfcc flags come from other block");
991         }
992         if (skip_Proj(flags) == prev) {
993                 be_emit_cstring("\tnop\n");
994         }
995         emit_sparc_branch(node, get_fcc);
996 }
997
998 static void emit_sparc_Ba(const ir_node *node)
999 {
1000         if (ba_is_fallthrough(node)) {
1001                 be_emit_cstring("\t/* fallthrough to ");
1002                 sparc_emit_cfop_target(node);
1003                 be_emit_cstring(" */");
1004                 be_emit_finish_line_gas(node);
1005         } else {
1006                 be_emit_cstring("\tba ");
1007                 sparc_emit_cfop_target(node);
1008                 be_emit_finish_line_gas(node);
1009                 fill_delay_slot();
1010         }
1011 }
1012
1013 static void emit_sparc_SwitchJmp(const ir_node *node)
1014 {
1015         const sparc_switch_jmp_attr_t *attr = get_sparc_switch_jmp_attr_const(node);
1016
1017         be_emit_cstring("\tjmp ");
1018         sparc_emit_source_register(node, 0);
1019         be_emit_finish_line_gas(node);
1020         fill_delay_slot();
1021
1022         emit_jump_table(node, attr->default_proj_num, attr->jump_table,
1023                         get_jump_target);
1024 }
1025
1026 static void emit_fmov(const ir_node *node, const arch_register_t *src_reg,
1027                       const arch_register_t *dst_reg)
1028 {
1029         be_emit_cstring("\tfmovs %");
1030         be_emit_string(arch_register_get_name(src_reg));
1031         be_emit_cstring(", %");
1032         be_emit_string(arch_register_get_name(dst_reg));
1033         be_emit_finish_line_gas(node);
1034 }
1035
1036 static const arch_register_t *get_next_fp_reg(const arch_register_t *reg)
1037 {
1038         unsigned idx = reg->global_index;
1039         assert(reg == &sparc_registers[idx]);
1040         idx++;
1041         assert(idx - REG_F0 < N_sparc_fp_REGS);
1042         return &sparc_registers[idx];
1043 }
1044
1045 static void emit_be_Copy(const ir_node *node)
1046 {
1047         ir_mode               *mode    = get_irn_mode(node);
1048         const arch_register_t *src_reg = arch_get_irn_register_in(node, 0);
1049         const arch_register_t *dst_reg = arch_get_irn_register_out(node, 0);
1050
1051         if (src_reg == dst_reg)
1052                 return;
1053
1054         if (mode_is_float(mode)) {
1055                 unsigned bits = get_mode_size_bits(mode);
1056                 int      n    = bits > 32 ? bits > 64 ? 3 : 1 : 0;
1057                 int      i;
1058                 emit_fmov(node, src_reg, dst_reg);
1059                 for (i = 0; i < n; ++i) {
1060                         src_reg = get_next_fp_reg(src_reg);
1061                         dst_reg = get_next_fp_reg(dst_reg);
1062                         emit_fmov(node, src_reg, dst_reg);
1063                 }
1064         } else if (mode_is_data(mode)) {
1065                 be_emit_cstring("\tmov ");
1066                 sparc_emit_source_register(node, 0);
1067                 be_emit_cstring(", ");
1068                 sparc_emit_dest_register(node, 0);
1069                 be_emit_finish_line_gas(node);
1070         } else {
1071                 panic("emit_be_Copy: invalid mode");
1072         }
1073 }
1074
1075 static void emit_nothing(const ir_node *irn)
1076 {
1077         (void) irn;
1078 }
1079
1080 typedef void (*emit_func) (const ir_node *);
1081
1082 static inline void set_emitter(ir_op *op, emit_func sparc_emit_node)
1083 {
1084         op->ops.generic = (op_func)sparc_emit_node;
1085 }
1086
1087 /**
1088  * Enters the emitter functions for handled nodes into the generic
1089  * pointer of an opcode.
1090  */
1091 static void sparc_register_emitters(void)
1092 {
1093         /* first clear the generic function pointer for all ops */
1094         clear_irp_opcodes_generic_func();
1095         /* register all emitter functions defined in spec */
1096         sparc_register_spec_emitters();
1097
1098         /* custom emitter */
1099         set_emitter(op_be_Copy,         emit_be_Copy);
1100         set_emitter(op_be_CopyKeep,     emit_be_Copy);
1101         set_emitter(op_be_IncSP,        emit_be_IncSP);
1102         set_emitter(op_be_MemPerm,      emit_be_MemPerm);
1103         set_emitter(op_be_Perm,         emit_be_Perm);
1104         set_emitter(op_sparc_Ba,        emit_sparc_Ba);
1105         set_emitter(op_sparc_Bicc,      emit_sparc_Bicc);
1106         set_emitter(op_sparc_Call,      emit_sparc_Call);
1107         set_emitter(op_sparc_fbfcc,     emit_sparc_fbfcc);
1108         set_emitter(op_sparc_FrameAddr, emit_sparc_FrameAddr);
1109         set_emitter(op_sparc_SMulh,     emit_sparc_Mulh);
1110         set_emitter(op_sparc_UMulh,     emit_sparc_Mulh);
1111         set_emitter(op_sparc_Return,    emit_sparc_Return);
1112         set_emitter(op_sparc_SDiv,      emit_sparc_SDiv);
1113         set_emitter(op_sparc_SwitchJmp, emit_sparc_SwitchJmp);
1114         set_emitter(op_sparc_UDiv,      emit_sparc_UDiv);
1115
1116         /* no need to emit anything for the following nodes */
1117         set_emitter(op_be_Keep,     emit_nothing);
1118         set_emitter(op_sparc_Start, emit_nothing);
1119         set_emitter(op_Phi,         emit_nothing);
1120 }
1121
1122 /**
1123  * Emits code for a node.
1124  */
1125 static void sparc_emit_node(const ir_node *node)
1126 {
1127         ir_op *op = get_irn_op(node);
1128
1129         if (op->ops.generic) {
1130                 emit_func func = (emit_func) op->ops.generic;
1131                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1132                 (*func) (node);
1133         } else {
1134                 panic("No emit handler for node %+F (graph %+F)\n", node,
1135                       current_ir_graph);
1136         }
1137 }
1138
1139 static ir_node *find_next_delay_slot(ir_node *from)
1140 {
1141         ir_node *schedpoint = from;
1142         while (!has_delay_slot(schedpoint)) {
1143                 if (!sched_has_next(schedpoint))
1144                         return NULL;
1145                 schedpoint = sched_next(schedpoint);
1146         }
1147         return schedpoint;
1148 }
1149
1150 static bool block_needs_label(const ir_node *block, const ir_node *sched_prev)
1151 {
1152         int n_cfgpreds;
1153
1154         if (has_Block_entity(block))
1155                 return true;
1156
1157         n_cfgpreds = get_Block_n_cfgpreds(block);
1158         if (n_cfgpreds == 0) {
1159                 return false;
1160         } else if (n_cfgpreds > 1) {
1161                 return true;
1162         } else {
1163                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
1164                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
1165                 if (is_Proj(cfgpred) && is_sparc_SwitchJmp(get_Proj_pred(cfgpred)))
1166                         return true;
1167                 return sched_prev != cfgpred_block || get_irn_link(cfgpred) != block;
1168         }
1169 }
1170
1171 /**
1172  * Walks over the nodes in a block connected by scheduling edges
1173  * and emits code for each node.
1174  */
1175 static void sparc_emit_block(ir_node *block, ir_node *prev)
1176 {
1177         ir_node *node;
1178         ir_node *next_delay_slot;
1179
1180         assert(is_Block(block));
1181
1182         if (block_needs_label(block, prev)) {
1183                 be_gas_emit_block_name(block);
1184                 be_emit_cstring(":\n");
1185                 be_emit_write_line();
1186         }
1187
1188         next_delay_slot = find_next_delay_slot(sched_first(block));
1189         if (next_delay_slot != NULL)
1190                 delay_slot_filler = pick_delay_slot_for(next_delay_slot);
1191
1192         sched_foreach(block, node) {
1193                 if (node == delay_slot_filler) {
1194                         continue;
1195                 }
1196
1197                 sparc_emit_node(node);
1198
1199                 if (node == next_delay_slot) {
1200                         assert(delay_slot_filler == NULL);
1201                         next_delay_slot = find_next_delay_slot(sched_next(node));
1202                         if (next_delay_slot != NULL)
1203                                 delay_slot_filler = pick_delay_slot_for(next_delay_slot);
1204                 }
1205         }
1206 }
1207
1208 /**
1209  * Emits code for function start.
1210  */
1211 static void sparc_emit_func_prolog(ir_graph *irg)
1212 {
1213         ir_entity *ent = get_irg_entity(irg);
1214         be_gas_emit_function_prolog(ent, 4);
1215         be_emit_write_line();
1216 }
1217
1218 /**
1219  * Emits code for function end
1220  */
1221 static void sparc_emit_func_epilog(ir_graph *irg)
1222 {
1223         ir_entity *ent = get_irg_entity(irg);
1224         const char *irg_name = get_entity_ld_name(ent);
1225         be_emit_write_line();
1226         be_emit_irprintf("\t.size  %s, .-%s\n", irg_name, irg_name);
1227         be_emit_cstring("# -- End ");
1228         be_emit_string(irg_name);
1229         be_emit_cstring("\n");
1230         be_emit_write_line();
1231 }
1232
1233 static void sparc_gen_labels(ir_node *block, void *env)
1234 {
1235         ir_node *pred;
1236         int n = get_Block_n_cfgpreds(block);
1237         (void) env;
1238
1239         for (n--; n >= 0; n--) {
1240                 pred = get_Block_cfgpred(block, n);
1241                 set_irn_link(pred, block); // link the pred of a block (which is a jmp)
1242         }
1243 }
1244
1245 void sparc_emit_routine(ir_graph *irg)
1246 {
1247         ir_entity  *entity = get_irg_entity(irg);
1248         ir_node   **block_schedule;
1249         size_t      i;
1250         size_t      n;
1251
1252         heights = heights_new(irg);
1253
1254         /* register all emitter functions */
1255         sparc_register_emitters();
1256         be_dbg_method_begin(entity);
1257
1258         /* create the block schedule. For now, we don't need it earlier. */
1259         block_schedule = be_create_block_schedule(irg);
1260
1261         sparc_emit_func_prolog(irg);
1262         irg_block_walk_graph(irg, sparc_gen_labels, NULL, NULL);
1263
1264         /* inject block scheduling links & emit code of each block */
1265         n = ARR_LEN(block_schedule);
1266         for (i = 0; i < n; ++i) {
1267                 ir_node *block      = block_schedule[i];
1268                 ir_node *next_block = i+1 < n ? block_schedule[i+1] : NULL;
1269                 set_irn_link(block, next_block);
1270         }
1271
1272         for (i = 0; i < n; ++i) {
1273                 ir_node *block = block_schedule[i];
1274                 ir_node *prev  = i>=1 ? block_schedule[i-1] : NULL;
1275                 if (block == get_irg_end_block(irg))
1276                         continue;
1277                 sparc_emit_block(block, prev);
1278         }
1279
1280         /* emit function epilog */
1281         sparc_emit_func_epilog(irg);
1282
1283         heights_free(heights);
1284 }
1285
1286 void sparc_init_emitter(void)
1287 {
1288         FIRM_DBG_REGISTER(dbg, "firm.be.sparc.emit");
1289 }