remove unused vars
[libfirm] / ir / be / arm / bearch_arm.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   The main arm backend driver file.
23  * @author  Matthias Braun, Oliver Richter, Tobias Gneist
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include "lc_opts.h"
29 #include "lc_opts_enum.h"
30
31 #include "pseudo_irg.h"
32 #include "irgwalk.h"
33 #include "irprog.h"
34 #include "irprintf.h"
35 #include "ircons.h"
36 #include "irgmod.h"
37 #include "irgopt.h"
38 #include "iroptimize.h"
39 #include "lowering.h"
40 #include "error.h"
41
42 #include "bitset.h"
43 #include "debug.h"
44 #include "array_t.h"
45 #include "irtools.h"
46
47 #include "../bearch.h"
48 #include "../benode.h"
49 #include "../belower.h"
50 #include "../besched.h"
51 #include "be.h"
52 #include "../beabi.h"
53 #include "../bemachine.h"
54 #include "../beilpsched.h"
55 #include "../bemodule.h"
56 #include "../beirg.h"
57 #include "../bespillslots.h"
58 #include "../begnuas.h"
59 #include "../belistsched.h"
60 #include "../beflags.h"
61
62 #include "bearch_arm_t.h"
63
64 #include "arm_new_nodes.h"
65 #include "gen_arm_regalloc_if.h"
66 #include "arm_transform.h"
67 #include "arm_optimize.h"
68 #include "arm_emitter.h"
69 #include "arm_map_regs.h"
70
71 static arch_irn_class_t arm_classify(const ir_node *irn)
72 {
73         (void) irn;
74         return 0;
75 }
76
77 static ir_entity *arm_get_frame_entity(const ir_node *irn)
78 {
79         const arm_attr_t *attr = get_arm_attr_const(irn);
80
81         if (is_arm_FrameAddr(irn)) {
82                 const arm_SymConst_attr_t *attr = get_irn_generic_attr_const(irn);
83                 return attr->entity;
84         }
85         if (attr->is_load_store) {
86                 const arm_load_store_attr_t *load_store_attr
87                         = get_arm_load_store_attr_const(irn);
88                 if (load_store_attr->is_frame_entity) {
89                         return load_store_attr->entity;
90                 }
91         }
92         return NULL;
93 }
94
95 static void arm_set_frame_entity(ir_node *irn, ir_entity *ent)
96 {
97         (void) irn;
98         (void) ent;
99         panic("arm_set_frame_entity() called. This should not happen.");
100 }
101
102 /**
103  * This function is called by the generic backend to correct offsets for
104  * nodes accessing the stack.
105  */
106 static void arm_set_stack_bias(ir_node *irn, int bias)
107 {
108         if (is_arm_FrameAddr(irn)) {
109                 arm_SymConst_attr_t *attr = get_irn_generic_attr(irn);
110                 attr->fp_offset += bias;
111         } else {
112                 arm_load_store_attr_t *attr = get_arm_load_store_attr(irn);
113                 assert(attr->base.is_load_store);
114                 attr->offset += bias;
115         }
116 }
117
118 static int arm_get_sp_bias(const ir_node *irn)
119 {
120         /* We don't have any nodes changing the stack pointer.
121                 TODO: we probably want to support post-/pre increment/decrement later */
122         (void) irn;
123         return 0;
124 }
125
126 /* fill register allocator interface */
127
128 static const arch_irn_ops_t arm_irn_ops = {
129         get_arm_in_req,
130         arm_classify,
131         arm_get_frame_entity,
132         arm_set_frame_entity,
133         arm_set_stack_bias,
134         arm_get_sp_bias,
135         NULL,    /* get_inverse             */
136         NULL,    /* get_op_estimated_cost   */
137         NULL,    /* possible_memory_operand */
138         NULL,    /* perform_memory_operand  */
139 };
140
141 /**
142  * Transforms the standard Firm graph into
143  * a ARM firm graph.
144  */
145 static void arm_prepare_graph(void *self)
146 {
147         arm_code_gen_t *cg = self;
148
149         /* transform nodes into assembler instructions */
150         arm_transform_graph(cg);
151
152         /* do local optimizations (mainly CSE) */
153         local_optimize_graph(cg->irg);
154
155         if (cg->dump)
156                 be_dump(cg->irg, "-transformed", dump_ir_block_graph_sched);
157
158         /* do code placement, to optimize the position of constants */
159         place_code(cg->irg);
160
161         if (cg->dump)
162                 be_dump(cg->irg, "-place", dump_ir_block_graph_sched);
163 }
164
165 /**
166  * Called immediately before emit phase.
167  */
168 static void arm_finish_irg(void *self)
169 {
170         arm_code_gen_t *cg = self;
171
172         /* do peephole optimizations and fix stack offsets */
173         arm_peephole_optimization(cg);
174 }
175
176 static ir_node *arm_flags_remat(ir_node *node, ir_node *after)
177 {
178         ir_node *block;
179         ir_node *copy;
180
181         if (is_Block(after)) {
182                 block = after;
183         } else {
184                 block = get_nodes_block(after);
185         }
186         copy = exact_copy(node);
187         set_nodes_block(copy, block);
188         sched_add_after(after, copy);
189         return copy;
190 }
191
192 static void arm_before_ra(void *self)
193 {
194         arm_code_gen_t *cg = self;
195
196         be_sched_fix_flags(cg->birg, &arm_reg_classes[CLASS_arm_flags],
197                            &arm_flags_remat);
198 }
199
200 static void transform_Reload(ir_node *node)
201 {
202         ir_graph  *irg    = get_irn_irg(node);
203         ir_node   *block  = get_nodes_block(node);
204         dbg_info  *dbgi   = get_irn_dbg_info(node);
205         ir_node   *ptr    = get_irg_frame(irg);
206         ir_node   *mem    = get_irn_n(node, be_pos_Reload_mem);
207         ir_mode   *mode   = get_irn_mode(node);
208         ir_entity *entity = be_get_frame_entity(node);
209         const arch_register_t *reg;
210         ir_node   *proj;
211         ir_node   *load;
212
213         ir_node  *sched_point = sched_prev(node);
214
215         load = new_bd_arm_Ldr(dbgi, block, ptr, mem, mode, entity, false, 0, true);
216         sched_add_after(sched_point, load);
217         sched_remove(node);
218
219         proj = new_rd_Proj(dbgi, load, mode, pn_arm_Ldr_res);
220
221         reg = arch_get_irn_register(node);
222         arch_set_irn_register(proj, reg);
223
224         exchange(node, proj);
225 }
226
227 static void transform_Spill(ir_node *node)
228 {
229         ir_graph  *irg    = get_irn_irg(node);
230         ir_node   *block  = get_nodes_block(node);
231         dbg_info  *dbgi   = get_irn_dbg_info(node);
232         ir_node   *ptr    = get_irg_frame(irg);
233         ir_node   *mem    = new_NoMem();
234         ir_node   *val    = get_irn_n(node, be_pos_Spill_val);
235         ir_mode   *mode   = get_irn_mode(val);
236         ir_entity *entity = be_get_frame_entity(node);
237         ir_node   *sched_point;
238         ir_node   *store;
239
240         sched_point = sched_prev(node);
241         store = new_bd_arm_Str(dbgi, block, ptr, val, mem, mode, entity, false, 0,
242                                true);
243
244         sched_remove(node);
245         sched_add_after(sched_point, store);
246
247         exchange(node, store);
248 }
249
250 static void arm_after_ra_walker(ir_node *block, void *data)
251 {
252         ir_node *node, *prev;
253         (void) data;
254
255         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
256                 prev = sched_prev(node);
257
258                 if (be_is_Reload(node)) {
259                         transform_Reload(node);
260                 } else if (be_is_Spill(node)) {
261                         transform_Spill(node);
262                 }
263         }
264 }
265
266 static void arm_after_ra(void *self)
267 {
268         arm_code_gen_t *cg = self;
269         be_coalesce_spillslots(cg->birg);
270
271         irg_block_walk_graph(cg->irg, NULL, arm_after_ra_walker, NULL);
272 }
273
274 /**
275  * Emits the code, closes the output file and frees
276  * the code generator interface.
277  */
278 static void arm_emit_and_done(void *self)
279 {
280         arm_code_gen_t *cg = self;
281         ir_graph       *irg = cg->irg;
282
283         arm_gen_routine(cg, irg);
284
285         /* de-allocate code generator */
286         del_set(cg->reg_set);
287         free(self);
288 }
289
290 /**
291  * Move a double floating point value into an integer register.
292  * Place the move operation into block bl.
293  *
294  * Handle some special cases here:
295  * 1.) A constant: simply split into two
296  * 2.) A load: simply split into two
297  */
298 static ir_node *convert_dbl_to_int(ir_node *bl, ir_node *arg, ir_node *mem,
299                                    ir_node **resH, ir_node **resL)
300 {
301         if (is_Const(arg)) {
302                 tarval *tv = get_Const_tarval(arg);
303                 unsigned v;
304
305                 /* get the upper 32 bits */
306                 v =            get_tarval_sub_bits(tv, 7);
307                 v = (v << 8) | get_tarval_sub_bits(tv, 6);
308                 v = (v << 8) | get_tarval_sub_bits(tv, 5);
309                 v = (v << 8) | get_tarval_sub_bits(tv, 4);
310                 *resH = new_Const_long(mode_Is, v);
311
312                 /* get the lower 32 bits */
313                 v =            get_tarval_sub_bits(tv, 3);
314                 v = (v << 8) | get_tarval_sub_bits(tv, 2);
315                 v = (v << 8) | get_tarval_sub_bits(tv, 1);
316                 v = (v << 8) | get_tarval_sub_bits(tv, 0);
317                 *resL = new_Const_long(mode_Is, v);
318         } else if (is_Load(skip_Proj(arg))) {
319                 /* FIXME: handling of low/high depends on LE/BE here */
320                 panic("Unimplemented convert_dbl_to_int() case");
321         }
322         else {
323                 ir_node *conv;
324
325                 conv = new_bd_arm_fpaDbl2GP(NULL, bl, arg, mem);
326                 /* move high/low */
327                 *resL = new_r_Proj(conv, mode_Is, pn_arm_fpaDbl2GP_low);
328                 *resH = new_r_Proj(conv, mode_Is, pn_arm_fpaDbl2GP_high);
329                 mem   = new_r_Proj(conv, mode_M,  pn_arm_fpaDbl2GP_M);
330         }
331         return mem;
332 }
333
334 /**
335  * Move a single floating point value into an integer register.
336  * Place the move operation into block bl.
337  *
338  * Handle some special cases here:
339  * 1.) A constant: simply move
340  * 2.) A load: simply load
341  */
342 static ir_node *convert_sng_to_int(ir_node *bl, ir_node *arg)
343 {
344         (void) bl;
345
346         if (is_Const(arg)) {
347                 tarval *tv = get_Const_tarval(arg);
348                 unsigned v;
349
350                 /* get the lower 32 bits */
351                 v =            get_tarval_sub_bits(tv, 3);
352                 v = (v << 8) | get_tarval_sub_bits(tv, 2);
353                 v = (v << 8) | get_tarval_sub_bits(tv, 1);
354                 v = (v << 8) | get_tarval_sub_bits(tv, 0);
355                 return new_Const_long(mode_Is, v);
356         } else if (is_Load(skip_Proj(arg))) {
357                 ir_node *load;
358
359                 load = skip_Proj(arg);
360         }
361         panic("Unimplemented convert_sng_to_int() case");
362 }
363
364 /**
365  * Convert the arguments of a call to support the
366  * ARM calling convention of general purpose AND floating
367  * point arguments.
368  */
369 static void handle_calls(ir_node *call, void *env)
370 {
371         arm_code_gen_t *cg = env;
372         int i, j, n, size, idx, flag, n_param, n_res, first_variadic;
373         ir_type *mtp, *new_mtd, *new_tp[5];
374         ir_node *new_in[5], **in;
375         ir_node *bl;
376
377         if (! is_Call(call))
378                 return;
379
380         /* check, if we need conversions */
381         n = get_Call_n_params(call);
382         mtp = get_Call_type(call);
383         assert(get_method_n_params(mtp) == n);
384
385         /* it's always enough to handle the first 4 parameters */
386         if (n > 4)
387                 n = 4;
388         flag = size = idx = 0;
389         bl = get_nodes_block(call);
390         for (i = 0; i < n; ++i) {
391                 ir_type *param_tp = get_method_param_type(mtp, i);
392
393                 if (is_compound_type(param_tp)) {
394                         /* an aggregate parameter: bad case */
395                         assert(0);
396                 }
397                 else {
398                         /* a primitive parameter */
399                         ir_mode *mode = get_type_mode(param_tp);
400
401                         if (mode_is_float(mode)) {
402                                 if (get_mode_size_bits(mode) > 32) {
403                                         ir_node *mem = get_Call_mem(call);
404
405                                         /* Beware: ARM wants the high part first */
406                                         size += 2 * 4;
407                                         new_tp[idx]   = cg->int_tp;
408                                         new_tp[idx+1] = cg->int_tp;
409                                         mem = convert_dbl_to_int(bl, get_Call_param(call, i), mem, &new_in[idx], &new_in[idx+1]);
410                                         idx += 2;
411                                         set_Call_mem(call, mem);
412                                 }
413                                 else {
414                                         size += 4;
415                                         new_tp[idx] = cg->int_tp;
416                                         new_in[idx] = convert_sng_to_int(bl, get_Call_param(call, i));
417                                         ++idx;
418                                 }
419                                 flag = 1;
420                         }
421                         else {
422                                 size += 4;
423                                 new_tp[idx] = param_tp;
424                                 new_in[idx] = get_Call_param(call, i);
425                                 ++idx;
426                         }
427                 }
428
429                 if (size >= 16)
430                         break;
431         }
432
433         /* if flag is NOT set, no need to translate the method type */
434         if (! flag)
435                 return;
436
437         /* construct a new method type */
438         n       = i;
439         n_param = get_method_n_params(mtp) - n + idx;
440         n_res   = get_method_n_ress(mtp);
441         new_mtd = new_d_type_method(n_param, n_res, get_type_dbg_info(mtp));
442
443         for (i = 0; i < idx; ++i)
444                 set_method_param_type(new_mtd, i, new_tp[i]);
445         for (i = n, j = idx; i < get_method_n_params(mtp); ++i)
446                 set_method_param_type(new_mtd, j++, get_method_param_type(mtp, i));
447         for (i = 0; i < n_res; ++i)
448                 set_method_res_type(new_mtd, i, get_method_res_type(mtp, i));
449
450         set_method_calling_convention(new_mtd, get_method_calling_convention(mtp));
451         first_variadic = get_method_first_variadic_param_index(mtp);
452         if (first_variadic >= 0)
453                 set_method_first_variadic_param_index(new_mtd, first_variadic);
454
455         if (is_lowered_type(mtp)) {
456                 mtp = get_associated_type(mtp);
457         }
458         set_lowered_type(mtp, new_mtd);
459
460         set_Call_type(call, new_mtd);
461
462         /* calculate new in array of the Call */
463         NEW_ARR_A(ir_node *, in, n_param + 2);
464         for (i = 0; i < idx; ++i)
465                 in[2 + i] = new_in[i];
466         for (i = n, j = idx; i < get_method_n_params(mtp); ++i)
467                 in[2 + j++] = get_Call_param(call, i);
468
469         in[0] = get_Call_mem(call);
470         in[1] = get_Call_ptr(call);
471
472         /* finally, change the call inputs */
473         set_irn_in(call, n_param + 2, in);
474 }
475
476 /**
477  * Handle graph transformations before the abi converter does its work.
478  */
479 static void arm_before_abi(void *self)
480 {
481         arm_code_gen_t *cg = self;
482
483         irg_walk_graph(cg->irg, NULL, handle_calls, cg);
484 }
485
486 /* forward */
487 static void *arm_cg_init(be_irg_t *birg);
488
489 static const arch_code_generator_if_t arm_code_gen_if = {
490         arm_cg_init,
491         NULL,               /* get_pic_base */
492         arm_before_abi,     /* before abi introduce */
493         arm_prepare_graph,
494         NULL,               /* spill */
495         arm_before_ra,      /* before register allocation hook */
496         arm_after_ra,
497         arm_finish_irg,
498         arm_emit_and_done,
499 };
500
501 /**
502  * Initializes the code generator.
503  */
504 static void *arm_cg_init(be_irg_t *birg)
505 {
506         static ir_type *int_tp = NULL;
507         arm_isa_t      *isa = (arm_isa_t *)birg->main_env->arch_env;
508         arm_code_gen_t *cg;
509
510         if (! int_tp) {
511                 /* create an integer type with machine size */
512                 int_tp = new_type_primitive(mode_Is);
513         }
514
515         cg = XMALLOC(arm_code_gen_t);
516         cg->impl         = &arm_code_gen_if;
517         cg->irg          = birg->irg;
518         cg->reg_set      = new_set(arm_cmp_irn_reg_assoc, 1024);
519         cg->isa          = isa;
520         cg->birg         = birg;
521         cg->int_tp       = int_tp;
522         cg->have_fp_insn = 0;
523         cg->dump         = (birg->main_env->options->dump_flags & DUMP_BE) ? 1 : 0;
524
525         FIRM_DBG_REGISTER(cg->mod, "firm.be.arm.cg");
526
527         /* enter the current code generator */
528         isa->cg = cg;
529
530         return (arch_code_generator_t *)cg;
531 }
532
533
534 /**
535  * Maps all intrinsic calls that the backend support
536  * and map all instructions the backend did not support
537  * to runtime calls.
538  */
539 static void arm_handle_intrinsics(void)
540 {
541         ir_type *tp, *int_tp, *uint_tp;
542         i_record records[8];
543         int n_records = 0;
544
545         runtime_rt rt_iDiv, rt_uDiv, rt_iMod, rt_uMod;
546
547 #define ID(x) new_id_from_chars(x, sizeof(x)-1)
548
549         int_tp  = new_type_primitive(mode_Is);
550         uint_tp = new_type_primitive(mode_Iu);
551
552         /* ARM has neither a signed div instruction ... */
553         {
554                 i_instr_record *map_Div = &records[n_records++].i_instr;
555
556                 tp = new_type_method(2, 1);
557                 set_method_param_type(tp, 0, int_tp);
558                 set_method_param_type(tp, 1, int_tp);
559                 set_method_res_type(tp, 0, int_tp);
560
561                 rt_iDiv.ent             = new_entity(get_glob_type(), ID("__divsi3"), tp);
562                 set_entity_ld_ident(rt_iDiv.ent, ID("__divsi3"));
563                 rt_iDiv.mode            = mode_T;
564                 rt_iDiv.res_mode        = mode_Is;
565                 rt_iDiv.mem_proj_nr     = pn_Div_M;
566                 rt_iDiv.regular_proj_nr = pn_Div_X_regular;
567                 rt_iDiv.exc_proj_nr     = pn_Div_X_except;
568                 rt_iDiv.exc_mem_proj_nr = pn_Div_M;
569                 rt_iDiv.res_proj_nr     = pn_Div_res;
570
571                 add_entity_linkage(rt_iDiv.ent, IR_LINKAGE_CONSTANT);
572                 set_entity_visibility(rt_iDiv.ent, ir_visibility_external);
573
574                 map_Div->kind     = INTRINSIC_INSTR;
575                 map_Div->op       = op_Div;
576                 map_Div->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
577                 map_Div->ctx      = &rt_iDiv;
578         }
579         /* ... nor an unsigned div instruction ... */
580         {
581                 i_instr_record *map_Div = &records[n_records++].i_instr;
582
583                 tp = new_type_method(2, 1);
584                 set_method_param_type(tp, 0, uint_tp);
585                 set_method_param_type(tp, 1, uint_tp);
586                 set_method_res_type(tp, 0, uint_tp);
587
588                 rt_uDiv.ent             = new_entity(get_glob_type(), ID("__udivsi3"), tp);
589                 set_entity_ld_ident(rt_uDiv.ent, ID("__udivsi3"));
590                 rt_uDiv.mode            = mode_T;
591                 rt_uDiv.res_mode        = mode_Iu;
592                 rt_uDiv.mem_proj_nr     = pn_Div_M;
593                 rt_uDiv.regular_proj_nr = pn_Div_X_regular;
594                 rt_uDiv.exc_proj_nr     = pn_Div_X_except;
595                 rt_uDiv.exc_mem_proj_nr = pn_Div_M;
596                 rt_uDiv.res_proj_nr     = pn_Div_res;
597
598                 set_entity_visibility(rt_uDiv.ent, ir_visibility_external);
599
600                 map_Div->kind     = INTRINSIC_INSTR;
601                 map_Div->op       = op_Div;
602                 map_Div->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
603                 map_Div->ctx      = &rt_uDiv;
604         }
605         /* ... nor a signed mod instruction ... */
606         {
607                 i_instr_record *map_Mod = &records[n_records++].i_instr;
608
609                 tp = new_type_method(2, 1);
610                 set_method_param_type(tp, 0, int_tp);
611                 set_method_param_type(tp, 1, int_tp);
612                 set_method_res_type(tp, 0, int_tp);
613
614                 rt_iMod.ent             = new_entity(get_glob_type(), ID("__modsi3"), tp);
615                 set_entity_ld_ident(rt_iMod.ent, ID("__modsi3"));
616                 rt_iMod.mode            = mode_T;
617                 rt_iMod.res_mode        = mode_Is;
618                 rt_iMod.mem_proj_nr     = pn_Mod_M;
619                 rt_iMod.regular_proj_nr = pn_Mod_X_regular;
620                 rt_iMod.exc_proj_nr     = pn_Mod_X_except;
621                 rt_iMod.exc_mem_proj_nr = pn_Mod_M;
622                 rt_iMod.res_proj_nr     = pn_Mod_res;
623
624                 set_entity_visibility(rt_iMod.ent, ir_visibility_external);
625
626                 map_Mod->kind     = INTRINSIC_INSTR;
627                 map_Mod->op       = op_Mod;
628                 map_Mod->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
629                 map_Mod->ctx      = &rt_iMod;
630         }
631         /* ... nor an unsigned mod. */
632         {
633                 i_instr_record *map_Mod = &records[n_records++].i_instr;
634
635                 tp = new_type_method(2, 1);
636                 set_method_param_type(tp, 0, uint_tp);
637                 set_method_param_type(tp, 1, uint_tp);
638                 set_method_res_type(tp, 0, uint_tp);
639
640                 rt_uMod.ent             = new_entity(get_glob_type(), ID("__umodsi3"), tp);
641                 set_entity_ld_ident(rt_uMod.ent, ID("__umodsi3"));
642                 rt_uMod.mode            = mode_T;
643                 rt_uMod.res_mode        = mode_Iu;
644                 rt_uMod.mem_proj_nr     = pn_Mod_M;
645                 rt_uMod.regular_proj_nr = pn_Mod_X_regular;
646                 rt_uMod.exc_proj_nr     = pn_Mod_X_except;
647                 rt_uMod.exc_mem_proj_nr = pn_Mod_M;
648                 rt_uMod.res_proj_nr     = pn_Mod_res;
649
650                 set_entity_visibility(rt_uMod.ent, ir_visibility_external);
651
652                 map_Mod->kind     = INTRINSIC_INSTR;
653                 map_Mod->op       = op_Mod;
654                 map_Mod->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
655                 map_Mod->ctx      = &rt_uMod;
656         }
657
658         if (n_records > 0)
659                 lower_intrinsics(records, n_records, /*part_block_used=*/0);
660 }
661
662 /*****************************************************************
663  *  ____             _                  _   _____  _____
664  * |  _ \           | |                | | |_   _|/ ____|  /\
665  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
666  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
667  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
668  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
669  *
670  *****************************************************************/
671
672 static arm_isa_t arm_isa_template = {
673         {
674                 &arm_isa_if,           /* isa interface */
675                 &arm_gp_regs[REG_SP],  /* stack pointer */
676                 &arm_gp_regs[REG_R11], /* base pointer */
677                 &arm_reg_classes[CLASS_arm_gp],  /* static link pointer class */
678                 -1,                    /* stack direction */
679                 2,                     /* power of two stack alignment for calls, 2^2 == 4 */
680                 NULL,                  /* main environment */
681                 7,                     /* spill costs */
682                 5,                     /* reload costs */
683         },
684         0,                     /* use generic register names instead of SP, LR, PC */
685         ARM_FPU_ARCH_FPE,      /* FPU architecture */
686         NULL,                  /* current code generator */
687 };
688
689 /**
690  * Initializes the backend ISA and opens the output file.
691  */
692 static arch_env_t *arm_init(FILE *file_handle)
693 {
694         static int inited = 0;
695         arm_isa_t *isa;
696
697         if (inited)
698                 return NULL;
699
700         isa = XMALLOC(arm_isa_t);
701         memcpy(isa, &arm_isa_template, sizeof(*isa));
702
703         arm_register_init();
704
705         isa->cg  = NULL;
706         be_emit_init(file_handle);
707
708         arm_create_opcodes(&arm_irn_ops);
709         arm_handle_intrinsics();
710
711         be_gas_emit_types = false;
712
713         /* needed for the debug support */
714         be_gas_emit_switch_section(GAS_SECTION_TEXT);
715         be_emit_irprintf("%stext0:\n", be_gas_get_private_prefix());
716         be_emit_write_line();
717
718         inited = 1;
719         return &isa->arch_env;
720 }
721
722
723
724 /**
725  * Closes the output file and frees the ISA structure.
726  */
727 static void arm_done(void *self)
728 {
729         arm_isa_t *isa = self;
730
731         be_gas_emit_decls(isa->arch_env.main_env);
732
733         be_emit_exit();
734         free(self);
735 }
736
737
738 /**
739  * Report the number of register classes.
740  * If we don't have fp instructions, report only GP
741  * here to speed up register allocation (and makes dumps
742  * smaller and more readable).
743  */
744 static unsigned arm_get_n_reg_class(void)
745 {
746         return N_CLASSES;
747 }
748
749 /**
750  * Return the register class with requested index.
751  */
752 static const arch_register_class_t *arm_get_reg_class(unsigned i)
753 {
754         assert(i < N_CLASSES);
755         return &arm_reg_classes[i];
756 }
757
758 /**
759  * Get the register class which shall be used to store a value of a given mode.
760  * @param self The this pointer.
761  * @param mode The mode in question.
762  * @return A register class which can hold values of the given mode.
763  */
764 static const arch_register_class_t *arm_get_reg_class_for_mode(const ir_mode *mode)
765 {
766         if (mode_is_float(mode))
767                 return &arm_reg_classes[CLASS_arm_fpa];
768         else
769                 return &arm_reg_classes[CLASS_arm_gp];
770 }
771
772 /**
773  * Produces the type which sits between the stack args and the locals on the stack.
774  * it will contain the return address and space to store the old base pointer.
775  * @return The Firm type modeling the ABI between type.
776  */
777 static ir_type *arm_get_between_type(void *self)
778 {
779         static ir_type *between_type = NULL;
780         (void) self;
781
782         if (between_type == NULL) {
783                 between_type = new_type_class(new_id_from_str("arm_between_type"));
784                 set_type_size_bytes(between_type, 0);
785         }
786
787         return between_type;
788 }
789
790
791 typedef struct {
792         be_abi_call_flags_bits_t flags;
793         const arch_env_t *arch_env;
794         ir_graph *irg;
795 } arm_abi_env_t;
796
797 static void *arm_abi_init(const be_abi_call_t *call, const arch_env_t *arch_env, ir_graph *irg)
798 {
799         arm_abi_env_t       *env = XMALLOC(arm_abi_env_t);
800         be_abi_call_flags_t  fl  = be_abi_call_get_flags(call);
801         env->flags    = fl.bits;
802         env->irg      = irg;
803         env->arch_env = arch_env;
804         return env;
805 }
806
807 /**
808  * Generate the routine prologue.
809  *
810  * @param self       The callback object.
811  * @param mem        A pointer to the mem node. Update this if you define new memory.
812  * @param reg_map    A map mapping all callee_save/ignore/parameter registers to their defining nodes.
813  * @param stack_bias Points to the current stack bias, can be modified if needed.
814  *
815  * @return        The register which shall be used as a stack frame base.
816  *
817  * All nodes which define registers in @p reg_map must keep @p reg_map current.
818  */
819 static const arch_register_t *arm_abi_prologue(void *self, ir_node **mem, pmap *reg_map, int *stack_bias)
820 {
821         arm_abi_env_t         *env = self;
822         ir_node               *store;
823         ir_graph              *irg;
824         ir_node               *block;
825         arch_register_class_t *gp;
826
827         ir_node               *fp, *ip, *lr, *pc;
828         ir_node               *sp = be_abi_reg_map_get(reg_map, env->arch_env->sp);
829
830         (void) stack_bias;
831
832         if (env->flags.try_omit_fp)
833                 return env->arch_env->sp;
834
835         fp = be_abi_reg_map_get(reg_map, env->arch_env->bp);
836         ip = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_R12]);
837         lr = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_LR]);
838         pc = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_PC]);
839
840         gp    = &arm_reg_classes[CLASS_arm_gp];
841         irg   = env->irg;
842         block = get_irg_start_block(irg);
843
844         /* mark bp register as ignore */
845         be_set_constr_single_reg_out(get_Proj_pred(fp),
846                                      get_Proj_proj(fp), env->arch_env->bp,
847                                      arch_register_req_type_ignore);
848
849         /* copy SP to IP (so we can spill it */
850         ip = be_new_Copy(gp, block, sp);
851         be_set_constr_single_reg_out(ip, 0, &arm_gp_regs[REG_R12], 0);
852
853         /* spill stuff */
854         store = new_bd_arm_StoreStackM4Inc(NULL, block, sp, fp, ip, lr, pc, *mem);
855
856         sp = new_r_Proj(store, env->arch_env->sp->reg_class->mode, pn_arm_StoreStackM4Inc_ptr);
857         arch_set_irn_register(sp, env->arch_env->sp);
858         *mem = new_r_Proj(store, mode_M, pn_arm_StoreStackM4Inc_M);
859
860         /* frame pointer is ip-4 (because ip is our old sp value) */
861         fp = new_bd_arm_Sub_imm(NULL, block, ip, 4, 0);
862         arch_set_irn_register(fp, env->arch_env->bp);
863
864         /* beware: we change the fp but the StoreStackM4Inc above wants the old
865          * fp value. We are not allowed to spill or anything in the prolog, so we
866          * have to enforce some order here. (scheduler/regalloc are too stupid
867          * to extract this order from register requirements) */
868         add_irn_dep(fp, store);
869
870         fp = be_new_Copy(gp, block, fp); // XXX Gammelfix: only be_ have custom register requirements
871         be_set_constr_single_reg_out(fp, 0, env->arch_env->bp,
872                                      arch_register_req_type_ignore);
873         arch_set_irn_register(fp, env->arch_env->bp);
874
875         be_abi_reg_map_set(reg_map, env->arch_env->bp, fp);
876         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_R12], ip);
877         be_abi_reg_map_set(reg_map, env->arch_env->sp, sp);
878         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_LR], lr);
879         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_PC], pc);
880
881         return env->arch_env->bp;
882 }
883
884 /**
885  * Builds the ARM epilogue
886  */
887 static void arm_abi_epilogue(void *self, ir_node *bl, ir_node **mem, pmap *reg_map)
888 {
889         arm_abi_env_t *env = self;
890         ir_node *curr_sp = be_abi_reg_map_get(reg_map, env->arch_env->sp);
891         ir_node *curr_bp = be_abi_reg_map_get(reg_map, env->arch_env->bp);
892         ir_node *curr_pc = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_PC]);
893         ir_node *curr_lr = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_LR]);
894
895         // TODO: Activate Omit fp in epilogue
896         if (env->flags.try_omit_fp) {
897                 ir_node *incsp = be_new_IncSP(env->arch_env->sp, bl, curr_sp, BE_STACK_FRAME_SIZE_SHRINK, 0);
898                 curr_sp = incsp;
899         } else {
900                 ir_node *load_node;
901
902                 load_node = new_bd_arm_LoadStackM3Epilogue(NULL, bl, curr_bp, *mem);
903
904                 curr_bp = new_r_Proj(load_node, env->arch_env->bp->reg_class->mode, pn_arm_LoadStackM3Epilogue_res0);
905                 curr_sp = new_r_Proj(load_node, env->arch_env->sp->reg_class->mode, pn_arm_LoadStackM3Epilogue_res1);
906                 curr_pc = new_r_Proj(load_node, mode_Iu, pn_arm_LoadStackM3Epilogue_res2);
907                 *mem    = new_r_Proj(load_node, mode_M, pn_arm_LoadStackM3Epilogue_M);
908                 arch_set_irn_register(curr_bp, env->arch_env->bp);
909                 arch_set_irn_register(curr_sp, env->arch_env->sp);
910                 arch_set_irn_register(curr_pc, &arm_gp_regs[REG_PC]);
911         }
912         be_abi_reg_map_set(reg_map, env->arch_env->sp, curr_sp);
913         be_abi_reg_map_set(reg_map, env->arch_env->bp, curr_bp);
914         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_LR], curr_lr);
915         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_PC], curr_pc);
916 }
917
918 static const be_abi_callbacks_t arm_abi_callbacks = {
919         arm_abi_init,
920         free,
921         arm_get_between_type,
922         arm_abi_prologue,
923         arm_abi_epilogue,
924 };
925
926
927 /**
928  * Get the ABI restrictions for procedure calls.
929  * @param self        The this pointer.
930  * @param method_type The type of the method (procedure) in question.
931  * @param abi         The abi object to be modified
932  */
933 static void arm_get_call_abi(const void *self, ir_type *method_type, be_abi_call_t *abi)
934 {
935         ir_type  *tp;
936         ir_mode  *mode;
937         int       i;
938         int       n = get_method_n_params(method_type);
939         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
940         (void) self;
941
942         /* set abi flags for calls */
943         call_flags.bits.left_to_right         = 0;
944         call_flags.bits.store_args_sequential = 0;
945         /* call_flags.bits.try_omit_fp     don't change this we can handle both */
946         call_flags.bits.fp_free               = 0;
947         call_flags.bits.call_has_imm          = 1;  /* IA32 calls can have immediate address */
948
949         /* set stack parameter passing style */
950         be_abi_call_set_flags(abi, call_flags, &arm_abi_callbacks);
951
952         for (i = 0; i < n; i++) {
953                 /* reg = get reg for param i;          */
954                 /* be_abi_call_param_reg(abi, i, reg); */
955                 if (i < 4) {
956                         be_abi_call_param_reg(abi, i, arm_get_RegParam_reg(i));
957                 } else {
958                         tp   = get_method_param_type(method_type, i);
959                         mode = get_type_mode(tp);
960                         be_abi_call_param_stack(abi, i, mode, 4, 0, 0);
961                 }
962         }
963
964         /* set return registers */
965         n = get_method_n_ress(method_type);
966
967         assert(n <= 2 && "more than two results not supported");
968
969         /* In case of 64bit returns, we will have two 32bit values */
970         if (n == 2) {
971                 tp   = get_method_res_type(method_type, 0);
972                 mode = get_type_mode(tp);
973
974                 assert(!mode_is_float(mode) && "two FP results not supported");
975
976                 tp   = get_method_res_type(method_type, 1);
977                 mode = get_type_mode(tp);
978
979                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
980
981                 be_abi_call_res_reg(abi, 0, &arm_gp_regs[REG_R0]);
982                 be_abi_call_res_reg(abi, 1, &arm_gp_regs[REG_R1]);
983         } else if (n == 1) {
984                 const arch_register_t *reg;
985
986                 tp   = get_method_res_type(method_type, 0);
987                 assert(is_atomic_type(tp));
988                 mode = get_type_mode(tp);
989
990                 reg = mode_is_float(mode) ? &arm_fpa_regs[REG_F0] : &arm_gp_regs[REG_R0];
991                 be_abi_call_res_reg(abi, 0, reg);
992         }
993 }
994
995 static int arm_to_appear_in_schedule(void *block_env, const ir_node *irn)
996 {
997         (void) block_env;
998         if (!is_arm_irn(irn))
999                 return -1;
1000
1001         return 1;
1002 }
1003
1004 /**
1005  * Initializes the code generator interface.
1006  */
1007 static const arch_code_generator_if_t *arm_get_code_generator_if(void *self)
1008 {
1009         (void) self;
1010         return &arm_code_gen_if;
1011 }
1012
1013 list_sched_selector_t arm_sched_selector;
1014
1015 /**
1016  * Returns the reg_pressure scheduler with to_appear_in_schedule() over\loaded
1017  */
1018 static const list_sched_selector_t *arm_get_list_sched_selector(const void *self, list_sched_selector_t *selector)
1019 {
1020         (void) self;
1021         memcpy(&arm_sched_selector, selector, sizeof(arm_sched_selector));
1022         /* arm_sched_selector.exectime              = arm_sched_exectime; */
1023         arm_sched_selector.to_appear_in_schedule = arm_to_appear_in_schedule;
1024         return &arm_sched_selector;
1025
1026 }
1027
1028 static const ilp_sched_selector_t *arm_get_ilp_sched_selector(const void *self)
1029 {
1030         (void) self;
1031         return NULL;
1032 }
1033
1034 /**
1035  * Returns the necessary byte alignment for storing a register of given class.
1036  */
1037 static int arm_get_reg_class_alignment(const arch_register_class_t *cls)
1038 {
1039         (void) cls;
1040         /* ARM is a 32 bit CPU, no need for other alignment */
1041         return 4;
1042 }
1043
1044 static const be_execution_unit_t ***arm_get_allowed_execution_units(const ir_node *irn)
1045 {
1046         (void) irn;
1047         /* TODO */
1048         panic("Unimplemented arm_get_allowed_execution_units()");
1049 }
1050
1051 static const be_machine_t *arm_get_machine(const void *self)
1052 {
1053         (void) self;
1054         /* TODO */
1055         panic("Unimplemented arm_get_machine()");
1056 }
1057
1058 /**
1059  * Return irp irgs in the desired order.
1060  */
1061 static ir_graph **arm_get_irg_list(const void *self, ir_graph ***irg_list)
1062 {
1063         (void) self;
1064         (void) irg_list;
1065         return NULL;
1066 }
1067
1068 /**
1069  * Allows or disallows the creation of Psi nodes for the given Phi nodes.
1070  * @return 1 if allowed, 0 otherwise
1071  */
1072 static int arm_is_mux_allowed(ir_node *sel, ir_node *mux_false,
1073                               ir_node *mux_true)
1074 {
1075         (void) sel;
1076         (void) mux_false;
1077         (void) mux_true;
1078
1079         return 0;
1080 }
1081
1082 static asm_constraint_flags_t arm_parse_asm_constraint(const char **c)
1083 {
1084         /* asm not supported */
1085         (void) c;
1086         return ASM_CONSTRAINT_FLAG_INVALID;
1087 }
1088
1089 static int arm_is_valid_clobber(const char *clobber)
1090 {
1091         (void) clobber;
1092         return 0;
1093 }
1094
1095 /**
1096  * Returns the libFirm configuration parameter for this backend.
1097  */
1098 static const backend_params *arm_get_libfirm_params(void)
1099 {
1100         static const ir_settings_if_conv_t ifconv = {
1101                 4,                    /* maxdepth, doesn't matter for Psi-conversion */
1102                 arm_is_mux_allowed   /* allows or disallows Mux creation for given selector */
1103         };
1104         static ir_settings_arch_dep_t ad = {
1105                 1,    /* allow subs */
1106                 1,        /* Muls are fast enough on ARM but ... */
1107                 31,   /* ... one shift would be possible better */
1108                 NULL, /* no evaluator function */
1109                 0,    /* SMUL is needed, only in Arch M */
1110                 0,    /* UMUL is needed, only in Arch M */
1111                 32,   /* SMUL & UMUL available for 32 bit */
1112         };
1113         static backend_params p = {
1114                 1,     /* need dword lowering */
1115                 0,     /* don't support inline assembler yet */
1116                 NULL,  /* will be set later */
1117                 NULL,  /* but yet no creator function */
1118                 NULL,  /* context for create_intrinsic_fkt */
1119                 NULL,  /* ifconv_info will be set below */
1120                 NULL,  /* float arithmetic mode (TODO) */
1121                 0,     /* no trampoline support: size 0 */
1122                 0,     /* no trampoline support: align 0 */
1123                 NULL,  /* no trampoline support: no trampoline builder */
1124                 4      /* alignment of stack parameter */
1125         };
1126
1127         p.dep_param    = &ad;
1128         p.if_conv_info = &ifconv;
1129         return &p;
1130 }
1131
1132 /* fpu set architectures. */
1133 static const lc_opt_enum_int_items_t arm_fpu_items[] = {
1134         { "softfloat", ARM_FPU_ARCH_SOFTFLOAT },
1135         { "fpe",       ARM_FPU_ARCH_FPE },
1136         { "fpa",       ARM_FPU_ARCH_FPA },
1137         { "vfp1xd",    ARM_FPU_ARCH_VFP_V1xD },
1138         { "vfp1",      ARM_FPU_ARCH_VFP_V1 },
1139         { "vfp2",      ARM_FPU_ARCH_VFP_V2 },
1140         { NULL,        0 }
1141 };
1142
1143 static lc_opt_enum_int_var_t arch_fpu_var = {
1144         &arm_isa_template.fpu_arch, arm_fpu_items
1145 };
1146
1147 static const lc_opt_table_entry_t arm_options[] = {
1148         LC_OPT_ENT_ENUM_INT("fpunit",    "select the floating point unit", &arch_fpu_var),
1149         LC_OPT_ENT_BOOL("gen_reg_names", "use generic register names", &arm_isa_template.gen_reg_names),
1150         LC_OPT_LAST
1151 };
1152
1153 const arch_isa_if_t arm_isa_if = {
1154         arm_init,
1155         arm_done,
1156         NULL,  /* handle_intrinsics */
1157         arm_get_n_reg_class,
1158         arm_get_reg_class,
1159         arm_get_reg_class_for_mode,
1160         arm_get_call_abi,
1161         arm_get_code_generator_if,
1162         arm_get_list_sched_selector,
1163         arm_get_ilp_sched_selector,
1164         arm_get_reg_class_alignment,
1165         arm_get_libfirm_params,
1166         arm_get_allowed_execution_units,
1167         arm_get_machine,
1168         arm_get_irg_list,
1169         NULL,               /* mark remat */
1170         arm_parse_asm_constraint,
1171         arm_is_valid_clobber
1172 };
1173
1174 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_arm);
1175 void be_init_arch_arm(void)
1176 {
1177         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1178         lc_opt_entry_t *arm_grp = lc_opt_get_grp(be_grp, "arm");
1179
1180         lc_opt_add_table(arm_grp, arm_options);
1181
1182         be_register_isa_if("arm", &arm_isa_if);
1183
1184         arm_init_transform();
1185         arm_init_emitter();
1186 }