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