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