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