becopyilp: Do not advertise the switch to dump the solution, because this is not...
[libfirm] / ir / be / beabi.c
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5
6 /**
7  * @file
8  * @brief       Backend ABI implementation.
9  * @author      Sebastian Hack, Michael Beck
10  */
11 #include "config.h"
12
13 #include "obst.h"
14
15 #include "irgopt.h"
16
17 #include "irgraph_t.h"
18 #include "irnode_t.h"
19 #include "ircons_t.h"
20 #include "iredges_t.h"
21 #include "irgmod.h"
22 #include "irgwalk.h"
23 #include "irprintf.h"
24 #include "irgopt.h"
25 #include "iropt_t.h"
26 #include "irtools.h"
27 #include "heights.h"
28 #include "pdeq.h"
29 #include "util.h"
30 #include "raw_bitset.h"
31 #include "error.h"
32 #include "pset_new.h"
33
34 #include "be.h"
35 #include "beabi.h"
36 #include "beabihelper.h"
37 #include "bearch.h"
38 #include "benode.h"
39 #include "belive_t.h"
40 #include "besched.h"
41 #include "beirg.h"
42 #include "bessaconstr.h"
43 #include "bemodule.h"
44 #include "betranshlp.h"
45
46 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
47
48 typedef struct be_abi_call_arg_t {
49         unsigned is_res   : 1;  /**< 1: the call argument is a return value. 0: it's a call parameter. */
50         unsigned in_reg   : 1;  /**< 1: this argument is transmitted 1: in registers, 0: on stack. */
51         unsigned callee   : 1;  /**< 1: someone called us. 0: We call another function */
52
53         int                    pos;
54         const arch_register_t *reg;
55         ir_entity             *stack_ent;
56         ir_mode               *load_mode;
57         unsigned               alignment;    /**< stack alignment */
58         unsigned               space_before; /**< allocate space before */
59         unsigned               space_after;  /**< allocate space after */
60 } be_abi_call_arg_t;
61
62 struct be_abi_call_t {
63         be_abi_call_flags_t       flags;  /**< Flags describing the ABI behavior on calls */
64         int                       pop;    /**< number of bytes the stack frame is shrinked by the callee on return. */
65         const be_abi_callbacks_t *cb;
66         set                      *params;
67 };
68
69 /**
70  * The ABI information for the current graph.
71  */
72 struct be_abi_irg_t {
73         be_abi_call_t        *call;         /**< The ABI call information. */
74
75         ir_node              *init_sp;      /**< The node representing the stack pointer
76                                                  at the start of the function. */
77
78         pmap                 *regs;         /**< A map of all callee-save and ignore regs to
79                                                  their Projs to the RegParams node. */
80         pmap                 *keep_map;     /**< mapping blocks to keep nodes. */
81
82         ir_node              **calls;       /**< flexible array containing all be_Call nodes */
83 };
84
85 static ir_heights_t *ir_heights;
86
87 static ir_node *be_abi_reg_map_get(pmap *map, const arch_register_t *reg)
88 {
89         return pmap_get(ir_node, map, reg);
90 }
91
92 static void be_abi_reg_map_set(pmap *map, const arch_register_t* reg,
93                                ir_node *node)
94 {
95         pmap_insert(map, reg, node);
96 }
97
98 /**
99  * Check if the given register is callee save, i.e. will be saved by the callee.
100  */
101 static bool arch_register_is_callee_save(
102         const arch_env_t      *arch_env,
103         const arch_register_t *reg)
104 {
105         if (arch_env->impl->register_saved_by)
106                 return arch_env->impl->register_saved_by(reg, /*callee=*/1);
107         return false;
108 }
109
110 /**
111  * Check if the given register is caller save, i.e. must be saved by the caller.
112  */
113 static bool arch_register_is_caller_save(
114         const arch_env_t      *arch_env,
115         const arch_register_t *reg)
116 {
117         if (arch_env->impl->register_saved_by)
118                 return arch_env->impl->register_saved_by(reg, /*callee=*/0);
119         return false;
120 }
121
122
123
124 /*
125      _    ____ ___    ____      _ _ _                _
126     / \  | __ )_ _|  / ___|__ _| | | |__   __ _  ___| | _____
127    / _ \ |  _ \| |  | |   / _` | | | '_ \ / _` |/ __| |/ / __|
128   / ___ \| |_) | |  | |__| (_| | | | |_) | (_| | (__|   <\__ \
129  /_/   \_\____/___|  \____\__,_|_|_|_.__/ \__,_|\___|_|\_\___/
130
131   These callbacks are used by the backend to set the parameters
132   for a specific call type.
133 */
134
135 /**
136  * Set compare function: compares two ABI call object arguments.
137  */
138 static int cmp_call_arg(const void *a, const void *b, size_t n)
139 {
140         const be_abi_call_arg_t *p = (const be_abi_call_arg_t*)a;
141         const be_abi_call_arg_t *q = (const be_abi_call_arg_t*)b;
142         (void) n;
143         return !(p->is_res == q->is_res && p->pos == q->pos && p->callee == q->callee);
144 }
145
146 /**
147  * Get  an ABI call object argument.
148  *
149  * @param call      the abi call
150  * @param is_res    true for call results, false for call arguments
151  * @param pos       position of the argument
152  * @param callee    context type - if we are callee or caller
153  */
154 static be_abi_call_arg_t *get_call_arg(be_abi_call_t *call, int is_res, int pos, int callee)
155 {
156         be_abi_call_arg_t arg;
157         unsigned hash;
158
159         memset(&arg, 0, sizeof(arg));
160         arg.is_res = is_res;
161         arg.pos    = pos;
162         arg.callee = callee;
163
164         hash = is_res * 128 + pos;
165
166         return set_find(be_abi_call_arg_t, call->params, &arg, sizeof(arg), hash);
167 }
168
169 /**
170  * Set an ABI call object argument.
171  */
172 static void remember_call_arg(be_abi_call_arg_t *arg, be_abi_call_t *call, be_abi_context_t context)
173 {
174         unsigned hash = arg->is_res * 128 + arg->pos;
175         if (context & ABI_CONTEXT_CALLEE) {
176                 arg->callee = 1;
177                 (void)set_insert(be_abi_call_arg_t, call->params, arg, sizeof(*arg), hash);
178         }
179         if (context & ABI_CONTEXT_CALLER) {
180                 arg->callee = 0;
181                 (void)set_insert(be_abi_call_arg_t, call->params, arg, sizeof(*arg), hash);
182         }
183 }
184
185 /* Set the flags for a call. */
186 void be_abi_call_set_flags(be_abi_call_t *call, be_abi_call_flags_t flags, const be_abi_callbacks_t *cb)
187 {
188         call->flags = flags;
189         call->cb    = cb;
190 }
191
192 /* Sets the number of bytes the stackframe is shrinked by the callee on return */
193 void be_abi_call_set_pop(be_abi_call_t *call, int pop)
194 {
195         assert(pop >= 0);
196         call->pop = pop;
197 }
198
199 void be_abi_call_param_stack(be_abi_call_t *call, int arg_pos,
200                              ir_mode *load_mode, unsigned alignment,
201                              unsigned space_before, unsigned space_after,
202                              be_abi_context_t context)
203 {
204         be_abi_call_arg_t arg;
205         memset(&arg, 0, sizeof(arg));
206         assert(alignment > 0 && "Alignment must be greater than 0");
207         arg.load_mode    = load_mode;
208         arg.alignment    = alignment;
209         arg.space_before = space_before;
210         arg.space_after  = space_after;
211         arg.is_res       = 0;
212         arg.pos          = arg_pos;
213
214         remember_call_arg(&arg, call, context);
215 }
216
217 void be_abi_call_param_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg, be_abi_context_t context)
218 {
219         be_abi_call_arg_t arg;
220         memset(&arg, 0, sizeof(arg));
221
222         arg.in_reg = 1;
223         arg.reg    = reg;
224         arg.is_res = 0;
225         arg.pos    = arg_pos;
226
227         remember_call_arg(&arg, call, context);
228 }
229
230 void be_abi_call_res_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg, be_abi_context_t context)
231 {
232         be_abi_call_arg_t arg;
233         memset(&arg, 0, sizeof(arg));
234
235         arg.in_reg = 1;
236         arg.reg    = reg;
237         arg.is_res = 1;
238         arg.pos    = arg_pos;
239
240         remember_call_arg(&arg, call, context);
241 }
242
243 /* Get the flags of a ABI call object. */
244 be_abi_call_flags_t be_abi_call_get_flags(const be_abi_call_t *call)
245 {
246         return call->flags;
247 }
248
249 /**
250  * Constructor for a new ABI call object.
251  *
252  * @return the new ABI call object
253  */
254 static be_abi_call_t *be_abi_call_new(void)
255 {
256         be_abi_call_t *call = XMALLOCZ(be_abi_call_t);
257
258         call->params            = new_set(cmp_call_arg, 16);
259         call->cb                = NULL;
260         call->flags.try_omit_fp = be_options.omit_fp;
261
262         return call;
263 }
264
265 /**
266  * Destructor for an ABI call object.
267  */
268 static void be_abi_call_free(be_abi_call_t *call)
269 {
270         del_set(call->params);
271         free(call);
272 }
273
274 /**
275  * Initializes the frame layout from parts
276  *
277  * @param frame     the stack layout that will be initialized
278  * @param args      the stack argument layout type
279  * @param between   the between layout type
280  * @param locals    the method frame type
281  *
282  * @return the initialized stack layout
283  */
284 static be_stack_layout_t *stack_frame_init(be_stack_layout_t *frame, ir_type *args,
285                                            ir_type *between, ir_type *locals)
286 {
287         frame->arg_type       = args;
288         frame->between_type   = between;
289         frame->frame_type     = locals;
290         frame->initial_offset = 0;
291         frame->initial_bias   = 0;
292         frame->order[1]       = between;
293
294         /* typical decreasing stack: locals have the
295          * lowest addresses, arguments the highest */
296         frame->order[0] = locals;
297         frame->order[2] = args;
298         return frame;
299 }
300
301 /*
302    ____      _ _
303   / ___|__ _| | |___
304  | |   / _` | | / __|
305  | |__| (_| | | \__ \
306   \____\__,_|_|_|___/
307
308   Adjustment of the calls inside a graph.
309
310 */
311
312 /**
313  * Transform a call node into a be_Call node.
314  *
315  * @param env The ABI environment for the current irg.
316  * @param irn The call node.
317  * @param curr_sp The stack pointer node to use.
318  * @return The stack pointer after the call.
319  */
320 static ir_node *adjust_call(be_abi_irg_t *env, ir_node *irn, ir_node *curr_sp)
321 {
322         ir_graph *irg              = get_irn_irg(irn);
323         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
324         ir_type *call_tp           = get_Call_type(irn);
325         ir_node *call_ptr          = get_Call_ptr(irn);
326         size_t   n_params          = get_method_n_params(call_tp);
327         ir_node *curr_mem          = get_Call_mem(irn);
328         ir_node *bl                = get_nodes_block(irn);
329         int stack_size             = 0;
330         const arch_register_t *sp  = arch_env->sp;
331         be_abi_call_t *call        = be_abi_call_new();
332         ir_mode *mach_mode         = sp->reg_class->mode;
333         int n_res                  = get_method_n_ress(call_tp);
334
335         ir_node *res_proj  = NULL;
336         int n_reg_params   = 0;
337         int n_stack_params = 0;
338         int n_ins;
339
340         const arch_register_t **states = NEW_ARR_F(const arch_register_t*, 0);
341         const arch_register_t **destroyed_regs = NEW_ARR_F(const arch_register_t*, 0);
342         ir_node                *low_call;
343         ir_node               **in;
344         ir_node               **res_projs;
345         int                     n_reg_results = 0;
346         int                    *reg_param_idxs;
347         int                    *stack_param_idx;
348         int                     i, n;
349         int                     throws_exception;
350         size_t                  s;
351         size_t                  p;
352         dbg_info               *dbgi;
353
354         /* Let the isa fill out the abi description for that call node. */
355         arch_env_get_call_abi(arch_env, call_tp, call);
356
357         /* Insert code to put the stack arguments on the stack. */
358         assert((size_t)get_Call_n_params(irn) == n_params);
359         stack_param_idx = ALLOCAN(int, n_params);
360         for (p = 0; p < n_params; ++p) {
361                 be_abi_call_arg_t *arg = get_call_arg(call, 0, p, 0);
362                 assert(arg);
363                 if (!arg->in_reg) {
364                         int arg_size = get_type_size_bytes(get_method_param_type(call_tp, p));
365
366                         stack_size += round_up2(arg->space_before, arg->alignment);
367                         stack_size += round_up2(arg_size, arg->alignment);
368                         stack_size += round_up2(arg->space_after, arg->alignment);
369
370                         stack_param_idx[n_stack_params++] = p;
371                 }
372         }
373
374         /* Collect all arguments which are passed in registers. */
375         reg_param_idxs = ALLOCAN(int, n_params);
376         for (p = 0; p < n_params; ++p) {
377                 be_abi_call_arg_t *arg = get_call_arg(call, 0, p, 0);
378                 if (arg && arg->in_reg) {
379                         reg_param_idxs[n_reg_params++] = p;
380                 }
381         }
382
383         /*
384          * If the stack is decreasing and we do not want to store sequentially,
385          * or someone else allocated the call frame
386          * we allocate as much space on the stack all parameters need, by
387          * moving the stack pointer along the stack's direction.
388          *
389          * Note: we also have to do this for stack_size == 0, because we may have
390          * to adjust stack alignment for the call.
391          */
392         curr_sp = be_new_IncSP(sp, bl, curr_sp, stack_size, 1);
393
394         dbgi = get_irn_dbg_info(irn);
395         /* If there are some parameters which shall be passed on the stack. */
396         if (n_stack_params > 0) {
397                 int       curr_ofs = 0;
398                 ir_node **in       = ALLOCAN(ir_node*, n_stack_params+1);
399                 unsigned  n_in     = 0;
400
401                 curr_mem = get_Call_mem(irn);
402                 in[n_in++] = curr_mem;
403
404                 for (i = 0; i < n_stack_params; ++i) {
405                         int p                  = stack_param_idx[i];
406                         be_abi_call_arg_t *arg = get_call_arg(call, 0, p, 0);
407                         ir_node *param         = get_Call_param(irn, p);
408                         ir_node *addr          = curr_sp;
409                         ir_node *mem           = NULL;
410                         ir_type *param_type    = get_method_param_type(call_tp, p);
411                         int param_size         = get_type_size_bytes(param_type) + arg->space_after;
412
413                         /*
414                          * If we wanted to build the arguments sequentially,
415                          * the stack pointer for the next must be incremented,
416                          * and the memory value propagated.
417                          */
418                         curr_ofs += arg->space_before;
419                         curr_ofs =  round_up2(curr_ofs, arg->alignment);
420
421                         /* Make the expression to compute the argument's offset. */
422                         if (curr_ofs > 0) {
423                                 ir_mode *constmode = mach_mode;
424                                 if (mode_is_reference(mach_mode)) {
425                                         constmode = mode_Is;
426                                 }
427                                 addr = new_r_Const_long(irg, constmode, curr_ofs);
428                                 addr = new_r_Add(bl, curr_sp, addr, mach_mode);
429                         }
430
431                         /* Insert a store for primitive arguments. */
432                         if (is_atomic_type(param_type)) {
433                                 ir_node *nomem     = get_irg_no_mem(irg);
434                                 ir_node *mem_input = nomem;
435                                 ir_node *store     = new_rd_Store(dbgi, bl, mem_input, addr, param, cons_none);
436                                 mem   = new_r_Proj(store, mode_M, pn_Store_M);
437                         } else {
438                                 /* Make a mem copy for compound arguments. */
439                                 ir_node *copy;
440
441                                 assert(mode_is_reference(get_irn_mode(param)));
442                                 copy = new_rd_CopyB(dbgi, bl, curr_mem, addr, param, param_type);
443                                 mem = new_r_Proj(copy, mode_M, pn_CopyB_M);
444                         }
445
446                         curr_ofs += param_size;
447
448                         in[n_in++] = mem;
449                 }
450
451                 /* We need the sync only, if we didn't build the stores sequentially. */
452                 if (n_stack_params >= 1) {
453                         curr_mem = new_r_Sync(bl, n_in, in);
454                 } else {
455                         curr_mem = get_Call_mem(irn);
456                 }
457         }
458
459         /* Put caller save into the destroyed set and state registers in the states
460          * set */
461         for (i = 0, n = arch_env->n_register_classes; i < n; ++i) {
462                 unsigned j;
463                 const arch_register_class_t *cls = &arch_env->register_classes[i];
464                 for (j = 0; j < cls->n_regs; ++j) {
465                         const arch_register_t *reg = arch_register_for_index(cls, j);
466
467                         /* even if destroyed all is specified, neither SP nor FP are
468                          * destroyed (else bad things will happen) */
469                         if (reg == arch_env->sp || reg == arch_env->bp)
470                                 continue;
471
472                         if (reg->type & arch_register_type_state) {
473                                 ARR_APP1(const arch_register_t*, destroyed_regs, reg);
474                                 ARR_APP1(const arch_register_t*, states, reg);
475                                 /* we're already in the destroyed set so no need for further
476                                  * checking */
477                                 continue;
478                         }
479                         if (arch_register_is_caller_save(arch_env, reg))
480                                 ARR_APP1(const arch_register_t*, destroyed_regs, reg);
481                 }
482         }
483
484         /* search the largest result proj number */
485         res_projs = ALLOCANZ(ir_node*, n_res);
486
487         foreach_out_edge(irn, edge) {
488                 ir_node *irn = get_edge_src_irn(edge);
489
490                 if (!is_Proj(irn) || get_Proj_proj(irn) != pn_Call_T_result)
491                         continue;
492
493                 foreach_out_edge(irn, res_edge) {
494                         ir_node *const res  = get_edge_src_irn(res_edge);
495                         long     const proj = get_Proj_proj(res);
496                         assert(proj < n_res);
497                         assert(res_projs[proj] == NULL);
498                         res_projs[proj] = res;
499                 }
500                 res_proj = irn;
501                 break;
502         }
503
504         /** TODO: this is not correct for cases where return values are passed
505          * on the stack, but no known ABI does this currently...
506          */
507         n_reg_results = n_res;
508
509         n_ins = 0;
510         in    = ALLOCAN(ir_node*, n_reg_params + ARR_LEN(states));
511
512         /* make the back end call node and set its register requirements. */
513         for (i = 0; i < n_reg_params; ++i) {
514                 in[n_ins++] = get_Call_param(irn, reg_param_idxs[i]);
515         }
516
517         /* add state registers ins */
518         for (s = 0; s < ARR_LEN(states); ++s) {
519                 const arch_register_t       *reg = states[s];
520                 const arch_register_class_t *cls = reg->reg_class;
521                 ir_node *regnode = new_r_Unknown(irg, cls->mode);
522                 in[n_ins++]      = regnode;
523         }
524         assert(n_ins == (int) (n_reg_params + ARR_LEN(states)));
525
526         /* ins collected, build the call */
527         throws_exception = ir_throws_exception(irn);
528         if (env->call->flags.call_has_imm && is_SymConst(call_ptr)) {
529                 /* direct call */
530                 low_call = be_new_Call(dbgi, bl, curr_mem, sp->single_req, curr_sp,
531                                        sp->single_req, curr_sp,
532                                        n_reg_results + pn_be_Call_first_res + ARR_LEN(destroyed_regs),
533                                        n_ins, in, get_Call_type(irn));
534                 be_Call_set_entity(low_call, get_SymConst_entity(call_ptr));
535         } else {
536                 /* indirect call */
537                 low_call = be_new_Call(dbgi, bl, curr_mem, sp->single_req, curr_sp,
538                                        sp->reg_class->class_req, call_ptr,
539                                        n_reg_results + pn_be_Call_first_res + ARR_LEN(destroyed_regs),
540                                        n_ins, in, get_Call_type(irn));
541         }
542         ir_set_throws_exception(low_call, throws_exception);
543         be_Call_set_pop(low_call, call->pop);
544
545         /* put the call into the list of all calls for later processing */
546         ARR_APP1(ir_node *, env->calls, low_call);
547
548         /* create new stack pointer */
549         curr_sp = new_r_Proj(low_call, get_irn_mode(curr_sp), pn_be_Call_sp);
550         be_set_constr_single_reg_out(low_call, pn_be_Call_sp, sp,
551                         arch_register_req_type_ignore | arch_register_req_type_produces_sp);
552         arch_set_irn_register(curr_sp, sp);
553
554         /* now handle results */
555         for (i = 0; i < n_res; ++i) {
556                 ir_node           *proj = res_projs[i];
557                 be_abi_call_arg_t *arg  = get_call_arg(call, 1, i, 0);
558
559                 /* returns values on stack not supported yet */
560                 assert(arg->in_reg);
561
562                 /*
563                         shift the proj number to the right, since we will drop the
564                         unspeakable Proj_T from the Call. Therefore, all real argument
565                         Proj numbers must be increased by pn_be_Call_first_res
566                 */
567                 long pn = i + pn_be_Call_first_res;
568
569                 if (proj == NULL) {
570                         ir_type *res_type = get_method_res_type(call_tp, i);
571                         ir_mode *mode     = get_type_mode(res_type);
572                         proj              = new_r_Proj(low_call, mode, pn);
573                         res_projs[i]      = proj;
574                 } else {
575                         set_Proj_pred(proj, low_call);
576                         set_Proj_proj(proj, pn);
577                 }
578
579                 if (arg->in_reg) {
580                         /* remove register from destroyed regs */
581                         size_t j;
582                         size_t n = ARR_LEN(destroyed_regs);
583                         for (j = 0; j < n; ++j) {
584                                 if (destroyed_regs[j] == arg->reg) {
585                                         destroyed_regs[j] = destroyed_regs[n-1];
586                                         ARR_SHRINKLEN(destroyed_regs,n-1);
587                                         break;
588                                 }
589                         }
590                 }
591         }
592
593         DBG((dbg, LEVEL_3, "\tcreated backend call %+F\n", low_call));
594
595         /* Set the register classes and constraints of the Call parameters. */
596         for (i = 0; i < n_reg_params; ++i) {
597                 int index = reg_param_idxs[i];
598                 be_abi_call_arg_t *arg = get_call_arg(call, 0, index, 0);
599                 assert(arg->reg != NULL);
600
601                 be_set_constr_single_reg_in(low_call, n_be_Call_first_arg + i,
602                                             arg->reg, arch_register_req_type_none);
603         }
604
605         /* Set the register constraints of the results. */
606         for (i = 0; i < n_res; ++i) {
607                 ir_node                 *proj = res_projs[i];
608                 const be_abi_call_arg_t *arg  = get_call_arg(call, 1, i, 0);
609                 int                      pn   = get_Proj_proj(proj);
610
611                 assert(arg->in_reg);
612                 be_set_constr_single_reg_out(low_call, pn, arg->reg,
613                                              arch_register_req_type_none);
614                 arch_set_irn_register(proj, arg->reg);
615         }
616         exchange(irn, low_call);
617
618         /* kill the ProjT node */
619         if (res_proj != NULL) {
620                 kill_node(res_proj);
621         }
622
623         /* Make additional projs for the caller save registers
624            and the Keep node which keeps them alive. */
625         {
626                 ir_node               **in, *keep;
627                 int                   i;
628                 size_t                d;
629                 int                   n = 0;
630                 int                   curr_res_proj = pn_be_Call_first_res + n_reg_results;
631                 int                   n_ins;
632
633                 n_ins = ARR_LEN(destroyed_regs) + n_reg_results + 1;
634                 in    = ALLOCAN(ir_node *, n_ins);
635
636                 /* also keep the stack pointer */
637                 set_irn_link(curr_sp, (void*) sp);
638                 in[n++] = curr_sp;
639
640                 for (d = 0; d < ARR_LEN(destroyed_regs); ++d) {
641                         const arch_register_t *reg = destroyed_regs[d];
642                         ir_node *proj = new_r_Proj(low_call, reg->reg_class->mode, curr_res_proj);
643
644                         /* memorize the register in the link field. we need afterwards to set the register class of the keep correctly. */
645                         be_set_constr_single_reg_out(low_call, curr_res_proj, reg,
646                                                      arch_register_req_type_none);
647                         arch_set_irn_register(proj, reg);
648
649                         set_irn_link(proj, (void*) reg);
650                         in[n++] = proj;
651                         ++curr_res_proj;
652                 }
653
654                 for (i = 0; i < n_reg_results; ++i) {
655                         ir_node *proj = res_projs[i];
656                         const arch_register_t *reg = arch_get_irn_register(proj);
657                         set_irn_link(proj, (void*) reg);
658                         in[n++] = proj;
659                 }
660                 assert(n <= n_ins);
661
662                 /* create the Keep for the caller save registers */
663                 keep = be_new_Keep(bl, n, in);
664                 for (i = 0; i < n; ++i) {
665                         const arch_register_t *reg = (const arch_register_t*)get_irn_link(in[i]);
666                         be_node_set_reg_class_in(keep, i, reg->reg_class);
667                 }
668         }
669
670         /* Clean up the stack. */
671         assert(stack_size >= call->pop);
672         stack_size -= call->pop;
673
674         if (stack_size > 0) {
675                 ir_node *mem_proj = NULL;
676
677                 foreach_out_edge(low_call, edge) {
678                         ir_node *irn = get_edge_src_irn(edge);
679                         if (is_Proj(irn) && get_Proj_proj(irn) == pn_Call_M) {
680                                 mem_proj = irn;
681                                 break;
682                         }
683                 }
684
685                 if (! mem_proj) {
686                         mem_proj = new_r_Proj(low_call, mode_M, pn_be_Call_M);
687                         keep_alive(mem_proj);
688                 }
689         }
690         /* Clean up the stack frame or revert alignment fixes if we allocated it */
691         curr_sp = be_new_IncSP(sp, bl, curr_sp, -stack_size, 0);
692
693         be_abi_call_free(call);
694
695         DEL_ARR_F(states);
696         DEL_ARR_F(destroyed_regs);
697
698         return curr_sp;
699 }
700
701 /**
702  * Adjust the size of a node representing a stack alloc or free for the minimum stack alignment.
703  *
704  * @param alignment  the minimum stack alignment
705  * @param size       the node containing the non-aligned size
706  * @param block      the block where new nodes are allocated on
707  * @param dbg        debug info for new nodes
708  *
709  * @return a node representing the aligned size
710  */
711 static ir_node *adjust_alloc_size(unsigned stack_alignment, ir_node *size,
712                                   ir_node *block, dbg_info *dbg)
713 {
714         if (stack_alignment > 1) {
715                 ir_mode   *mode;
716                 ir_tarval *tv;
717                 ir_node   *mask;
718                 ir_graph  *irg;
719
720                 assert(is_po2(stack_alignment));
721
722                 mode = get_irn_mode(size);
723                 tv   = new_tarval_from_long(stack_alignment-1, mode);
724                 irg  = get_Block_irg(block);
725                 mask = new_r_Const(irg, tv);
726                 size = new_rd_Add(dbg, block, size, mask, mode);
727
728                 tv   = new_tarval_from_long(-(long)stack_alignment, mode);
729                 mask = new_r_Const(irg, tv);
730                 size = new_rd_And(dbg, block, size, mask, mode);
731         }
732         return size;
733 }
734 /**
735  * Adjust an alloca.
736  * The alloca is transformed into a back end alloca node and connected to the stack nodes.
737  */
738 static ir_node *adjust_alloc(be_abi_irg_t *env, ir_node *alloc, ir_node *curr_sp)
739 {
740         ir_node          *block     = get_nodes_block(alloc);
741         ir_graph         *irg       = get_Block_irg(block);
742         const arch_env_t *arch_env  = be_get_irg_arch_env(irg);
743         ir_node          *alloc_mem = NULL;
744         ir_node          *alloc_res = NULL;
745         ir_type          *type      = get_Alloc_type(alloc);
746         dbg_info         *dbg;
747
748         ir_node *new_alloc;
749         ir_node *count;
750         ir_node *size;
751         ir_node *ins[2];
752         unsigned stack_alignment;
753
754         /* all non-stack Alloc nodes should already be lowered before the backend */
755         assert(get_Alloc_where(alloc) == stack_alloc);
756
757         foreach_out_edge(alloc, edge) {
758                 ir_node *irn = get_edge_src_irn(edge);
759
760                 switch (get_Proj_proj(irn)) {
761                 case pn_Alloc_M:
762                         alloc_mem = irn;
763                         break;
764                 case pn_Alloc_res:
765                         alloc_res = irn;
766                         break;
767                 default:
768                         break;
769                 }
770         }
771
772         /* Beware: currently Alloc nodes without a result might happen,
773            only escape analysis kills them and this phase runs only for object
774            oriented source. We kill the Alloc here. */
775         if (alloc_res == NULL && alloc_mem) {
776                 exchange(alloc_mem, get_Alloc_mem(alloc));
777                 return curr_sp;
778         }
779
780         dbg   = get_irn_dbg_info(alloc);
781         count = get_Alloc_count(alloc);
782
783         /* we might need to multiply the count with the element size */
784         if (!is_unknown_type(type) && get_type_size_bytes(type) != 1) {
785                 ir_mode   *mode  = get_irn_mode(count);
786                 ir_tarval *tv    = new_tarval_from_long(get_type_size_bytes(type),
787                                                         mode);
788                 ir_node   *cnst = new_rd_Const(dbg, irg, tv);
789                 size            = new_rd_Mul(dbg, block, count, cnst, mode);
790         } else {
791                 size = count;
792         }
793
794         /* The stack pointer will be modified in an unknown manner.
795            We cannot omit it. */
796         env->call->flags.try_omit_fp = 0;
797
798         stack_alignment = 1 << arch_env->stack_alignment;
799         size            = adjust_alloc_size(stack_alignment, size, block, dbg);
800         new_alloc       = be_new_AddSP(arch_env->sp, block, curr_sp, size);
801         set_irn_dbg_info(new_alloc, dbg);
802
803         if (alloc_mem != NULL) {
804                 ir_node *addsp_mem;
805                 ir_node *sync;
806
807                 addsp_mem = new_r_Proj(new_alloc, mode_M, pn_be_AddSP_M);
808
809                 /* We need to sync the output mem of the AddSP with the input mem
810                    edge into the alloc node. */
811                 ins[0] = get_Alloc_mem(alloc);
812                 ins[1] = addsp_mem;
813                 sync = new_r_Sync(block, 2, ins);
814
815                 exchange(alloc_mem, sync);
816         }
817
818         exchange(alloc, new_alloc);
819
820         /* fix projnum of alloca res */
821         set_Proj_proj(alloc_res, pn_be_AddSP_res);
822
823         curr_sp = new_r_Proj(new_alloc,  get_irn_mode(curr_sp), pn_be_AddSP_sp);
824
825         return curr_sp;
826 }
827
828 /**
829  * Adjust a Free.
830  * The Free is transformed into a back end free node and connected to the stack nodes.
831  */
832 static ir_node *adjust_free(be_abi_irg_t *env, ir_node *free, ir_node *curr_sp)
833 {
834         ir_node          *block    = get_nodes_block(free);
835         ir_graph         *irg      = get_irn_irg(free);
836         ir_type          *type     = get_Free_type(free);
837         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
838         ir_mode          *sp_mode  = arch_env->sp->reg_class->mode;
839         dbg_info         *dbg      = get_irn_dbg_info(free);
840         ir_node  *subsp, *mem, *res, *size, *sync;
841         ir_node *in[2];
842         unsigned stack_alignment;
843
844         /* all non-stack-alloc Free nodes should already be lowered before the
845          * backend phase */
846         assert(get_Free_where(free) == stack_alloc);
847
848         /* we might need to multiply the size with the element size */
849         if (!is_unknown_type(type) && get_type_size_bytes(type) != 1) {
850                 ir_tarval *tv   = new_tarval_from_long(get_type_size_bytes(type), mode_Iu);
851                 ir_node   *cnst = new_rd_Const(dbg, irg, tv);
852                 ir_node   *mul  = new_rd_Mul(dbg, block, get_Free_count(free),
853                                              cnst, mode_Iu);
854                 size = mul;
855         } else {
856                 size = get_Free_count(free);
857         }
858
859         stack_alignment = 1 << arch_env->stack_alignment;
860         size            = adjust_alloc_size(stack_alignment, size, block, dbg);
861
862         /* The stack pointer will be modified in an unknown manner.
863            We cannot omit it. */
864         env->call->flags.try_omit_fp = 0;
865         subsp = be_new_SubSP(arch_env->sp, block, curr_sp, size);
866         set_irn_dbg_info(subsp, dbg);
867
868         mem = new_r_Proj(subsp, mode_M, pn_be_SubSP_M);
869         res = new_r_Proj(subsp, sp_mode, pn_be_SubSP_sp);
870
871         /* we need to sync the memory */
872         in[0] = get_Free_mem(free);
873         in[1] = mem;
874         sync = new_r_Sync(block, 2, in);
875
876         /* and make the AddSP dependent on the former memory */
877         add_irn_dep(subsp, get_Free_mem(free));
878
879         /* kill the free */
880         exchange(free, sync);
881         curr_sp = res;
882
883         return curr_sp;
884 }
885
886 /**
887  * Check if a node is somehow data dependent on another one.
888  * both nodes must be in the same basic block.
889  * @param n1 The first node.
890  * @param n2 The second node.
891  * @return 1, if n1 is data dependent (transitively) on n2, 0 if not.
892  */
893 static int dependent_on(ir_node *n1, ir_node *n2)
894 {
895         assert(get_nodes_block(n1) == get_nodes_block(n2));
896
897         return heights_reachable_in_block(ir_heights, n1, n2);
898 }
899
900 static int cmp_call_dependency(const void *c1, const void *c2)
901 {
902         ir_node *n1 = *(ir_node **) c1;
903         ir_node *n2 = *(ir_node **) c2;
904         unsigned h1, h2;
905
906         /*
907                 Classical qsort() comparison function behavior:
908                 0  if both elements are equal
909                 1  if second is "smaller" that first
910                 -1 if first is "smaller" that second
911         */
912         if (dependent_on(n1, n2))
913                 return -1;
914
915         if (dependent_on(n2, n1))
916                 return 1;
917
918         /* The nodes have no depth order, but we need a total order because qsort()
919          * is not stable.
920          *
921          * Additionally, we need to respect transitive dependencies. Consider a
922          * Call a depending on Call b and an independent Call c.
923          * We MUST NOT order c > a and b > c. */
924         h1 = get_irn_height(ir_heights, n1);
925         h2 = get_irn_height(ir_heights, n2);
926         if (h1 < h2) return -1;
927         if (h1 > h2) return  1;
928         /* Same height, so use a random (but stable) order */
929         return get_irn_idx(n1) - get_irn_idx(n2);
930 }
931
932 /**
933  * Walker: links all Call/Alloc/Free nodes to the Block they are contained.
934  */
935 static void link_ops_in_block_walker(ir_node *irn, void *data)
936 {
937         be_abi_irg_t *env  = (be_abi_irg_t*)data;
938         unsigned      code = get_irn_opcode(irn);
939
940         if (code == iro_Call ||
941            (code == iro_Alloc && get_Alloc_where(irn) == stack_alloc) ||
942            (code == iro_Free && get_Free_where(irn) == stack_alloc)) {
943                 ir_node *bl       = get_nodes_block(irn);
944                 void *save        = get_irn_link(bl);
945
946                 set_irn_link(irn, save);
947                 set_irn_link(bl, irn);
948         }
949
950         if (code == iro_Builtin && get_Builtin_kind(irn) == ir_bk_return_address) {
951                 ir_node       *param = get_Builtin_param(irn, 0);
952                 ir_tarval     *tv    = get_Const_tarval(param);
953                 unsigned long  value = get_tarval_long(tv);
954                 /* use ebp, so the climbframe algo works... */
955                 if (value > 0) {
956                         env->call->flags.try_omit_fp = 0;
957                 }
958         }
959 }
960
961 /**
962  * Block-walker:
963  * Process all Call/Alloc/Free nodes inside a basic block.
964  * Note that the link field of the block must contain a linked list of all
965  * nodes inside the Block. We first order this list according to data dependency
966  * and that connect the nodes together.
967  */
968 static void process_ops_in_block(ir_node *bl, void *data)
969 {
970         be_abi_irg_t   *env     = (be_abi_irg_t*)data;
971         ir_node        *curr_sp = env->init_sp;
972         ir_node        *irn;
973         ir_node       **nodes;
974         int             n;
975         int             n_nodes;
976
977         n_nodes = 0;
978         for (irn = (ir_node*)get_irn_link(bl); irn != NULL;
979              irn = (ir_node*)get_irn_link(irn)) {
980                 ++n_nodes;
981         }
982
983         nodes = ALLOCAN(ir_node*, n_nodes);
984         for (irn = (ir_node*)get_irn_link(bl), n = 0; irn != NULL;
985              irn = (ir_node*)get_irn_link(irn), ++n) {
986                 nodes[n] = irn;
987         }
988
989         /* If there were call nodes in the block. */
990         if (n > 0) {
991                 ir_node *keep;
992                 int i;
993
994                 /* order the call nodes according to data dependency */
995                 qsort(nodes, n_nodes, sizeof(nodes[0]), cmp_call_dependency);
996
997                 for (i = n_nodes - 1; i >= 0; --i) {
998                         ir_node *irn = nodes[i];
999
1000                         DBG((dbg, LEVEL_3, "\tprocessing call %+F\n", irn));
1001                         switch (get_irn_opcode(irn)) {
1002                         case iro_Call:
1003                                 curr_sp = adjust_call(env, irn, curr_sp);
1004                                 break;
1005                         case iro_Alloc:
1006                                 if (get_Alloc_where(irn) == stack_alloc)
1007                                         curr_sp = adjust_alloc(env, irn, curr_sp);
1008                                 break;
1009                         case iro_Free:
1010                                 if (get_Free_where(irn) == stack_alloc)
1011                                         curr_sp = adjust_free(env, irn, curr_sp);
1012                                 break;
1013                         default:
1014                                 panic("invalid call");
1015                         }
1016                 }
1017
1018                 /* Keep the last stack state in the block by tying it to Keep node,
1019                  * the proj from calls is already kept */
1020                 if (curr_sp != env->init_sp &&
1021                     !(is_Proj(curr_sp) && be_is_Call(get_Proj_pred(curr_sp)))) {
1022                         nodes[0] = curr_sp;
1023                         keep     = be_new_Keep(bl, 1, nodes);
1024                         pmap_insert(env->keep_map, bl, keep);
1025                 }
1026         }
1027
1028         set_irn_link(bl, curr_sp);
1029 }
1030
1031 /**
1032  * Adjust all call nodes in the graph to the ABI conventions.
1033  */
1034 static void process_calls(ir_graph *const irg, be_abi_irg_t *const abi)
1035 {
1036         irg_walk_graph(irg, firm_clear_link, link_ops_in_block_walker, abi);
1037
1038         ir_heights = heights_new(irg);
1039         irg_block_walk_graph(irg, NULL, process_ops_in_block, abi);
1040         heights_free(ir_heights);
1041 }
1042
1043 /**
1044  * Computes the stack argument layout type.
1045  * Changes a possibly allocated value param type by moving
1046  * entities to the stack layout type.
1047  *
1048  * @param call          the current call ABI
1049  * @param method_type   the method type
1050  *
1051  * @return the stack argument layout type
1052  */
1053 static ir_type *compute_arg_type(ir_graph *irg, be_abi_call_t *call,
1054                                                                  ir_type *method_type)
1055 {
1056         struct obstack *obst = be_get_be_obst(irg);
1057         ir_type   *frame_type      = get_irg_frame_type(irg);
1058         size_t     n_params        = get_method_n_params(method_type);
1059         size_t     n_frame_members = get_compound_n_members(frame_type);
1060         ir_entity *va_start_entity = NULL;
1061         size_t   f;
1062         int      ofs  = 0;
1063
1064         ir_type *res;
1065         size_t i;
1066         ir_entity **map = OALLOCNZ(obst, ir_entity*, n_params);
1067         res = new_type_struct(new_id_from_chars("arg_type", 8));
1068
1069         /* collect existing entities for value_param_types */
1070         for (f = n_frame_members; f > 0; ) {
1071                 ir_entity *entity = get_compound_member(frame_type, --f);
1072                 size_t     num;
1073
1074                 set_entity_link(entity, NULL);
1075                 if (!is_parameter_entity(entity))
1076                         continue;
1077                 num = get_entity_parameter_number(entity);
1078                 if (num == IR_VA_START_PARAMETER_NUMBER) {
1079                         /* move entity to new arg_type */
1080                         set_entity_owner(entity, res);
1081                         va_start_entity = entity;
1082                         continue;
1083                 }
1084                 assert(num < n_params);
1085                 if (map[num] != NULL)
1086                         panic("multiple entities for parameter %u in %+F found", f, irg);
1087
1088                 if (num != n_params && get_call_arg(call, 0, num, 1)->in_reg) {
1089                         /* don't move this entity */
1090                         continue;
1091                 }
1092
1093                 map[num] = entity;
1094                 /* move entity to new arg_type */
1095                 set_entity_owner(entity, res);
1096         }
1097
1098         for (i = 0; i < n_params; ++i) {
1099                 be_abi_call_arg_t *arg        = get_call_arg(call, 0, i, 1);
1100                 ir_type           *param_type = get_method_param_type(method_type, i);
1101                 ir_entity         *entity;
1102
1103                 if (arg->in_reg)
1104                         continue;
1105                 entity = map[i];
1106                 if (entity == NULL) {
1107                         /* create a new entity */
1108                         entity = new_parameter_entity(res, i, param_type);
1109                 }
1110                 ofs += arg->space_before;
1111                 ofs = round_up2(ofs, arg->alignment);
1112                 set_entity_offset(entity, ofs);
1113                 ofs += arg->space_after;
1114                 ofs += get_type_size_bytes(param_type);
1115                 arg->stack_ent = entity;
1116         }
1117         if (va_start_entity != NULL) {
1118                 set_entity_offset(va_start_entity, ofs);
1119         }
1120         set_type_size_bytes(res, ofs);
1121         set_type_state(res, layout_fixed);
1122
1123         return res;
1124 }
1125
1126 static int cmp_regs(const void *a, const void *b)
1127 {
1128         arch_register_t const *const p = *(arch_register_t const**)a;
1129         arch_register_t const *const q = *(arch_register_t const**)b;
1130
1131         if (p->reg_class == q->reg_class)
1132                 return p->index - q->index;
1133         else
1134                 return p->reg_class < q->reg_class ? -1 : +1;
1135 }
1136
1137 static void reg_map_to_arr(arch_register_t const **const res, pmap *const reg_map)
1138 {
1139         pmap_entry *ent;
1140         size_t n = pmap_count(reg_map);
1141         size_t i = 0;
1142
1143         foreach_pmap(reg_map, ent) {
1144                 res[i++] = (arch_register_t const*)ent->key;
1145         }
1146
1147         qsort(res, n, sizeof(res[0]), cmp_regs);
1148 }
1149
1150 /**
1151  * Creates a be_Return for a Return node.
1152  *
1153  * @param @env  the abi environment
1154  * @param irn   the Return node
1155  */
1156 static ir_node *create_be_return(be_abi_irg_t *const env, ir_node *const irn)
1157 {
1158         ir_node          *const bl = get_nodes_block(irn);
1159         be_abi_call_t    *call     = env->call;
1160         ir_graph         *irg      = get_Block_irg(bl);
1161         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
1162         pmap *reg_map  = pmap_create();
1163         ir_node *keep  = pmap_get(ir_node, env->keep_map, bl);
1164         size_t in_max;
1165         int i, n;
1166         ir_node **in;
1167         ir_node *stack;
1168         const arch_register_t **regs;
1169         pmap_entry *ent;
1170
1171         /*
1172                 get the valid stack node in this block.
1173                 If we had a call in that block there is a Keep constructed by process_calls()
1174                 which points to the last stack modification in that block. we'll use
1175                 it then. Else we use the stack from the start block and let
1176                 the ssa construction fix the usage.
1177         */
1178         stack = be_abi_reg_map_get(env->regs, arch_env->sp);
1179         if (keep) {
1180                 stack = get_irn_n(keep, 0);
1181                 kill_node(keep);
1182                 remove_End_keepalive(get_irg_end(irg), keep);
1183         }
1184
1185         int const n_res = get_Return_n_ress(irn);
1186         /* Insert results for Return into the register map. */
1187         for (i = 0; i < n_res; ++i) {
1188                 ir_node *res           = get_Return_res(irn, i);
1189                 be_abi_call_arg_t *arg = get_call_arg(call, 1, i, 1);
1190                 assert(arg->in_reg && "return value must be passed in register");
1191                 pmap_insert(reg_map, (void *) arg->reg, res);
1192         }
1193
1194         /* Add uses of the callee save registers. */
1195         foreach_pmap(env->regs, ent) {
1196                 const arch_register_t *reg = (const arch_register_t*)ent->key;
1197                 if (arch_register_is_callee_save(arch_env, reg))
1198                         pmap_insert(reg_map, ent->key, ent->value);
1199         }
1200
1201         be_abi_reg_map_set(reg_map, arch_env->sp, stack);
1202
1203         /*
1204                 Maximum size of the in array for Return nodes is
1205                 return args + callee save/ignore registers + memory + stack pointer
1206         */
1207         in_max = pmap_count(reg_map) + n_res + 2;
1208
1209         in   = ALLOCAN(ir_node*,               in_max);
1210         regs = ALLOCAN(arch_register_t const*, in_max);
1211
1212         in[0]   = get_Return_mem(irn);
1213         in[1]   = be_abi_reg_map_get(reg_map, arch_env->sp);
1214         regs[0] = NULL;
1215         regs[1] = arch_env->sp;
1216         n       = 2;
1217
1218         /* clear SP entry, since it has already been grown. */
1219         pmap_insert(reg_map, (void *) arch_env->sp, NULL);
1220         for (i = 0; i < n_res; ++i) {
1221                 be_abi_call_arg_t *arg = get_call_arg(call, 1, i, 1);
1222
1223                 in[n]     = be_abi_reg_map_get(reg_map, arg->reg);
1224                 regs[n++] = arg->reg;
1225
1226                 /* Clear the map entry to mark the register as processed. */
1227                 be_abi_reg_map_set(reg_map, arg->reg, NULL);
1228         }
1229
1230         /* grow the rest of the stuff. */
1231         foreach_pmap(reg_map, ent) {
1232                 if (ent->value) {
1233                         in[n]     = (ir_node*)ent->value;
1234                         regs[n++] = (const arch_register_t*)ent->key;
1235                 }
1236         }
1237
1238         /* The in array for the new back end return is now ready. */
1239         dbg_info *const dbgi = get_irn_dbg_info(irn);
1240         ir_node  *const ret  = be_new_Return(dbgi, bl, n_res, call->pop, n, in);
1241
1242         /* Set the register classes of the return's parameter accordingly. */
1243         for (i = 0; i < n; ++i) {
1244                 if (regs[i] == NULL)
1245                         continue;
1246
1247                 be_set_constr_single_reg_in(ret, i, regs[i], arch_register_req_type_none);
1248         }
1249
1250         /* Free the space of the Epilog's in array and the register <-> proj map. */
1251         pmap_destroy(reg_map);
1252
1253         return ret;
1254 }
1255
1256 typedef struct lower_frame_sels_env_t {
1257         ir_node      *frame;                     /**< the current frame */
1258         const arch_register_class_t *sp_class;   /**< register class of the stack pointer */
1259 } lower_frame_sels_env_t;
1260
1261 /**
1262  * Walker: Replaces Sels of frame type and
1263  * value param type entities by FrameAddress.
1264  * Links all used entities.
1265  */
1266 static void lower_frame_sels_walker(ir_node *irn, void *data)
1267 {
1268         lower_frame_sels_env_t *ctx = (lower_frame_sels_env_t*)data;
1269
1270         if (is_Sel(irn)) {
1271                 ir_node *ptr = get_Sel_ptr(irn);
1272
1273                 if (ptr == ctx->frame) {
1274                         ir_entity    *ent = get_Sel_entity(irn);
1275                         ir_node      *bl  = get_nodes_block(irn);
1276                         ir_node      *nw;
1277
1278                         nw = be_new_FrameAddr(ctx->sp_class, bl, ctx->frame, ent);
1279                         exchange(irn, nw);
1280                 }
1281         }
1282 }
1283
1284 /**
1285  * The start block has no jump, instead it has an initial exec Proj.
1286  * The backend wants to handle all blocks the same way, so we replace
1287  * the out cfg edge with a real jump.
1288  */
1289 static void fix_start_block(ir_graph *irg)
1290 {
1291         ir_node *initial_X   = get_irg_initial_exec(irg);
1292         ir_node *start_block = get_irg_start_block(irg);
1293         ir_node *jmp         = new_r_Jmp(start_block);
1294
1295         assert(is_Proj(initial_X));
1296         exchange(initial_X, jmp);
1297         set_irg_initial_exec(irg, new_r_Bad(irg, mode_X));
1298
1299         /* merge start block with successor if possible */
1300         {
1301                 foreach_out_edge(jmp, edge) {
1302                         ir_node *succ = get_edge_src_irn(edge);
1303                         if (!is_Block(succ))
1304                                 continue;
1305
1306                         if (get_irn_arity(succ) == 1) {
1307                                 exchange(succ, start_block);
1308                         }
1309                         break;
1310                 }
1311         }
1312 }
1313
1314 /**
1315  * Modify the irg itself and the frame type.
1316  */
1317 static void modify_irg(ir_graph *const irg, be_abi_irg_t *const env)
1318 {
1319         be_abi_call_t         *call         = env->call;
1320         const arch_env_t      *arch_env     = be_get_irg_arch_env(irg);
1321         const arch_register_t *sp           = arch_env->sp;
1322         ir_type               *method_type  = get_entity_type(get_irg_entity(irg));
1323         be_irg_t              *birg         = be_birg_from_irg(irg);
1324         struct obstack        *obst         = be_get_be_obst(irg);
1325         be_stack_layout_t     *stack_layout = be_get_irg_stack_layout(irg);
1326         ir_node *end;
1327         ir_node *old_mem;
1328         ir_node *new_mem_proj;
1329         ir_node *mem;
1330
1331         int n_params;
1332         int i, n;
1333         unsigned j;
1334
1335         const arch_register_t *fp_reg;
1336         ir_node *frame_pointer;
1337         ir_node *start_bl;
1338         ir_node **args;
1339         ir_node *arg_tuple;
1340         ir_type *arg_type, *bet_type;
1341         lower_frame_sels_env_t ctx;
1342
1343         DBG((dbg, LEVEL_1, "introducing abi on %+F\n", irg));
1344
1345         old_mem = get_irg_initial_mem(irg);
1346
1347         irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
1348
1349         arg_type = compute_arg_type(irg, call, method_type);
1350
1351         /* Convert the Sel nodes in the irg to frame addr nodes: */
1352         ctx.frame    = get_irg_frame(irg);
1353         ctx.sp_class = arch_env->sp->reg_class;
1354
1355         ir_type *const frame_tp = get_irg_frame_type(irg);
1356         /* layout the stackframe now */
1357         if (get_type_state(frame_tp) == layout_undefined) {
1358                 default_layout_compound_type(frame_tp);
1359         }
1360
1361         /* align stackframe */
1362         unsigned const alignment  = 1U << arch_env->stack_alignment;
1363         unsigned const frame_size = round_up2(get_type_size_bytes(frame_tp), alignment);
1364         set_type_size_bytes(frame_tp, frame_size);
1365
1366         env->regs  = pmap_create();
1367
1368         n_params = get_method_n_params(method_type);
1369         args     = OALLOCNZ(obst, ir_node*, n_params);
1370
1371         be_add_parameter_entity_stores(irg);
1372
1373         irg_walk_graph(irg, lower_frame_sels_walker, NULL, &ctx);
1374
1375         irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
1376
1377         /* Fill the argument vector */
1378         arg_tuple = get_irg_args(irg);
1379         foreach_out_edge(arg_tuple, edge) {
1380                 ir_node *irn = get_edge_src_irn(edge);
1381                 if (! is_Anchor(irn)) {
1382                         int nr       = get_Proj_proj(irn);
1383                         args[nr]     = irn;
1384                         DBG((dbg, LEVEL_2, "\treading arg: %d -> %+F\n", nr, irn));
1385                 }
1386         }
1387
1388         stack_layout->sp_relative = call->flags.try_omit_fp;
1389         bet_type = call->cb->get_between_type(irg);
1390         stack_frame_init(stack_layout, arg_type, bet_type,
1391                          get_irg_frame_type(irg));
1392
1393         /* Count the register params and add them to the number of Projs for the RegParams node */
1394         for (i = 0; i < n_params; ++i) {
1395                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i, 1);
1396                 if (arg->in_reg && args[i]) {
1397                         assert(arg->reg != sp && "cannot use stack pointer as parameter register");
1398                         assert(i == get_Proj_proj(args[i]));
1399
1400                         /* For now, associate the register with the old Proj from Start representing that argument. */
1401                         pmap_insert(env->regs, (void *) arg->reg, args[i]);
1402                         DBG((dbg, LEVEL_2, "\targ #%d -> reg %s\n", i, arg->reg->name));
1403                 }
1404         }
1405
1406         /* Collect all callee-save registers */
1407         for (i = 0, n = arch_env->n_register_classes; i < n; ++i) {
1408                 const arch_register_class_t *cls = &arch_env->register_classes[i];
1409                 for (j = 0; j < cls->n_regs; ++j) {
1410                         const arch_register_t *reg = &cls->regs[j];
1411                         if ((reg->type & arch_register_type_state) || arch_register_is_callee_save(arch_env, reg)) {
1412                                 pmap_insert(env->regs, (void *) reg, NULL);
1413                         }
1414                 }
1415         }
1416
1417         fp_reg = call->flags.try_omit_fp ? arch_env->sp : arch_env->bp;
1418         rbitset_clear(birg->allocatable_regs, fp_reg->global_index);
1419
1420         /* handle start block here (place a jump in the block) */
1421         fix_start_block(irg);
1422
1423         pmap_insert(env->regs, (void *) sp, NULL);
1424         pmap_insert(env->regs, (void *) arch_env->bp, NULL);
1425         start_bl   = get_irg_start_block(irg);
1426         ir_node *const start = be_new_Start(NULL, start_bl, pmap_count(env->regs) + 1);
1427         set_irg_start(irg, start);
1428
1429         /*
1430          * make proj nodes for the callee save registers.
1431          * memorize them, since Return nodes get those as inputs.
1432          *
1433          * Note, that if a register corresponds to an argument, the regs map
1434          * contains the old Proj from start for that argument.
1435          */
1436         arch_register_t const **const regs = ALLOCAN(arch_register_t const*, pmap_count(env->regs));
1437         reg_map_to_arr(regs, env->regs);
1438         for (i = 0, n = pmap_count(env->regs); i < n; ++i) {
1439                 const arch_register_t    *reg      = regs[i];
1440                 ir_mode                  *mode     = reg->reg_class->mode;
1441                 long                      nr       = i;
1442                 arch_register_req_type_t  add_type = arch_register_req_type_none;
1443                 ir_node                  *proj;
1444
1445                 if (reg == sp)
1446                         add_type |= arch_register_req_type_produces_sp;
1447                 if (!rbitset_is_set(birg->allocatable_regs, reg->global_index)) {
1448                         add_type |= arch_register_req_type_ignore;
1449                 }
1450
1451                 assert(nr >= 0);
1452                 proj = new_r_Proj(start, mode, nr + 1);
1453                 pmap_insert(env->regs, (void *) reg, proj);
1454                 be_set_constr_single_reg_out(start, nr + 1, reg, add_type);
1455                 arch_set_irn_register(proj, reg);
1456
1457                 DBG((dbg, LEVEL_2, "\tregister save proj #%d -> reg %s\n", nr, reg->name));
1458         }
1459
1460         /* create a new initial memory proj */
1461         assert(is_Proj(old_mem));
1462         arch_set_irn_register_req_out(start, 0, arch_no_register_req);
1463         new_mem_proj = new_r_Proj(start, mode_M, 0);
1464         mem = new_mem_proj;
1465         set_irg_initial_mem(irg, mem);
1466
1467         env->init_sp = be_abi_reg_map_get(env->regs, sp);
1468
1469         /* set new frame_pointer */
1470         frame_pointer = be_abi_reg_map_get(env->regs, fp_reg);
1471         set_irg_frame(irg, frame_pointer);
1472
1473         /* rewire old mem users to new mem */
1474         exchange(old_mem, mem);
1475
1476         /* keep the mem (for functions with an endless loop = no return) */
1477         keep_alive(mem);
1478
1479         set_irg_initial_mem(irg, mem);
1480
1481         /* Now, introduce stack param nodes for all parameters passed on the stack */
1482         for (i = 0; i < n_params; ++i) {
1483                 ir_node *arg_proj = args[i];
1484                 ir_node *repl     = NULL;
1485
1486                 if (arg_proj != NULL) {
1487                         be_abi_call_arg_t *arg;
1488                         ir_type *param_type;
1489                         int     nr = get_Proj_proj(arg_proj);
1490                         ir_mode *mode;
1491
1492                         nr         = MIN(nr, n_params);
1493                         arg        = get_call_arg(call, 0, nr, 1);
1494                         param_type = get_method_param_type(method_type, nr);
1495
1496                         if (arg->in_reg) {
1497                                 repl = pmap_get(ir_node, env->regs, arg->reg);
1498                         } else {
1499                                 ir_node *addr = be_new_FrameAddr(sp->reg_class, start_bl, frame_pointer, arg->stack_ent);
1500
1501                                 /* For atomic parameters which are actually used, we create a Load node. */
1502                                 if (is_atomic_type(param_type) && get_irn_n_edges(args[i]) > 0) {
1503                                         ir_mode *mode      = get_type_mode(param_type);
1504                                         ir_mode *load_mode = arg->load_mode;
1505                                         ir_node *nomem     = get_irg_no_mem(irg);
1506
1507                                         ir_node *load = new_r_Load(start_bl, nomem, addr, load_mode, cons_floats);
1508                                         repl = new_r_Proj(load, load_mode, pn_Load_res);
1509
1510                                         if (mode != load_mode) {
1511                                                 repl = new_r_Conv(start_bl, repl, mode);
1512                                         }
1513                                 } else {
1514                                         /* The stack parameter is not primitive (it is a struct or array),
1515                                          * we thus will create a node representing the parameter's address
1516                                          * on the stack. */
1517                                         repl = addr;
1518                                 }
1519                         }
1520
1521                         assert(repl != NULL);
1522
1523                         /* Beware: the mode of the register parameters is always the mode of the register class
1524                            which may be wrong. Add Conv's then. */
1525                         mode = get_irn_mode(args[i]);
1526                         if (mode != get_irn_mode(repl)) {
1527                                 repl = new_r_Conv(get_nodes_block(repl), repl, mode);
1528                         }
1529                         exchange(args[i], repl);
1530                 }
1531         }
1532
1533         /* the arg proj is not needed anymore now and should be only used by the anchor */
1534         assert(get_irn_n_edges(arg_tuple) == 1);
1535         kill_node(arg_tuple);
1536         set_irg_args(irg, new_r_Bad(irg, mode_T));
1537
1538         /* All Return nodes hang on the End node, so look for them there. */
1539         end = get_irg_end_block(irg);
1540         for (i = 0, n = get_Block_n_cfgpreds(end); i < n; ++i) {
1541                 ir_node *irn = get_Block_cfgpred(end, i);
1542
1543                 if (is_Return(irn)) {
1544                         ir_node *const ret = create_be_return(env, irn);
1545                         exchange(irn, ret);
1546                 }
1547         }
1548
1549         /* if we have endless loops here, n might be <= 0. Do NOT create a be_Return then,
1550            the code is dead and will never be executed. */
1551 }
1552
1553 /** Fix the state inputs of calls that still hang on unknowns */
1554 static void fix_call_state_inputs(ir_graph *const irg, be_abi_irg_t *const env)
1555 {
1556         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
1557         int i, n, n_states;
1558         arch_register_t **stateregs = NEW_ARR_F(arch_register_t*, 0);
1559
1560         /* Collect caller save registers */
1561         n = arch_env->n_register_classes;
1562         for (i = 0; i < n; ++i) {
1563                 unsigned j;
1564                 const arch_register_class_t *cls = &arch_env->register_classes[i];
1565                 for (j = 0; j < cls->n_regs; ++j) {
1566                         const arch_register_t *reg = arch_register_for_index(cls, j);
1567                         if (reg->type & arch_register_type_state) {
1568                                 ARR_APP1(arch_register_t*, stateregs, (arch_register_t *)reg);
1569                         }
1570                 }
1571         }
1572
1573         n = ARR_LEN(env->calls);
1574         n_states = ARR_LEN(stateregs);
1575         for (i = 0; i < n; ++i) {
1576                 int s, arity;
1577                 ir_node *call = env->calls[i];
1578
1579                 arity = get_irn_arity(call);
1580
1581                 /* the state reg inputs are the last n inputs of the calls */
1582                 for (s = 0; s < n_states; ++s) {
1583                         int inp = arity - n_states + s;
1584                         const arch_register_t *reg = stateregs[s];
1585                         ir_node *regnode = be_abi_reg_map_get(env->regs, reg);
1586
1587                         set_irn_n(call, inp, regnode);
1588                 }
1589         }
1590
1591         DEL_ARR_F(stateregs);
1592 }
1593
1594 /**
1595  * Create a trampoline entity for the given method.
1596  */
1597 static ir_entity *create_trampoline(be_main_env_t *be, ir_entity *method)
1598 {
1599         ir_type   *type   = get_entity_type(method);
1600         ident     *old_id = get_entity_ld_ident(method);
1601         ident     *id     = id_mangle3("", old_id, "$stub");
1602         ir_type   *parent = be->pic_trampolines_type;
1603         ir_entity *ent    = new_entity(parent, old_id, type);
1604         set_entity_ld_ident(ent, id);
1605         set_entity_visibility(ent, ir_visibility_private);
1606
1607         return ent;
1608 }
1609
1610 /**
1611  * Returns the trampoline entity for the given method.
1612  */
1613 static ir_entity *get_trampoline(be_main_env_t *env, ir_entity *method)
1614 {
1615         ir_entity *result = pmap_get(ir_entity, env->ent_trampoline_map, method);
1616         if (result == NULL) {
1617                 result = create_trampoline(env, method);
1618                 pmap_insert(env->ent_trampoline_map, method, result);
1619         }
1620
1621         return result;
1622 }
1623
1624 static ir_entity *create_pic_symbol(be_main_env_t *be, ir_entity *entity)
1625 {
1626         ident     *old_id = get_entity_ld_ident(entity);
1627         ident     *id     = id_mangle3("", old_id, "$non_lazy_ptr");
1628         ir_type   *e_type = get_entity_type(entity);
1629         ir_type   *type   = new_type_pointer(e_type);
1630         ir_type   *parent = be->pic_symbols_type;
1631         ir_entity *ent    = new_entity(parent, old_id, type);
1632         set_entity_ld_ident(ent, id);
1633         set_entity_visibility(ent, ir_visibility_private);
1634
1635         return ent;
1636 }
1637
1638 static ir_entity *get_pic_symbol(be_main_env_t *env, ir_entity *entity)
1639 {
1640         ir_entity *result = pmap_get(ir_entity, env->ent_pic_symbol_map, entity);
1641         if (result == NULL) {
1642                 result = create_pic_symbol(env, entity);
1643                 pmap_insert(env->ent_pic_symbol_map, entity, result);
1644         }
1645
1646         return result;
1647 }
1648
1649
1650
1651 /**
1652  * Returns non-zero if a given entity can be accessed using a relative address.
1653  */
1654 static int can_address_relative(ir_entity *entity)
1655 {
1656         return entity_has_definition(entity) && !(get_entity_linkage(entity) & IR_LINKAGE_MERGE);
1657 }
1658
1659 static ir_node *get_pic_base(ir_graph *irg)
1660 {
1661         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
1662         if (arch_env->impl->get_pic_base == NULL)
1663                 return NULL;
1664         return arch_env->impl->get_pic_base(irg);
1665 }
1666
1667 /** patches SymConsts to work in position independent code */
1668 static void fix_pic_symconsts(ir_node *node, void *data)
1669 {
1670         ir_graph         *irg = get_irn_irg(node);
1671         be_main_env_t    *be  = be_get_irg_main_env(irg);
1672         ir_node          *pic_base;
1673         ir_node          *add;
1674         ir_node          *block;
1675         ir_mode          *mode;
1676         ir_node          *load;
1677         ir_node          *load_res;
1678         int               arity, i;
1679         (void) data;
1680
1681         arity = get_irn_arity(node);
1682         for (i = 0; i < arity; ++i) {
1683                 dbg_info  *dbgi;
1684                 ir_node   *pred = get_irn_n(node, i);
1685                 ir_entity *entity;
1686                 ir_entity *pic_symbol;
1687                 ir_node   *pic_symconst;
1688
1689                 if (!is_SymConst(pred))
1690                         continue;
1691
1692                 entity = get_SymConst_entity(pred);
1693                 block  = get_nodes_block(pred);
1694
1695                 /* calls can jump to relative addresses, so we can directly jump to
1696                    the (relatively) known call address or the trampoline */
1697                 if (i == 1 && is_Call(node)) {
1698                         ir_entity *trampoline;
1699                         ir_node   *trampoline_const;
1700
1701                         if (can_address_relative(entity))
1702                                 continue;
1703
1704                         dbgi             = get_irn_dbg_info(pred);
1705                         trampoline       = get_trampoline(be, entity);
1706                         trampoline_const = new_rd_SymConst_addr_ent(dbgi, irg, mode_P_code,
1707                                                                     trampoline);
1708                         set_irn_n(node, i, trampoline_const);
1709                         continue;
1710                 }
1711
1712                 /* everything else is accessed relative to EIP */
1713                 mode     = get_irn_mode(pred);
1714                 pic_base = get_pic_base(irg);
1715
1716                 /* all ok now for locally constructed stuff */
1717                 if (can_address_relative(entity)) {
1718                         ir_node *add = new_r_Add(block, pic_base, pred, mode);
1719
1720                         /* make sure the walker doesn't visit this add again */
1721                         mark_irn_visited(add);
1722                         set_irn_n(node, i, add);
1723                         continue;
1724                 }
1725
1726                 /* get entry from pic symbol segment */
1727                 dbgi         = get_irn_dbg_info(pred);
1728                 pic_symbol   = get_pic_symbol(be, entity);
1729                 pic_symconst = new_rd_SymConst_addr_ent(dbgi, irg, mode_P_code,
1730                                                         pic_symbol);
1731                 add = new_r_Add(block, pic_base, pic_symconst, mode);
1732                 mark_irn_visited(add);
1733
1734                 /* we need an extra indirection for global data outside our current
1735                    module. The loads are always safe and can therefore float
1736                    and need no memory input */
1737                 load     = new_r_Load(block, get_irg_no_mem(irg), add, mode, cons_floats);
1738                 load_res = new_r_Proj(load, mode, pn_Load_res);
1739
1740                 set_irn_n(node, i, load_res);
1741         }
1742 }
1743
1744 void be_abi_introduce(ir_graph *irg)
1745 {
1746         ir_node          *old_frame   = get_irg_frame(irg);
1747         const arch_env_t *arch_env    = be_get_irg_arch_env(irg);
1748         ir_entity        *entity      = get_irg_entity(irg);
1749         ir_type          *method_type = get_entity_type(entity);
1750         be_irg_t         *birg        = be_birg_from_irg(irg);
1751         struct obstack   *obst        = &birg->obst;
1752         ir_node          *dummy       = new_r_Dummy(irg,
1753                                                     arch_env->sp->reg_class->mode);
1754         unsigned          r;
1755
1756         /* determine allocatable registers */
1757         assert(birg->allocatable_regs == NULL);
1758         birg->allocatable_regs = rbitset_obstack_alloc(obst, arch_env->n_registers);
1759         for (r = 0; r < arch_env->n_registers; ++r) {
1760                 const arch_register_t *reg = &arch_env->registers[r];
1761                 if ( !(reg->type & arch_register_type_ignore)) {
1762                         rbitset_set(birg->allocatable_regs, r);
1763                 }
1764         }
1765
1766         /* Break here if backend provides a custom API. */
1767
1768         be_abi_irg_t env;
1769         env.keep_map     = pmap_create();
1770         env.call         = be_abi_call_new();
1771         arch_env_get_call_abi(arch_env, method_type, env.call);
1772
1773         env.init_sp = dummy;
1774         env.calls   = NEW_ARR_F(ir_node*, 0);
1775
1776         assure_edges(irg);
1777
1778         if (be_options.pic) {
1779                 irg_walk_graph(irg, fix_pic_symconsts, NULL, NULL);
1780         }
1781
1782         /* Lower all call nodes in the IRG. */
1783         process_calls(irg, &env);
1784
1785         /* Process the IRG */
1786         modify_irg(irg, &env);
1787
1788         /* fix call inputs for state registers */
1789         fix_call_state_inputs(irg, &env);
1790
1791         be_abi_call_free(env.call);
1792
1793         /* We don't need the keep map anymore. */
1794         pmap_destroy(env.keep_map);
1795
1796         /* calls array is not needed anymore */
1797         DEL_ARR_F(env.calls);
1798
1799         /* reroute the stack origin of the calls to the true stack origin. */
1800         exchange(dummy, env.init_sp);
1801         exchange(old_frame, get_irg_frame(irg));
1802
1803         pmap_destroy(env.regs);
1804 }
1805
1806 void be_put_allocatable_regs(const ir_graph *irg,
1807                              const arch_register_class_t *cls, bitset_t *bs)
1808 {
1809         be_irg_t *birg             = be_birg_from_irg(irg);
1810         unsigned *allocatable_regs = birg->allocatable_regs;
1811         unsigned  i;
1812
1813         assert(bitset_size(bs) == cls->n_regs);
1814         bitset_clear_all(bs);
1815         for (i = 0; i < cls->n_regs; ++i) {
1816                 const arch_register_t *reg = &cls->regs[i];
1817                 if (rbitset_is_set(allocatable_regs, reg->global_index))
1818                         bitset_set(bs, i);
1819         }
1820 }
1821
1822 unsigned be_get_n_allocatable_regs(const ir_graph *irg,
1823                                    const arch_register_class_t *cls)
1824 {
1825         bitset_t *bs = bitset_alloca(cls->n_regs);
1826         be_put_allocatable_regs(irg, cls, bs);
1827         return bitset_popcount(bs);
1828 }
1829
1830 void be_set_allocatable_regs(const ir_graph *irg,
1831                              const arch_register_class_t *cls,
1832                              unsigned *raw_bitset)
1833 {
1834         be_irg_t *birg             = be_birg_from_irg(irg);
1835         unsigned *allocatable_regs = birg->allocatable_regs;
1836         unsigned  i;
1837
1838         rbitset_clear_all(raw_bitset, cls->n_regs);
1839         for (i = 0; i < cls->n_regs; ++i) {
1840                 const arch_register_t *reg = &cls->regs[i];
1841                 if (rbitset_is_set(allocatable_regs, reg->global_index))
1842                         rbitset_set(raw_bitset, i);
1843         }
1844 }
1845
1846 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_abi)
1847 void be_init_abi(void)
1848 {
1849         FIRM_DBG_REGISTER(dbg, "firm.be.abi");
1850 }