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