- stack alignment is now power of two
[libfirm] / ir / be / beabi.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       Backend ABI implementation.
23  * @author      Sebastian Hack, Michael Beck
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include "obst.h"
31 #include "offset.h"
32
33 #include "irgopt.h"
34
35 #include "irgraph_t.h"
36 #include "irnode_t.h"
37 #include "ircons_t.h"
38 #include "iredges_t.h"
39 #include "irgmod.h"
40 #include "irgwalk.h"
41 #include "irprintf_t.h"
42 #include "irgopt.h"
43 #include "irbitset.h"
44 #include "height.h"
45 #include "pdeq.h"
46 #include "irtools.h"
47 #include "raw_bitset.h"
48 #include "error.h"
49
50 #include "be.h"
51 #include "beabi.h"
52 #include "bearch_t.h"
53 #include "benode_t.h"
54 #include "belive_t.h"
55 #include "besched_t.h"
56 #include "beirg_t.h"
57 #include "bessaconstr.h"
58
59 typedef struct _be_abi_call_arg_t {
60         unsigned is_res   : 1;  /**< 1: the call argument is a return value. 0: it's a call parameter. */
61         unsigned in_reg   : 1;  /**< 1: this argument is transmitted in registers. */
62         unsigned on_stack : 1;  /**< 1: this argument is transmitted on the stack. */
63
64         int                    pos;
65         const arch_register_t *reg;
66         ir_entity             *stack_ent;
67         ir_mode               *load_mode;
68         unsigned               alignment;    /**< stack alignment */
69         unsigned               space_before; /**< allocate space before */
70         unsigned               space_after;  /**< allocate space after */
71 } be_abi_call_arg_t;
72
73 struct _be_abi_call_t {
74         be_abi_call_flags_t          flags;
75         int                          pop;
76         const be_abi_callbacks_t    *cb;
77         ir_type                     *between_type;
78         set                         *params;
79         const arch_register_class_t *cls_addr;
80 };
81
82 struct _be_abi_irg_t {
83         struct obstack       obst;
84         be_stack_layout_t    *frame;        /**< The stack frame model. */
85         be_irg_t             *birg;         /**< The back end IRG. */
86         const arch_env_t     *arch_env;
87         survive_dce_t        *dce_survivor;
88
89         be_abi_call_t        *call;         /**< The ABI call information. */
90         ir_type              *method_type;  /**< The type of the method of the IRG. */
91
92         ir_node              *init_sp;      /**< The node representing the stack pointer
93                                                  at the start of the function. */
94
95         ir_node              *reg_params;   /**< The reg params node. */
96         pmap                 *regs;         /**< A map of all callee-save and ignore regs to
97                                                  their Projs to the RegParams node. */
98
99         int                  start_block_bias; /**< The stack bias at the end of the start block. */
100
101         void                 *cb;           /**< ABI Callback self pointer. */
102
103         pmap                 *keep_map;     /**< mapping blocks to keep nodes. */
104         pset                 *ignore_regs;  /**< Additional registers which shall be ignored. */
105
106         ir_node             **calls;        /**< flexible array containing all be_Call nodes */
107
108         arch_register_req_t sp_req;
109         arch_register_req_t sp_cls_req;
110
111         DEBUG_ONLY(firm_dbg_module_t    *dbg;)  /**< The debugging module. */
112 };
113
114 static heights_t *ir_heights;
115
116 /* Flag: if set, try to omit the frame pointer if called by the backend */
117 static int be_omit_fp = 1;
118
119 /*
120      _    ____ ___    ____      _ _ _                _
121     / \  | __ )_ _|  / ___|__ _| | | |__   __ _  ___| | _____
122    / _ \ |  _ \| |  | |   / _` | | | '_ \ / _` |/ __| |/ / __|
123   / ___ \| |_) | |  | |__| (_| | | | |_) | (_| | (__|   <\__ \
124  /_/   \_\____/___|  \____\__,_|_|_|_.__/ \__,_|\___|_|\_\___/
125
126   These callbacks are used by the backend to set the parameters
127   for a specific call type.
128 */
129
130 /**
131  * Set compare function: compares two ABI call object arguments.
132  */
133 static int cmp_call_arg(const void *a, const void *b, size_t n)
134 {
135         const be_abi_call_arg_t *p = a, *q = b;
136         (void) n;
137         return !(p->is_res == q->is_res && p->pos == q->pos);
138 }
139
140 /**
141  * Get or set an ABI call object argument.
142  *
143  * @param call      the abi call
144  * @param is_res    true for call results, false for call arguments
145  * @param pos       position of the argument
146  * @param do_insert true if the argument is set, false if it's retrieved
147  */
148 static be_abi_call_arg_t *get_or_set_call_arg(be_abi_call_t *call, int is_res, int pos, int do_insert)
149 {
150         be_abi_call_arg_t arg;
151         unsigned hash;
152
153         memset(&arg, 0, sizeof(arg));
154         arg.is_res = is_res;
155         arg.pos    = pos;
156
157         hash = is_res * 128 + pos;
158
159         return do_insert
160                 ? set_insert(call->params, &arg, sizeof(arg), hash)
161                 : set_find(call->params, &arg, sizeof(arg), hash);
162 }
163
164 /**
165  * Retrieve an ABI call object argument.
166  *
167  * @param call      the ABI call object
168  * @param is_res    true for call results, false for call arguments
169  * @param pos       position of the argument
170  */
171 static INLINE be_abi_call_arg_t *get_call_arg(be_abi_call_t *call, int is_res, int pos)
172 {
173         return get_or_set_call_arg(call, is_res, pos, 0);
174 }
175
176 /* Set the flags for a call. */
177 void be_abi_call_set_flags(be_abi_call_t *call, be_abi_call_flags_t flags, const be_abi_callbacks_t *cb)
178 {
179         call->flags = flags;
180         call->cb    = cb;
181 }
182
183 void be_abi_call_set_pop(be_abi_call_t *call, int pop)
184 {
185         assert(pop >= 0);
186         call->pop = pop;
187 }
188
189 /* Set register class for call address */
190 void be_abi_call_set_call_address_reg_class(be_abi_call_t *call, const arch_register_class_t *cls)
191 {
192         call->cls_addr = cls;
193 }
194
195
196 void be_abi_call_param_stack(be_abi_call_t *call, int arg_pos, ir_mode *load_mode, unsigned alignment, unsigned space_before, unsigned space_after)
197 {
198         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 0, arg_pos, 1);
199         arg->on_stack     = 1;
200         arg->load_mode    = load_mode;
201         arg->alignment    = alignment;
202         arg->space_before = space_before;
203         arg->space_after  = space_after;
204         assert(alignment > 0 && "Alignment must be greater than 0");
205 }
206
207 void be_abi_call_param_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg)
208 {
209         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 0, arg_pos, 1);
210         arg->in_reg = 1;
211         arg->reg = reg;
212 }
213
214 void be_abi_call_res_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg)
215 {
216         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 1, arg_pos, 1);
217         arg->in_reg = 1;
218         arg->reg = reg;
219 }
220
221 /* Get the flags of a ABI call object. */
222 be_abi_call_flags_t be_abi_call_get_flags(const be_abi_call_t *call)
223 {
224         return call->flags;
225 }
226
227 /**
228  * Constructor for a new ABI call object.
229  *
230  * @return the new ABI call object
231  */
232 static be_abi_call_t *be_abi_call_new(const arch_register_class_t *cls_addr)
233 {
234         be_abi_call_t *call = xmalloc(sizeof(call[0]));
235         memset(call, 0, sizeof(call[0]));
236
237         call->flags.val  = 0;
238         call->params     = new_set(cmp_call_arg, 16);
239         call->cb         = NULL;
240         call->cls_addr   = cls_addr;
241
242         call->flags.bits.try_omit_fp = be_omit_fp;
243
244         return call;
245 }
246
247 /**
248  * Destructor for an ABI call object.
249  */
250 static void be_abi_call_free(be_abi_call_t *call)
251 {
252         del_set(call->params);
253         free(call);
254 }
255
256 /*
257   _____                           _   _                 _ _ _
258  |  ___| __ __ _ _ __ ___   ___  | | | | __ _ _ __   __| | (_)_ __   __ _
259  | |_ | '__/ _` | '_ ` _ \ / _ \ | |_| |/ _` | '_ \ / _` | | | '_ \ / _` |
260  |  _|| | | (_| | | | | | |  __/ |  _  | (_| | | | | (_| | | | | | | (_| |
261  |_|  |_|  \__,_|_| |_| |_|\___| |_| |_|\__,_|_| |_|\__,_|_|_|_| |_|\__, |
262                                                                     |___/
263
264   Handling of the stack frame. It is composed of three types:
265   1) The type of the arguments which are pushed on the stack.
266   2) The "between type" which consists of stuff the call of the
267      function pushes on the stack (like the return address and
268          the old base pointer for ia32).
269   3) The Firm frame type which consists of all local variables
270      and the spills.
271 */
272
273 static int get_stack_entity_offset(be_stack_layout_t *frame, ir_entity *ent,
274                                    int bias)
275 {
276         ir_type *t = get_entity_owner(ent);
277         int ofs    = get_entity_offset(ent);
278
279         int i, index;
280
281         /* Find the type the entity is contained in. */
282         for(index = 0; index < N_FRAME_TYPES; ++index) {
283                 if(frame->order[index] == t)
284                         break;
285         }
286
287         /* Add the size of all the types below the one of the entity to the entity's offset */
288         for(i = 0; i < index; ++i)
289                 ofs += get_type_size_bytes(frame->order[i]);
290
291         /* correct the offset by the initial position of the frame pointer */
292         ofs -= frame->initial_offset;
293
294         /* correct the offset with the current bias. */
295         ofs += bias;
296
297         return ofs;
298 }
299
300 /**
301  * Retrieve the entity with given offset from a frame type.
302  */
303 static ir_entity *search_ent_with_offset(ir_type *t, int offset)
304 {
305         int i, n;
306
307         for(i = 0, n = get_compound_n_members(t); i < n; ++i) {
308                 ir_entity *ent = get_compound_member(t, i);
309                 if(get_entity_offset(ent) == offset)
310                         return ent;
311         }
312
313         return NULL;
314 }
315
316 static int stack_frame_compute_initial_offset(be_stack_layout_t *frame)
317 {
318         ir_type  *base = frame->stack_dir < 0 ? frame->between_type : frame->frame_type;
319         ir_entity *ent = search_ent_with_offset(base, 0);
320
321         frame->initial_offset = ent ? get_stack_entity_offset(frame, ent, 0) : 0;
322
323         return frame->initial_offset;
324 }
325
326 /**
327  * Initializes the frame layout from parts
328  *
329  * @param frame     the stack layout that will be initialized
330  * @param args      the stack argument layout type
331  * @param between   the between layout type
332  * @param locals    the method frame type
333  * @param stack_dir the stack direction
334  * @param param_map an array mapping method argument positions to the stack argument type
335  *
336  * @return the initialized stack layout
337  */
338 static be_stack_layout_t *stack_frame_init(be_stack_layout_t *frame, ir_type *args,
339                                            ir_type *between, ir_type *locals, int stack_dir,
340                                            ir_entity *param_map[])
341 {
342         frame->arg_type       = args;
343         frame->between_type   = between;
344         frame->frame_type     = locals;
345         frame->initial_offset = 0;
346         frame->stack_dir      = stack_dir;
347         frame->order[1]       = between;
348         frame->param_map      = param_map;
349
350         if(stack_dir > 0) {
351                 frame->order[0] = args;
352                 frame->order[2] = locals;
353         }
354         else {
355                 frame->order[0] = locals;
356                 frame->order[2] = args;
357         }
358         return frame;
359 }
360
361 #if 0
362 /** Dumps the stack layout to file. */
363 static void stack_layout_dump(FILE *file, be_stack_layout_t *frame)
364 {
365         int i, j, n;
366
367         ir_fprintf(file, "initial offset: %d\n", frame->initial_offset);
368         for (j = 0; j < N_FRAME_TYPES; ++j) {
369                 ir_type *t = frame->order[j];
370
371                 ir_fprintf(file, "type %d: %F size: %d\n", j, t, get_type_size_bytes(t));
372                 for (i = 0, n = get_compound_n_members(t); i < n; ++i) {
373                         ir_entity *ent = get_compound_member(t, i);
374                         ir_fprintf(file, "\t%F int ofs: %d glob ofs: %d\n", ent, get_entity_offset_bytes(ent), get_stack_entity_offset(frame, ent, 0));
375                 }
376         }
377 }
378 #endif
379
380 /**
381  * Returns non-zero if the call argument at given position
382  * is transfered on the stack.
383  */
384 static INLINE int is_on_stack(be_abi_call_t *call, int pos)
385 {
386         be_abi_call_arg_t *arg = get_call_arg(call, 0, pos);
387         return arg && !arg->in_reg;
388 }
389
390 /*
391    ____      _ _
392   / ___|__ _| | |___
393  | |   / _` | | / __|
394  | |__| (_| | | \__ \
395   \____\__,_|_|_|___/
396
397   Adjustment of the calls inside a graph.
398
399 */
400
401 /**
402  * Transform a call node into a be_Call node.
403  *
404  * @param env The ABI environment for the current irg.
405  * @param irn The call node.
406  * @param curr_sp The stack pointer node to use.
407  * @return The stack pointer after the call.
408  */
409 static ir_node *adjust_call(be_abi_irg_t *env, ir_node *irn, ir_node *curr_sp)
410 {
411         ir_graph *irg              = env->birg->irg;
412         const arch_env_t *arch_env = env->birg->main_env->arch_env;
413         ir_type *call_tp           = get_Call_type(irn);
414         ir_node *call_ptr          = get_Call_ptr(irn);
415         int n_params               = get_method_n_params(call_tp);
416         ir_node *curr_mem          = get_Call_mem(irn);
417         ir_node *bl                = get_nodes_block(irn);
418         pset *results              = pset_new_ptr(8);
419         pset *caller_save          = pset_new_ptr(8);
420         pset *states               = pset_new_ptr(2);
421         int stack_size             = 0;
422         int stack_dir              = arch_env_stack_dir(arch_env);
423         const arch_register_t *sp  = arch_env_sp(arch_env);
424         be_abi_call_t *call        = be_abi_call_new(sp->reg_class);
425         ir_mode *mach_mode         = sp->reg_class->mode;
426         struct obstack *obst       = &env->obst;
427         int no_alloc               = call->flags.bits.frame_is_setup_on_call;
428         int n_res                  = get_method_n_ress(call_tp);
429         int do_seq                 = call->flags.bits.store_args_sequential && !no_alloc;
430
431         ir_node *res_proj  = NULL;
432         int n_reg_params   = 0;
433         int n_stack_params = 0;
434         int n_ins;
435
436         ir_node *low_call;
437         ir_node **in;
438         ir_node **res_projs;
439         int      n_reg_results = 0;
440         const arch_register_t *reg;
441         const ir_edge_t *edge;
442         int *reg_param_idxs;
443         int *stack_param_idx;
444         int i, n;
445
446         /* Let the isa fill out the abi description for that call node. */
447         arch_env_get_call_abi(arch_env, call_tp, call);
448
449         /* Insert code to put the stack arguments on the stack. */
450         assert(get_Call_n_params(irn) == n_params);
451         for (i = 0; i < n_params; ++i) {
452                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
453                 assert(arg);
454                 if (arg->on_stack) {
455                         int arg_size = get_type_size_bytes(get_method_param_type(call_tp, i));
456
457                         stack_size += round_up2(arg->space_before, arg->alignment);
458                         stack_size += round_up2(arg_size, arg->alignment);
459                         stack_size += round_up2(arg->space_after, arg->alignment);
460                         obstack_int_grow(obst, i);
461                         ++n_stack_params;
462                 }
463         }
464         stack_param_idx = obstack_finish(obst);
465
466         /* Collect all arguments which are passed in registers. */
467         for (i = 0; i < n_params; ++i) {
468                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
469                 if (arg && arg->in_reg) {
470                         obstack_int_grow(obst, i);
471                         ++n_reg_params;
472                 }
473         }
474         reg_param_idxs = obstack_finish(obst);
475
476         /*
477          * If the stack is decreasing and we do not want to store sequentially,
478          * or someone else allocated the call frame
479          * we allocate as much space on the stack all parameters need, by
480          * moving the stack pointer along the stack's direction.
481          *
482          * Note: we also have to do this for stack_size == 0, because we may have
483          * to adjust stack alignment for the call.
484          */
485         if (stack_dir < 0 && !do_seq && !no_alloc) {
486                 curr_sp = be_new_IncSP(sp, irg, bl, curr_sp, stack_size, 1);
487         }
488
489         /* If there are some parameters which shall be passed on the stack. */
490         if (n_stack_params > 0) {
491                 int curr_ofs      = 0;
492
493                 /*
494                  * Reverse list of stack parameters if call arguments are from left to right.
495                  * We must them reverse again if they are pushed (not stored) and the stack
496                  * direction is downwards.
497                  */
498                 if (call->flags.bits.left_to_right ^ (do_seq && stack_dir < 0)) {
499                         for (i = 0; i < n_stack_params >> 1; ++i) {
500                                 int other  = n_stack_params - i - 1;
501                                 int tmp    = stack_param_idx[i];
502                                 stack_param_idx[i]     = stack_param_idx[other];
503                                 stack_param_idx[other] = tmp;
504                         }
505                 }
506
507                 curr_mem = get_Call_mem(irn);
508                 if (! do_seq) {
509                         obstack_ptr_grow(obst, curr_mem);
510                 }
511
512                 for (i = 0; i < n_stack_params; ++i) {
513                         int p                  = stack_param_idx[i];
514                         be_abi_call_arg_t *arg = get_call_arg(call, 0, p);
515                         ir_node *param         = get_Call_param(irn, p);
516                         ir_node *addr          = curr_sp;
517                         ir_node *mem           = NULL;
518                         ir_type *param_type    = get_method_param_type(call_tp, p);
519                         int param_size         = get_type_size_bytes(param_type) + arg->space_after;
520
521                         /*
522                          * If we wanted to build the arguments sequentially,
523                          * the stack pointer for the next must be incremented,
524                          * and the memory value propagated.
525                          */
526                         if (do_seq) {
527                                 curr_ofs = 0;
528                                 addr = curr_sp = be_new_IncSP(sp, irg, bl, curr_sp, param_size + arg->space_before, 0);
529                                 add_irn_dep(curr_sp, curr_mem);
530                         }
531                         else {
532                                 curr_ofs += arg->space_before;
533                                 curr_ofs =  round_up2(curr_ofs, arg->alignment);
534
535                                 /* Make the expression to compute the argument's offset. */
536                                 if (curr_ofs > 0) {
537                                         ir_mode *constmode = mach_mode;
538                                         if(mode_is_reference(mach_mode)) {
539                                                 constmode = mode_Is;
540                                         }
541                                         addr = new_r_Const_long(irg, bl, constmode, curr_ofs);
542                                         addr = new_r_Add(irg, bl, curr_sp, addr, mach_mode);
543                                 }
544                         }
545
546                         /* Insert a store for primitive arguments. */
547                         if (is_atomic_type(param_type)) {
548                                 ir_node *store;
549                                 ir_node *mem_input = do_seq ? curr_mem : new_NoMem();
550                                 store = new_r_Store(irg, bl, mem_input, addr, param);
551                                 mem = new_r_Proj(irg, bl, store, mode_M, pn_Store_M);
552                         }
553
554                         /* Make a mem copy for compound arguments. */
555                         else {
556                                 ir_node *copy;
557
558                                 assert(mode_is_reference(get_irn_mode(param)));
559                                 copy = new_r_CopyB(irg, bl, curr_mem, addr, param, param_type);
560                                 mem = new_r_Proj(irg, bl, copy, mode_M, pn_CopyB_M_regular);
561                         }
562
563                         curr_ofs += param_size;
564
565                         if (do_seq)
566                                 curr_mem = mem;
567                         else
568                                 obstack_ptr_grow(obst, mem);
569                 }
570
571                 in = (ir_node **) obstack_finish(obst);
572
573                 /* We need the sync only, if we didn't build the stores sequentially. */
574                 if (! do_seq) {
575                         if (n_stack_params >= 1) {
576                                 curr_mem = new_r_Sync(irg, bl, n_stack_params + 1, in);
577                         } else {
578                                 curr_mem = get_Call_mem(irn);
579                         }
580                 }
581                 obstack_free(obst, in);
582         }
583
584         /* Collect caller save registers */
585         for (i = 0, n = arch_env_get_n_reg_class(arch_env); i < n; ++i) {
586                 unsigned j;
587                 const arch_register_class_t *cls = arch_env_get_reg_class(arch_env, i);
588                 for (j = 0; j < cls->n_regs; ++j) {
589                         const arch_register_t *reg = arch_register_for_index(cls, j);
590                         if (arch_register_type_is(reg, caller_save)) {
591                                 pset_insert_ptr(caller_save, (void *) reg);
592                         }
593                         if (arch_register_type_is(reg, state)) {
594                                 pset_insert_ptr(caller_save, (void*) reg);
595                                 pset_insert_ptr(states, (void*) reg);
596                         }
597                 }
598         }
599
600         /* search the greatest result proj number */
601
602         res_projs = alloca(n_res * sizeof(res_projs[0]));
603         memset(res_projs, 0, n_res * sizeof(res_projs[0]));
604
605         foreach_out_edge(irn, edge) {
606                 const ir_edge_t *res_edge;
607                 ir_node         *irn = get_edge_src_irn(edge);
608
609                 if(!is_Proj(irn) || get_Proj_proj(irn) != pn_Call_T_result)
610                         continue;
611
612                 foreach_out_edge(irn, res_edge) {
613                         int proj;
614                         ir_node *res = get_edge_src_irn(res_edge);
615
616                         assert(is_Proj(res));
617
618                         proj = get_Proj_proj(res);
619                         assert(proj < n_res);
620                         assert(res_projs[proj] == NULL);
621                         res_projs[proj] = res;
622                 }
623                 res_proj = irn;
624                 break;
625         }
626
627         /** TODO: this is not correct for cases where return values are passed
628          * on the stack, but no known ABI does this currentl...
629          */
630         n_reg_results = n_res;
631
632         /* make the back end call node and set its register requirements. */
633         for (i = 0; i < n_reg_params; ++i) {
634                 obstack_ptr_grow(obst, get_Call_param(irn, reg_param_idxs[i]));
635         }
636         foreach_pset(states, reg) {
637                 const arch_register_class_t *cls = arch_register_get_class(reg);
638 #if 0
639                 ir_node *regnode = be_abi_reg_map_get(env->regs, reg);
640                 ir_fprintf(stderr, "Adding %+F\n", regnode);
641 #endif
642                 ir_node *regnode = new_rd_Unknown(irg, arch_register_class_mode(cls));
643                 obstack_ptr_grow(obst, regnode);
644         }
645         n_ins = n_reg_params + pset_count(states);
646
647         in = obstack_finish(obst);
648
649         if (env->call->flags.bits.call_has_imm && is_SymConst(call_ptr)) {
650                 /* direct call */
651                 low_call = be_new_Call(get_irn_dbg_info(irn), irg, bl, curr_mem,
652                                        curr_sp, curr_sp,
653                                        n_reg_results + pn_be_Call_first_res + pset_count(caller_save),
654                                        n_ins, in, get_Call_type(irn));
655                 be_Call_set_entity(low_call, get_SymConst_entity(call_ptr));
656         } else {
657                 /* indirect call */
658                 low_call = be_new_Call(get_irn_dbg_info(irn), irg, bl, curr_mem,
659                                        curr_sp, call_ptr,
660                                        n_reg_results + pn_be_Call_first_res + pset_count(caller_save),
661                                        n_ins, in, get_Call_type(irn));
662         }
663         be_Call_set_pop(low_call, call->pop);
664         ARR_APP1(ir_node *, env->calls, low_call);
665
666         /* create new stack pointer */
667         curr_sp = new_r_Proj(irg, bl, low_call, get_irn_mode(curr_sp),
668                              pn_be_Call_sp);
669         be_set_constr_single_reg(low_call, BE_OUT_POS(pn_be_Call_sp), sp);
670         arch_set_irn_register(arch_env, curr_sp, sp);
671         be_node_set_flags(low_call, BE_OUT_POS(pn_be_Call_sp),
672                         arch_irn_flags_ignore | arch_irn_flags_modify_sp);
673
674         for(i = 0; i < n_res; ++i) {
675                 int pn;
676                 ir_node           *proj = res_projs[i];
677                 be_abi_call_arg_t *arg  = get_call_arg(call, 1, i);
678
679                 /* returns values on stack not supported yet */
680                 assert(arg->in_reg);
681
682                 /*
683                         shift the proj number to the right, since we will drop the
684                         unspeakable Proj_T from the Call. Therefore, all real argument
685                         Proj numbers must be increased by pn_be_Call_first_res
686                 */
687                 pn = i + pn_be_Call_first_res;
688
689                 if(proj == NULL) {
690                         ir_type *res_type = get_method_res_type(call_tp, i);
691                         ir_mode *mode     = get_type_mode(res_type);
692                         proj              = new_r_Proj(irg, bl, low_call, mode, pn);
693                         res_projs[i]      = proj;
694                 } else {
695                         set_Proj_pred(proj, low_call);
696                         set_Proj_proj(proj, pn);
697                 }
698
699                 if (arg->in_reg) {
700                         pset_remove_ptr(caller_save, arg->reg);
701                 }
702         }
703
704         /*
705                 Set the register class of the call address to
706                 the backend provided class (default: stack pointer class)
707         */
708         be_node_set_reg_class(low_call, be_pos_Call_ptr, call->cls_addr);
709
710         DBG((env->dbg, LEVEL_3, "\tcreated backend call %+F\n", low_call));
711
712         /* Set the register classes and constraints of the Call parameters. */
713         for (i = 0; i < n_reg_params; ++i) {
714                 int index = reg_param_idxs[i];
715                 be_abi_call_arg_t *arg = get_call_arg(call, 0, index);
716                 assert(arg->reg != NULL);
717
718                 be_set_constr_single_reg(low_call, be_pos_Call_first_arg + i, arg->reg);
719         }
720
721         /* Set the register constraints of the results. */
722         for (i = 0; i < n_res; ++i) {
723                 ir_node                 *proj = res_projs[i];
724                 const be_abi_call_arg_t *arg  = get_call_arg(call, 1, i);
725                 int                      pn   = get_Proj_proj(proj);
726
727                 assert(arg->in_reg);
728                 be_set_constr_single_reg(low_call, BE_OUT_POS(pn), arg->reg);
729                 arch_set_irn_register(arch_env, proj, arg->reg);
730         }
731         obstack_free(obst, in);
732         exchange(irn, low_call);
733
734         /* kill the ProjT node */
735         if (res_proj != NULL) {
736                 be_kill_node(res_proj);
737         }
738
739         /* Make additional projs for the caller save registers
740            and the Keep node which keeps them alive. */
741         if (1 || pset_count(caller_save) + n_reg_results > 0) {
742                 const arch_register_t *reg;
743                 ir_node               **in, *keep;
744                 int                   i;
745                 int                   n = 0;
746                 int                   curr_res_proj
747                         = pn_be_Call_first_res + n_reg_results;
748
749                 /* also keep the stack pointer */
750                 ++n;
751                 set_irn_link(curr_sp, (void*) sp);
752                 obstack_ptr_grow(obst, curr_sp);
753
754                 for (reg = pset_first(caller_save); reg; reg = pset_next(caller_save), ++n) {
755                         ir_node *proj = new_r_Proj(irg, bl, low_call, reg->reg_class->mode,
756                                                    curr_res_proj);
757
758                         /* memorize the register in the link field. we need afterwards to set the register class of the keep correctly. */
759                         be_set_constr_single_reg(low_call, BE_OUT_POS(curr_res_proj), reg);
760                         arch_set_irn_register(arch_env, proj, reg);
761
762                         /* a call can produce ignore registers, in this case set the flag and register for the Proj */
763                         if (arch_register_type_is(reg, ignore)) {
764                                 be_node_set_flags(low_call, BE_OUT_POS(curr_res_proj),
765                                                   arch_irn_flags_ignore);
766                         }
767
768                         set_irn_link(proj, (void*) reg);
769                         obstack_ptr_grow(obst, proj);
770                         curr_res_proj++;
771                 }
772
773                 for(i = 0; i < n_reg_results; ++i) {
774                         ir_node *proj = res_projs[i];
775                         const arch_register_t *reg = arch_get_irn_register(arch_env, proj);
776                         set_irn_link(proj, (void*) reg);
777                         obstack_ptr_grow(obst, proj);
778                 }
779                 n += n_reg_results;
780
781                 /* create the Keep for the caller save registers */
782                 in   = (ir_node **) obstack_finish(obst);
783                 keep = be_new_Keep(NULL, irg, bl, n, in);
784                 for (i = 0; i < n; ++i) {
785                         const arch_register_t *reg = get_irn_link(in[i]);
786                         be_node_set_reg_class(keep, i, reg->reg_class);
787                 }
788                 obstack_free(obst, in);
789         }
790
791         /* Clean up the stack. */
792         assert(stack_size >= call->pop);
793         stack_size -= call->pop;
794
795         if (stack_size > 0) {
796                 ir_node *mem_proj = NULL;
797
798                 foreach_out_edge(low_call, edge) {
799                         ir_node *irn = get_edge_src_irn(edge);
800                         if(is_Proj(irn) && get_Proj_proj(irn) == pn_Call_M) {
801                                 mem_proj = irn;
802                                 break;
803                         }
804                 }
805
806                 if (! mem_proj) {
807                         mem_proj = new_r_Proj(irg, bl, low_call, mode_M, pn_be_Call_M_regular);
808                         keep_alive(mem_proj);
809                 }
810         }
811         /* Clean up the stack frame or revert alignment fixes if we allocated it */
812         if (! no_alloc) {
813                 curr_sp = be_new_IncSP(sp, irg, bl, curr_sp, -stack_size, 0);
814         }
815
816         be_abi_call_free(call);
817         obstack_free(obst, stack_param_idx);
818         del_pset(results);
819         del_pset(states);
820         del_pset(caller_save);
821
822         return curr_sp;
823 }
824
825 /**
826  * Adjust the size of a node representing a stack alloc or free for the minimum stack alignment.
827  *
828  * @param alignment  the minimum stack alignment
829  * @param size       the node containing the non-aligned size
830  * @param irg        the irg where new nodes are allocated on
831  * @param irg        the block where new nodes are allocated on
832  * @param dbg        debug info for new nodes
833  *
834  * @return a node representing the aligned size
835  */
836 static ir_node *adjust_alloc_size(unsigned stack_alignment, ir_node *size,
837                                   ir_graph *irg, ir_node *block, dbg_info *dbg)
838 {
839         if (stack_alignment > 1) {
840                 ir_mode *mode;
841                 tarval  *tv;
842                 ir_node *mask;
843
844                 assert(is_po2(stack_alignment));
845
846                 mode = get_irn_mode(size);
847                 tv   = new_tarval_from_long(stack_alignment-1, mode);
848                 mask = new_r_Const(irg, block, mode, tv);
849                 size = new_rd_Add(dbg, irg, block, size, mask, mode);
850
851                 tv   = new_tarval_from_long(-(long)stack_alignment, mode);
852                 mask = new_r_Const(irg, block, mode, tv);
853                 size = new_rd_And(dbg, irg, block, size, mask, mode);
854         }
855         return size;
856 }
857 /**
858  * Adjust an alloca.
859  * The alloca is transformed into a back end alloca node and connected to the stack nodes.
860  */
861 static ir_node *adjust_alloc(be_abi_irg_t *env, ir_node *alloc, ir_node *curr_sp)
862 {
863         ir_node *block;
864         ir_graph *irg;
865         ir_node *alloc_mem;
866         ir_node *alloc_res;
867         ir_type *type;
868         dbg_info *dbg;
869
870         const ir_edge_t *edge;
871         ir_node *new_alloc, *size, *addr, *ins[2];
872         unsigned stack_alignment;
873
874         if (get_Alloc_where(alloc) != stack_alloc) {
875                 assert(0);
876                 return alloc;
877         }
878
879         block = get_nodes_block(alloc);
880         irg = get_irn_irg(block);
881         alloc_mem = NULL;
882         alloc_res = NULL;
883         type = get_Alloc_type(alloc);
884
885         foreach_out_edge(alloc, edge) {
886                 ir_node *irn = get_edge_src_irn(edge);
887
888                 assert(is_Proj(irn));
889                 switch(get_Proj_proj(irn)) {
890                 case pn_Alloc_M:
891                         alloc_mem = irn;
892                         break;
893                 case pn_Alloc_res:
894                         alloc_res = irn;
895                         break;
896                 default:
897                         break;
898                 }
899         }
900
901         /* Beware: currently Alloc nodes without a result might happen,
902            only escape analysis kills them and this phase runs only for object
903            oriented source. We kill the Alloc here. */
904         if (alloc_res == NULL && alloc_mem) {
905                 exchange(alloc_mem, get_Alloc_mem(alloc));
906                 return curr_sp;
907         }
908
909         dbg = get_irn_dbg_info(alloc);
910
911         /* we might need to multiply the size with the element size */
912         if(type != get_unknown_type() && get_type_size_bytes(type) != 1) {
913                 tarval *tv    = new_tarval_from_long(get_type_size_bytes(type),
914                                                      mode_Iu);
915                 ir_node *cnst = new_rd_Const(dbg, irg, block, mode_Iu, tv);
916                 ir_node *mul  = new_rd_Mul(dbg, irg, block, get_Alloc_size(alloc),
917                                            cnst, mode_Iu);
918                 size = mul;
919         } else {
920                 size = get_Alloc_size(alloc);
921         }
922
923         /* The stack pointer will be modified in an unknown manner.
924            We cannot omit it. */
925         env->call->flags.bits.try_omit_fp = 0;
926
927         stack_alignment = 1 << env->arch_env->stack_alignment;
928         size            = adjust_alloc_size(stack_alignment, size, irg, block, dbg);
929         new_alloc       = be_new_AddSP(env->arch_env->sp, irg, block, curr_sp, size);
930         set_irn_dbg_info(new_alloc, dbg);
931
932         if(alloc_mem != NULL) {
933                 ir_node *addsp_mem;
934                 ir_node *sync;
935
936                 addsp_mem = new_r_Proj(irg, block, new_alloc, mode_M, pn_be_AddSP_M);
937
938                 /* We need to sync the output mem of the AddSP with the input mem
939                    edge into the alloc node. */
940                 ins[0] = get_Alloc_mem(alloc);
941                 ins[1] = addsp_mem;
942                 sync = new_r_Sync(irg, block, 2, ins);
943
944                 exchange(alloc_mem, sync);
945         }
946
947         exchange(alloc, new_alloc);
948
949         /* fix projnum of alloca res */
950         set_Proj_proj(alloc_res, pn_be_AddSP_res);
951
952         addr    = alloc_res;
953         curr_sp = new_r_Proj(irg, block, new_alloc,  get_irn_mode(curr_sp),
954                              pn_be_AddSP_sp);
955
956         return curr_sp;
957 }  /* adjust_alloc */
958
959 /**
960  * Adjust a Free.
961  * The Free is transformed into a back end free node and connected to the stack nodes.
962  */
963 static ir_node *adjust_free(be_abi_irg_t *env, ir_node *free, ir_node *curr_sp)
964 {
965         ir_node *block;
966         ir_graph *irg;
967         ir_node *subsp, *mem, *res, *size, *sync;
968         ir_type *type;
969         ir_node *in[2];
970         ir_mode *sp_mode;
971         unsigned stack_alignment;
972         dbg_info *dbg;
973
974         if (get_Free_where(free) != stack_alloc) {
975                 assert(0);
976                 return free;
977         }
978
979         block = get_nodes_block(free);
980         irg = get_irn_irg(block);
981         type = get_Free_type(free);
982         sp_mode = env->arch_env->sp->reg_class->mode;
983         dbg = get_irn_dbg_info(free);
984
985         /* we might need to multiply the size with the element size */
986         if(type != get_unknown_type() && get_type_size_bytes(type) != 1) {
987                 tarval *tv = new_tarval_from_long(get_type_size_bytes(type), mode_Iu);
988                 ir_node *cnst = new_rd_Const(dbg, irg, block, mode_Iu, tv);
989                 ir_node *mul = new_rd_Mul(dbg, irg, block, get_Free_size(free),
990                                           cnst, mode_Iu);
991                 size = mul;
992         } else {
993                 size = get_Free_size(free);
994         }
995
996         stack_alignment = 1 << env->arch_env->stack_alignment;
997         size            = adjust_alloc_size(stack_alignment, size, irg, block, dbg);
998
999         /* The stack pointer will be modified in an unknown manner.
1000            We cannot omit it. */
1001         env->call->flags.bits.try_omit_fp = 0;
1002         subsp = be_new_SubSP(env->arch_env->sp, irg, block, curr_sp, size);
1003         set_irn_dbg_info(subsp, dbg);
1004
1005         mem = new_r_Proj(irg, block, subsp, mode_M, pn_be_SubSP_M);
1006         res = new_r_Proj(irg, block, subsp, sp_mode, pn_be_SubSP_sp);
1007
1008         /* we need to sync the memory */
1009         in[0] = get_Free_mem(free);
1010         in[1] = mem;
1011         sync = new_r_Sync(irg, block, 2, in);
1012
1013         /* and make the AddSP dependent on the former memory */
1014         add_irn_dep(subsp, get_Free_mem(free));
1015
1016         /* kill the free */
1017         exchange(free, sync);
1018         curr_sp = res;
1019
1020         return curr_sp;
1021 }  /* adjust_free */
1022
1023 /* the following function is replaced by the usage of the heights module */
1024 #if 0
1025 /**
1026  * Walker for dependent_on().
1027  * This function searches a node tgt recursively from a given node
1028  * but is restricted to the given block.
1029  * @return 1 if tgt was reachable from curr, 0 if not.
1030  */
1031 static int check_dependence(ir_node *curr, ir_node *tgt, ir_node *bl)
1032 {
1033         int n, i;
1034
1035         if (get_nodes_block(curr) != bl)
1036                 return 0;
1037
1038         if (curr == tgt)
1039                 return 1;
1040
1041         /* Phi functions stop the recursion inside a basic block */
1042         if (! is_Phi(curr)) {
1043                 for(i = 0, n = get_irn_arity(curr); i < n; ++i) {
1044                         if (check_dependence(get_irn_n(curr, i), tgt, bl))
1045                                 return 1;
1046                 }
1047         }
1048
1049         return 0;
1050 }
1051 #endif /* if 0 */
1052
1053 /**
1054  * Check if a node is somehow data dependent on another one.
1055  * both nodes must be in the same basic block.
1056  * @param n1 The first node.
1057  * @param n2 The second node.
1058  * @return 1, if n1 is data dependent (transitively) on n2, 0 if not.
1059  */
1060 static int dependent_on(ir_node *n1, ir_node *n2)
1061 {
1062         assert(get_nodes_block(n1) == get_nodes_block(n2));
1063
1064         return heights_reachable_in_block(ir_heights, n1, n2);
1065 }
1066
1067 static int cmp_call_dependency(const void *c1, const void *c2)
1068 {
1069         ir_node *n1 = *(ir_node **) c1;
1070         ir_node *n2 = *(ir_node **) c2;
1071
1072         /*
1073                 Classical qsort() comparison function behavior:
1074                 0  if both elements are equal
1075                 1  if second is "smaller" that first
1076                 -1 if first is "smaller" that second
1077         */
1078         if (dependent_on(n1, n2))
1079                 return -1;
1080
1081         if (dependent_on(n2, n1))
1082                 return 1;
1083
1084         return 0;
1085 }
1086
1087 /**
1088  * Walker: links all Call/alloc/Free nodes to the Block they are contained.
1089  */
1090 static void link_calls_in_block_walker(ir_node *irn, void *data)
1091 {
1092         ir_opcode code = get_irn_opcode(irn);
1093
1094         if (code == iro_Call ||
1095                 (code == iro_Alloc && get_Alloc_where(irn) == stack_alloc) ||
1096                 (code == iro_Free && get_Free_where(irn) == stack_alloc)) {
1097                 be_abi_irg_t *env = data;
1098                 ir_node *bl       = get_nodes_block(irn);
1099                 void *save        = get_irn_link(bl);
1100
1101                 if (code == iro_Call)
1102                         env->call->flags.bits.irg_is_leaf = 0;
1103
1104                 set_irn_link(irn, save);
1105                 set_irn_link(bl, irn);
1106         }
1107 }
1108
1109 /**
1110  * Block-walker:
1111  * Process all Call nodes inside a basic block.
1112  * Note that the link field of the block must contain a linked list of all
1113  * Call nodes inside the Block. We first order this list according to data dependency
1114  * and that connect the calls together.
1115  */
1116 static void process_calls_in_block(ir_node *bl, void *data)
1117 {
1118         be_abi_irg_t *env = data;
1119         ir_node *curr_sp  = env->init_sp;
1120         ir_node *irn;
1121         int n;
1122
1123         for(irn = get_irn_link(bl), n = 0; irn; irn = get_irn_link(irn), ++n)
1124                 obstack_ptr_grow(&env->obst, irn);
1125
1126         /* If there were call nodes in the block. */
1127         if(n > 0) {
1128                 ir_node *keep;
1129                 ir_node **nodes;
1130                 int i;
1131
1132                 nodes = obstack_finish(&env->obst);
1133
1134                 /* order the call nodes according to data dependency */
1135                 qsort(nodes, n, sizeof(nodes[0]), cmp_call_dependency);
1136
1137                 for(i = n - 1; i >= 0; --i) {
1138                         ir_node *irn = nodes[i];
1139
1140                         DBG((env->dbg, LEVEL_3, "\tprocessing call %+F\n", irn));
1141                         switch(get_irn_opcode(irn)) {
1142                         case iro_Call:
1143                                 curr_sp = adjust_call(env, irn, curr_sp);
1144                                 break;
1145                         case iro_Alloc:
1146                                 curr_sp = adjust_alloc(env, irn, curr_sp);
1147                                 break;
1148                         case iro_Free:
1149                                 curr_sp = adjust_free(env, irn, curr_sp);
1150                                 break;
1151                         default:
1152                                 panic("invalid call");
1153                                 break;
1154                         }
1155                 }
1156
1157                 obstack_free(&env->obst, nodes);
1158
1159                 /* Keep the last stack state in the block by tying it to Keep node,
1160                  * the proj from calls is already kept */
1161                 if(curr_sp != env->init_sp
1162                                 && !(is_Proj(curr_sp) && be_is_Call(get_Proj_pred(curr_sp)))) {
1163                         nodes[0] = curr_sp;
1164                         keep     = be_new_Keep(env->arch_env->sp->reg_class,
1165                                                get_irn_irg(bl), bl, 1, nodes);
1166                         pmap_insert(env->keep_map, bl, keep);
1167                 }
1168         }
1169
1170         set_irn_link(bl, curr_sp);
1171 }  /* process_calls_in_block */
1172
1173 /**
1174  * Adjust all call nodes in the graph to the ABI conventions.
1175  */
1176 static void process_calls(be_abi_irg_t *env)
1177 {
1178         ir_graph *irg = env->birg->irg;
1179
1180         env->call->flags.bits.irg_is_leaf = 1;
1181         irg_walk_graph(irg, firm_clear_link, link_calls_in_block_walker, env);
1182
1183         ir_heights = heights_new(env->birg->irg);
1184         irg_block_walk_graph(irg, NULL, process_calls_in_block, env);
1185         heights_free(ir_heights);
1186 }
1187
1188 /**
1189  * Computes the stack argument layout type.
1190  * Changes a possibly allocated value param type by moving
1191  * entities to the stack layout type.
1192  *
1193  * @param env          the ABI environment
1194  * @param call         the current call ABI
1195  * @param method_type  the method type
1196  * @param param_map    an array mapping method arguments to the stack layout type
1197  *
1198  * @return the stack argument layout type
1199  */
1200 static ir_type *compute_arg_type(be_abi_irg_t *env, be_abi_call_t *call, ir_type *method_type, ir_entity ***param_map)
1201 {
1202         int dir  = env->call->flags.bits.left_to_right ? 1 : -1;
1203         int inc  = env->birg->main_env->arch_env->stack_dir * dir;
1204         int n    = get_method_n_params(method_type);
1205         int curr = inc > 0 ? 0 : n - 1;
1206         int ofs  = 0;
1207
1208         char buf[128];
1209         ir_type *res;
1210         int i;
1211         ir_type *val_param_tp = get_method_value_param_type(method_type);
1212         ident *id = get_entity_ident(get_irg_entity(env->birg->irg));
1213         ir_entity **map;
1214
1215         *param_map = map = obstack_alloc(&env->obst, n * sizeof(ir_entity *));
1216         res = new_type_struct(mangle_u(id, new_id_from_chars("arg_type", 8)));
1217         for (i = 0; i < n; ++i, curr += inc) {
1218                 ir_type *param_type    = get_method_param_type(method_type, curr);
1219                 be_abi_call_arg_t *arg = get_call_arg(call, 0, curr);
1220
1221                 map[i] = NULL;
1222                 if (arg->on_stack) {
1223                         if (val_param_tp) {
1224                                 /* the entity was already created, move it to the param type */
1225                                 arg->stack_ent = get_method_value_param_ent(method_type, i);
1226                                 remove_struct_member(val_param_tp, arg->stack_ent);
1227                                 set_entity_owner(arg->stack_ent, res);
1228                                 add_struct_member(res, arg->stack_ent);
1229                                 /* must be automatic to set a fixed layout */
1230                                 set_entity_allocation(arg->stack_ent, allocation_automatic);
1231                         }
1232                         else {
1233                                 snprintf(buf, sizeof(buf), "param_%d", i);
1234                                 arg->stack_ent = new_entity(res, new_id_from_str(buf), param_type);
1235                         }
1236                         ofs += arg->space_before;
1237                         ofs = round_up2(ofs, arg->alignment);
1238                         set_entity_offset(arg->stack_ent, ofs);
1239                         ofs += arg->space_after;
1240                         ofs += get_type_size_bytes(param_type);
1241                         map[i] = arg->stack_ent;
1242                 }
1243         }
1244         set_type_size_bytes(res, ofs);
1245         set_type_state(res, layout_fixed);
1246         return res;
1247 }
1248
1249 #if 0
1250 static void create_register_perms(const arch_isa_t *isa, ir_graph *irg, ir_node *bl, pmap *regs)
1251 {
1252         int i, j, n;
1253         struct obstack obst;
1254
1255         obstack_init(&obst);
1256
1257         /* Create a Perm after the RegParams node to delimit it. */
1258         for(i = 0, n = arch_isa_get_n_reg_class(isa); i < n; ++i) {
1259                 const arch_register_class_t *cls = arch_isa_get_reg_class(isa, i);
1260                 ir_node *perm;
1261                 ir_node **in;
1262                 int n_regs;
1263
1264                 for(n_regs = 0, j = 0; j < cls->n_regs; ++j) {
1265                         const arch_register_t *reg = &cls->regs[j];
1266                         ir_node *irn = pmap_get(regs, (void *) reg);
1267
1268                         if(irn && !arch_register_type_is(reg, ignore)) {
1269                                 n_regs++;
1270                                 obstack_ptr_grow(&obst, irn);
1271                                 set_irn_link(irn, (void *) reg);
1272                         }
1273                 }
1274
1275                 obstack_ptr_grow(&obst, NULL);
1276                 in = obstack_finish(&obst);
1277                 if(n_regs > 0) {
1278                         perm = be_new_Perm(cls, irg, bl, n_regs, in);
1279                         for(j = 0; j < n_regs; ++j) {
1280                                 ir_node *arg = in[j];
1281                                 arch_register_t *reg = get_irn_link(arg);
1282                                 pmap_insert(regs, reg, arg);
1283                                 be_set_constr_single_reg(perm, BE_OUT_POS(j), reg);
1284                         }
1285                 }
1286                 obstack_free(&obst, in);
1287         }
1288
1289         obstack_free(&obst, NULL);
1290 }
1291 #endif
1292
1293 typedef struct {
1294         const arch_register_t *reg;
1295         ir_node *irn;
1296 } reg_node_map_t;
1297
1298 static int cmp_regs(const void *a, const void *b)
1299 {
1300         const reg_node_map_t *p = a;
1301         const reg_node_map_t *q = b;
1302
1303         if(p->reg->reg_class == q->reg->reg_class)
1304                 return p->reg->index - q->reg->index;
1305         else
1306                 return p->reg->reg_class - q->reg->reg_class;
1307 }
1308
1309 static reg_node_map_t *reg_map_to_arr(struct obstack *obst, pmap *reg_map)
1310 {
1311         pmap_entry *ent;
1312         int n = pmap_count(reg_map);
1313         int i = 0;
1314         reg_node_map_t *res = obstack_alloc(obst, n * sizeof(res[0]));
1315
1316         foreach_pmap(reg_map, ent) {
1317                 res[i].reg = ent->key;
1318                 res[i].irn = ent->value;
1319                 i++;
1320         }
1321
1322         qsort(res, n, sizeof(res[0]), cmp_regs);
1323         return res;
1324 }
1325
1326 /**
1327  * Creates a barrier.
1328  */
1329 static ir_node *create_barrier(be_abi_irg_t *env, ir_node *bl, ir_node **mem, pmap *regs, int in_req)
1330 {
1331         ir_graph *irg = env->birg->irg;
1332         int n_regs    = pmap_count(regs);
1333         int n;
1334         ir_node *irn;
1335         ir_node **in;
1336         reg_node_map_t *rm;
1337
1338         rm = reg_map_to_arr(&env->obst, regs);
1339
1340         for(n = 0; n < n_regs; ++n)
1341                 obstack_ptr_grow(&env->obst, rm[n].irn);
1342
1343         if(mem) {
1344                 obstack_ptr_grow(&env->obst, *mem);
1345                 n++;
1346         }
1347
1348         in = (ir_node **) obstack_finish(&env->obst);
1349         irn = be_new_Barrier(irg, bl, n, in);
1350         obstack_free(&env->obst, in);
1351
1352         for(n = 0; n < n_regs; ++n) {
1353                 const arch_register_t *reg = rm[n].reg;
1354                 int flags                  = 0;
1355                 int pos                    = BE_OUT_POS(n);
1356                 ir_node *proj;
1357
1358                 proj = new_r_Proj(irg, bl, irn, get_irn_mode(rm[n].irn), n);
1359                 be_node_set_reg_class(irn, n, reg->reg_class);
1360                 if(in_req)
1361                         be_set_constr_single_reg(irn, n, reg);
1362                 be_set_constr_single_reg(irn, pos, reg);
1363                 be_node_set_reg_class(irn, pos, reg->reg_class);
1364                 arch_set_irn_register(env->birg->main_env->arch_env, proj, reg);
1365
1366                 /* if the proj projects a ignore register or a node which is set to ignore, propagate this property. */
1367                 if(arch_register_type_is(reg, ignore) || arch_irn_is(env->birg->main_env->arch_env, in[n], ignore))
1368                         flags |= arch_irn_flags_ignore;
1369
1370                 if(arch_irn_is(env->birg->main_env->arch_env, in[n], modify_sp))
1371                         flags |= arch_irn_flags_modify_sp;
1372
1373                 be_node_set_flags(irn, pos, flags);
1374
1375                 pmap_insert(regs, (void *) reg, proj);
1376         }
1377
1378         if(mem) {
1379                 *mem = new_r_Proj(irg, bl, irn, mode_M, n);
1380         }
1381
1382         obstack_free(&env->obst, rm);
1383         return irn;
1384 }
1385
1386 /**
1387  * Creates a be_Return for a Return node.
1388  *
1389  * @param @env    the abi environment
1390  * @param irn     the Return node or NULL if there was none
1391  * @param bl      the block where the be_Retun should be placed
1392  * @param mem     the current memory
1393  * @param n_res   number of return results
1394  */
1395 static ir_node *create_be_return(be_abi_irg_t *env, ir_node *irn, ir_node *bl,
1396                 ir_node *mem, int n_res)
1397 {
1398         be_abi_call_t    *call     = env->call;
1399         const arch_env_t *arch_env = env->birg->main_env->arch_env;
1400         dbg_info *dbgi;
1401         pmap *reg_map  = pmap_create();
1402         ir_node *keep  = pmap_get(env->keep_map, bl);
1403         int in_max;
1404         ir_node *ret;
1405         int i, n;
1406         unsigned pop;
1407         ir_node **in;
1408         ir_node *stack;
1409         const arch_register_t **regs;
1410         pmap_entry *ent ;
1411
1412         /*
1413                 get the valid stack node in this block.
1414                 If we had a call in that block there is a Keep constructed by process_calls()
1415                 which points to the last stack modification in that block. we'll use
1416                 it then. Else we use the stack from the start block and let
1417                 the ssa construction fix the usage.
1418         */
1419         stack = be_abi_reg_map_get(env->regs, arch_env->sp);
1420         if (keep) {
1421                 stack = get_irn_n(keep, 0);
1422                 be_kill_node(keep);
1423                 remove_End_keepalive(get_irg_end(env->birg->irg), keep);
1424         }
1425
1426         /* Insert results for Return into the register map. */
1427         for(i = 0; i < n_res; ++i) {
1428                 ir_node *res           = get_Return_res(irn, i);
1429                 be_abi_call_arg_t *arg = get_call_arg(call, 1, i);
1430                 assert(arg->in_reg && "return value must be passed in register");
1431                 pmap_insert(reg_map, (void *) arg->reg, res);
1432         }
1433
1434         /* Add uses of the callee save registers. */
1435         foreach_pmap(env->regs, ent) {
1436                 const arch_register_t *reg = ent->key;
1437                 if(arch_register_type_is(reg, callee_save) || arch_register_type_is(reg, ignore))
1438                         pmap_insert(reg_map, ent->key, ent->value);
1439         }
1440
1441         be_abi_reg_map_set(reg_map, arch_env->sp, stack);
1442
1443         /* Make the Epilogue node and call the arch's epilogue maker. */
1444         create_barrier(env, bl, &mem, reg_map, 1);
1445         call->cb->epilogue(env->cb, bl, &mem, reg_map);
1446
1447         /*
1448                 Maximum size of the in array for Return nodes is
1449                 return args + callee save/ignore registers + memory + stack pointer
1450         */
1451         in_max = pmap_count(reg_map) + n_res + 2;
1452
1453         in   = obstack_alloc(&env->obst, in_max * sizeof(in[0]));
1454         regs = obstack_alloc(&env->obst, in_max * sizeof(regs[0]));
1455
1456         in[0]   = mem;
1457         in[1]   = be_abi_reg_map_get(reg_map, arch_env->sp);
1458         regs[0] = NULL;
1459         regs[1] = arch_env->sp;
1460         n       = 2;
1461
1462         /* clear SP entry, since it has already been grown. */
1463         pmap_insert(reg_map, (void *) arch_env->sp, NULL);
1464         for(i = 0; i < n_res; ++i) {
1465                 be_abi_call_arg_t *arg = get_call_arg(call, 1, i);
1466
1467                 in[n]     = be_abi_reg_map_get(reg_map, arg->reg);
1468                 regs[n++] = arg->reg;
1469
1470                 /* Clear the map entry to mark the register as processed. */
1471                 be_abi_reg_map_set(reg_map, arg->reg, NULL);
1472         }
1473
1474         /* grow the rest of the stuff. */
1475         foreach_pmap(reg_map, ent) {
1476                 if(ent->value) {
1477                         in[n]     = ent->value;
1478                         regs[n++] = ent->key;
1479                 }
1480         }
1481
1482         /* The in array for the new back end return is now ready. */
1483         if(irn != NULL) {
1484                 dbgi = get_irn_dbg_info(irn);
1485         } else {
1486                 dbgi = NULL;
1487         }
1488         /* we have to pop the shadow parameter in in case of struct returns */
1489         pop = call->pop;
1490         ret = be_new_Return(dbgi, env->birg->irg, bl, n_res, pop, n, in);
1491
1492         /* Set the register classes of the return's parameter accordingly. */
1493         for(i = 0; i < n; ++i)
1494                 if(regs[i])
1495                         be_node_set_reg_class(ret, i, regs[i]->reg_class);
1496
1497         /* Free the space of the Epilog's in array and the register <-> proj map. */
1498         obstack_free(&env->obst, in);
1499         pmap_destroy(reg_map);
1500
1501         return ret;
1502 }
1503
1504 typedef struct lower_frame_sels_env_t {
1505         be_abi_irg_t *env;
1506         ir_entity    *value_param_list;  /**< the list of all value param entities */
1507         ir_entity    *value_param_tail;  /**< the tail of the list of all value param entities */
1508 } lower_frame_sels_env_t;
1509
1510 /**
1511  * Walker: Replaces Sels of frame type and
1512  * value param type entities by FrameAddress.
1513  * Links all used entities.
1514  */
1515 static void lower_frame_sels_walker(ir_node *irn, void *data) {
1516         lower_frame_sels_env_t *ctx = data;
1517
1518         if (is_Sel(irn)) {
1519                 ir_graph *irg        = current_ir_graph;
1520                 ir_node  *frame      = get_irg_frame(irg);
1521                 ir_node  *param_base = get_irg_value_param_base(irg);
1522                 ir_node  *ptr        = get_Sel_ptr(irn);
1523
1524                 if (ptr == frame || ptr == param_base) {
1525                         be_abi_irg_t *env = ctx->env;
1526                         ir_entity    *ent = get_Sel_entity(irn);
1527                         ir_node      *bl  = get_nodes_block(irn);
1528                         ir_node      *nw;
1529
1530                         nw = be_new_FrameAddr(env->arch_env->sp->reg_class, irg, bl, frame, ent);
1531                         exchange(irn, nw);
1532
1533                         /* check, if it's a param sel and if have not seen this entity before */
1534                         if (ptr == param_base &&
1535                                         ent != ctx->value_param_tail &&
1536                                         get_entity_link(ent) == NULL) {
1537                                 set_entity_link(ent, ctx->value_param_list);
1538                                 ctx->value_param_list = ent;
1539                                 if (ctx->value_param_tail == NULL) ctx->value_param_tail = ent;
1540                         }
1541                 }
1542         }
1543 }
1544
1545 /**
1546  * Check if a value parameter is transmitted as a register.
1547  * This might happen if the address of an parameter is taken which is
1548  * transmitted in registers.
1549  *
1550  * Note that on some architectures this case must be handled specially
1551  * because the place of the backing store is determined by their ABI.
1552  *
1553  * In the default case we move the entity to the frame type and create
1554  * a backing store into the first block.
1555  */
1556 static void fix_address_of_parameter_access(be_abi_irg_t *env, ir_entity *value_param_list) {
1557         be_abi_call_t *call = env->call;
1558         ir_graph *irg       = env->birg->irg;
1559         ir_entity *ent, *next_ent, *new_list;
1560         ir_type *frame_tp;
1561         DEBUG_ONLY(firm_dbg_module_t *dbg = env->dbg;)
1562
1563         new_list = NULL;
1564         for (ent = value_param_list; ent; ent = next_ent) {
1565                 int i = get_struct_member_index(get_entity_owner(ent), ent);
1566                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
1567
1568                 next_ent = get_entity_link(ent);
1569                 if (arg->in_reg) {
1570                         DBG((dbg, LEVEL_2, "\targ #%d need backing store\n", i));
1571                         set_entity_link(ent, new_list);
1572                         new_list = ent;
1573                 }
1574         }
1575         if (new_list) {
1576                 /* ok, change the graph */
1577                 ir_node *start_bl = get_irg_start_block(irg);
1578                 ir_node *first_bl = NULL;
1579                 ir_node *frame, *imem, *nmem, *store, *mem, *args, *args_bl;
1580                 const ir_edge_t *edge;
1581                 optimization_state_t state;
1582                 unsigned offset;
1583
1584                 foreach_block_succ(start_bl, edge) {
1585                         ir_node *succ = get_edge_src_irn(edge);
1586                         if (start_bl != succ) {
1587                                 first_bl = succ;
1588                                 break;
1589                         }
1590                 }
1591                 assert(first_bl);
1592                 /* we had already removed critical edges, so the following
1593                    assertion should be always true. */
1594                 assert(get_Block_n_cfgpreds(first_bl) == 1);
1595
1596                 /* now create backing stores */
1597                 frame = get_irg_frame(irg);
1598                 imem = get_irg_initial_mem(irg);
1599
1600                 save_optimization_state(&state);
1601                 set_optimize(0);
1602                 nmem = new_r_Proj(irg, first_bl, get_irg_start(irg), mode_M, pn_Start_M);
1603                 restore_optimization_state(&state);
1604
1605                 /* reroute all edges to the new memory source */
1606                 edges_reroute(imem, nmem, irg);
1607
1608                 store   = NULL;
1609                 mem     = imem;
1610                 args    = get_irg_args(irg);
1611                 args_bl = get_nodes_block(args);
1612                 for (ent = new_list; ent; ent = get_entity_link(ent)) {
1613                         int     i     = get_struct_member_index(get_entity_owner(ent), ent);
1614                         ir_type *tp   = get_entity_type(ent);
1615                         ir_mode *mode = get_type_mode(tp);
1616                         ir_node *addr;
1617
1618                         /* address for the backing store */
1619                         addr = be_new_FrameAddr(env->arch_env->sp->reg_class, irg, first_bl, frame, ent);
1620
1621                         if (store)
1622                                 mem = new_r_Proj(irg, first_bl, store, mode_M, pn_Store_M);
1623
1624                         /* the backing store itself */
1625                         store = new_r_Store(irg, first_bl, mem, addr,
1626                                             new_r_Proj(irg, args_bl, args, mode, i));
1627                 }
1628                 /* the new memory Proj gets the last Proj from store */
1629                 set_Proj_pred(nmem, store);
1630                 set_Proj_proj(nmem, pn_Store_M);
1631
1632                 /* move all entities to the frame type */
1633                 frame_tp = get_irg_frame_type(irg);
1634                 offset   = get_type_size_bytes(frame_tp);
1635
1636                 /* we will add new entities: set the layout to undefined */
1637                 assert(get_type_state(frame_tp) == layout_fixed);
1638                 set_type_state(frame_tp, layout_undefined);
1639                 for (ent = new_list; ent; ent = get_entity_link(ent)) {
1640                         ir_type  *tp   = get_entity_type(ent);
1641                         unsigned align = get_type_alignment_bytes(tp);
1642
1643                         offset += align - 1;
1644                         offset &= ~(align - 1);
1645                         set_entity_owner(ent, frame_tp);
1646                         add_class_member(frame_tp, ent);
1647                         /* must be automatic to set a fixed layout */
1648                         set_entity_allocation(ent, allocation_automatic);
1649                         set_entity_offset(ent, offset);
1650                         offset += get_type_size_bytes(tp);
1651                 }
1652                 set_type_size_bytes(frame_tp, offset);
1653                 /* fix the layout again */
1654                 set_type_state(frame_tp, layout_fixed);
1655         }
1656 }
1657
1658 #if 1
1659 /**
1660  * The start block has no jump, instead it has an initial exec Proj.
1661  * The backend wants to handle all blocks the same way, so we replace
1662  * the out cfg edge with a real jump.
1663  */
1664 static void fix_start_block(ir_node *block, void *env) {
1665         int      *done = env;
1666         int      i;
1667         ir_node  *start_block;
1668         ir_graph *irg;
1669
1670         /* we processed the start block, return */
1671         if (*done)
1672                 return;
1673
1674         irg         = get_irn_irg(block);
1675         start_block = get_irg_start_block(irg);
1676
1677         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
1678                 ir_node *pred       = get_Block_cfgpred(block, i);
1679                 ir_node *pred_block = get_nodes_block(pred);
1680
1681                 /* ok, we are in the block, having start as cfg predecessor */
1682                 if (pred_block == start_block) {
1683                         ir_node *jump = new_r_Jmp(irg, pred_block);
1684                         set_Block_cfgpred(block, i, jump);
1685                         *done = 1;
1686                 }
1687         }
1688 }
1689 #endif
1690
1691 /**
1692  * Modify the irg itself and the frame type.
1693  */
1694 static void modify_irg(be_abi_irg_t *env)
1695 {
1696         be_abi_call_t *call       = env->call;
1697         const arch_env_t *arch_env= env->birg->main_env->arch_env;
1698         const arch_register_t *sp = arch_env_sp(arch_env);
1699         ir_graph *irg             = env->birg->irg;
1700         ir_node *bl               = get_irg_start_block(irg);
1701         ir_node *end              = get_irg_end_block(irg);
1702         ir_node *old_mem          = get_irg_initial_mem(irg);
1703         ir_node *new_mem_proj;
1704         ir_node *mem;
1705         ir_type *method_type      = get_entity_type(get_irg_entity(irg));
1706         pset *dont_save           = pset_new_ptr(8);
1707
1708         int n_params;
1709         int i, n;
1710         unsigned j;
1711
1712         reg_node_map_t *rm;
1713         const arch_register_t *fp_reg;
1714         ir_node *frame_pointer;
1715         ir_node *reg_params_bl;
1716         ir_node **args;
1717         ir_node *arg_tuple;
1718         ir_node *value_param_base;
1719         const ir_edge_t *edge;
1720         ir_type *arg_type, *bet_type, *tp;
1721         lower_frame_sels_env_t ctx;
1722         ir_entity **param_map;
1723
1724         bitset_t *used_proj_nr;
1725         DEBUG_ONLY(firm_dbg_module_t *dbg = env->dbg;)
1726
1727         DBG((dbg, LEVEL_1, "introducing abi on %+F\n", irg));
1728
1729         /* set the links of all frame entities to NULL, we use it
1730            to detect if an entity is already linked in the value_param_list */
1731         tp = get_method_value_param_type(method_type);
1732         if (tp != NULL) {
1733                 for (i = get_struct_n_members(tp) - 1; i >= 0; --i)
1734                         set_entity_link(get_struct_member(tp, i), NULL);
1735         }
1736
1737         /* Convert the Sel nodes in the irg to frame load/store/addr nodes. */
1738         ctx.env              = env;
1739         ctx.value_param_list = NULL;
1740         ctx.value_param_tail = NULL;
1741         irg_walk_graph(irg, lower_frame_sels_walker, NULL, &ctx);
1742
1743         /* value_param_base anchor is not needed anymore now */
1744         value_param_base = get_irg_value_param_base(irg);
1745         be_kill_node(value_param_base);
1746         set_irg_value_param_base(irg, new_r_Bad(irg));
1747
1748         env->frame = obstack_alloc(&env->obst, sizeof(env->frame[0]));
1749         env->regs  = pmap_create();
1750
1751         used_proj_nr = bitset_alloca(1024);
1752         n_params     = get_method_n_params(method_type);
1753         args         = obstack_alloc(&env->obst, n_params * sizeof(args[0]));
1754         memset(args, 0, n_params * sizeof(args[0]));
1755
1756         /* Check if a value parameter is transmitted as a register.
1757          * This might happen if the address of an parameter is taken which is
1758          * transmitted in registers.
1759          *
1760          * Note that on some architectures this case must be handled specially
1761          * because the place of the backing store is determined by their ABI.
1762          *
1763          * In the default case we move the entity to the frame type and create
1764          * a backing store into the first block.
1765          */
1766         fix_address_of_parameter_access(env, ctx.value_param_list);
1767
1768         /* Fill the argument vector */
1769         arg_tuple = get_irg_args(irg);
1770         foreach_out_edge(arg_tuple, edge) {
1771                 ir_node *irn = get_edge_src_irn(edge);
1772                 if (! is_Anchor(irn)) {
1773                         int nr       = get_Proj_proj(irn);
1774                         args[nr]     = irn;
1775                         DBG((dbg, LEVEL_2, "\treading arg: %d -> %+F\n", nr, irn));
1776                 }
1777         }
1778
1779         arg_type = compute_arg_type(env, call, method_type, &param_map);
1780         bet_type = call->cb->get_between_type(env->cb);
1781         stack_frame_init(env->frame, arg_type, bet_type, get_irg_frame_type(irg), arch_env->stack_dir, param_map);
1782
1783         /* Count the register params and add them to the number of Projs for the RegParams node */
1784         for(i = 0; i < n_params; ++i) {
1785                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
1786                 if(arg->in_reg && args[i]) {
1787                         assert(arg->reg != sp && "cannot use stack pointer as parameter register");
1788                         assert(i == get_Proj_proj(args[i]));
1789
1790                         /* For now, associate the register with the old Proj from Start representing that argument. */
1791                         pmap_insert(env->regs, (void *) arg->reg, args[i]);
1792                         bitset_set(used_proj_nr, i);
1793                         DBG((dbg, LEVEL_2, "\targ #%d -> reg %s\n", i, arg->reg->name));
1794                 }
1795         }
1796
1797         /* Collect all callee-save registers */
1798         for(i = 0, n = arch_env_get_n_reg_class(arch_env); i < n; ++i) {
1799                 const arch_register_class_t *cls = arch_env_get_reg_class(arch_env, i);
1800                 for(j = 0; j < cls->n_regs; ++j) {
1801                         const arch_register_t *reg = &cls->regs[j];
1802                         if(arch_register_type_is(reg, callee_save) ||
1803                                         arch_register_type_is(reg, state)) {
1804                                 pmap_insert(env->regs, (void *) reg, NULL);
1805                         }
1806                 }
1807         }
1808
1809         pmap_insert(env->regs, (void *) sp, NULL);
1810         pmap_insert(env->regs, (void *) arch_env->bp, NULL);
1811         reg_params_bl   = get_irg_start_block(irg);
1812         env->reg_params = be_new_RegParams(irg, reg_params_bl, pmap_count(env->regs));
1813         add_irn_dep(env->reg_params, get_irg_start(irg));
1814
1815         /*
1816          * make proj nodes for the callee save registers.
1817          * memorize them, since Return nodes get those as inputs.
1818          *
1819          * Note, that if a register corresponds to an argument, the regs map contains
1820          * the old Proj from start for that argument.
1821          */
1822
1823         rm = reg_map_to_arr(&env->obst, env->regs);
1824         for(i = 0, n = pmap_count(env->regs); i < n; ++i) {
1825                 arch_register_t *reg = (void *) rm[i].reg;
1826                 ir_mode *mode        = reg->reg_class->mode;
1827                 long nr              = i;
1828                 int pos              = BE_OUT_POS((int) nr);
1829                 int flags            = 0;
1830
1831                 ir_node *proj;
1832
1833                 assert(nr >= 0);
1834                 bitset_set(used_proj_nr, nr);
1835                 proj = new_r_Proj(irg, reg_params_bl, env->reg_params, mode, nr);
1836                 pmap_insert(env->regs, (void *) reg, proj);
1837                 be_set_constr_single_reg(env->reg_params, pos, reg);
1838                 arch_set_irn_register(env->birg->main_env->arch_env, proj, reg);
1839
1840                 /*
1841                  * If the register is an ignore register,
1842                  * The Proj for that register shall also be ignored during register allocation.
1843                  */
1844                 if(arch_register_type_is(reg, ignore))
1845                         flags |= arch_irn_flags_ignore;
1846
1847                 if(reg == sp)
1848                         flags |= arch_irn_flags_modify_sp;
1849
1850                 be_node_set_flags(env->reg_params, pos, flags);
1851
1852                 DBG((dbg, LEVEL_2, "\tregister save proj #%d -> reg %s\n", nr, reg->name));
1853         }
1854         obstack_free(&env->obst, rm);
1855
1856         /* create a new initial memory proj */
1857         assert(is_Proj(old_mem));
1858         new_mem_proj = new_r_Proj(irg, get_nodes_block(old_mem),
1859                                   new_r_Unknown(irg, mode_T), mode_M,
1860                                   get_Proj_proj(old_mem));
1861         mem = new_mem_proj;
1862
1863         /* Generate the Prologue */
1864         fp_reg  = call->cb->prologue(env->cb, &mem, env->regs);
1865
1866         /* do the stack allocation BEFORE the barrier, or spill code
1867            might be added before it */
1868         env->init_sp = be_abi_reg_map_get(env->regs, sp);
1869         env->init_sp = be_new_IncSP(sp, irg, bl, env->init_sp, BE_STACK_FRAME_SIZE_EXPAND, 0);
1870         be_abi_reg_map_set(env->regs, sp, env->init_sp);
1871
1872         create_barrier(env, bl, &mem, env->regs, 0);
1873
1874         env->init_sp = be_abi_reg_map_get(env->regs, sp);
1875         arch_set_irn_register(env->birg->main_env->arch_env, env->init_sp, sp);
1876
1877         frame_pointer = be_abi_reg_map_get(env->regs, fp_reg);
1878         set_irg_frame(irg, frame_pointer);
1879         pset_insert_ptr(env->ignore_regs, fp_reg);
1880
1881         /* rewire old mem users to new mem */
1882         set_Proj_pred(new_mem_proj, get_Proj_pred(old_mem));
1883         exchange(old_mem, mem);
1884
1885         set_irg_initial_mem(irg, mem);
1886
1887         /* Now, introduce stack param nodes for all parameters passed on the stack */
1888         for(i = 0; i < n_params; ++i) {
1889                 ir_node *arg_proj = args[i];
1890                 ir_node *repl     = NULL;
1891
1892                 if(arg_proj != NULL) {
1893                         be_abi_call_arg_t *arg;
1894                         ir_type *param_type;
1895                         int     nr = get_Proj_proj(arg_proj);
1896                         ir_mode *mode;
1897
1898                         nr         = MIN(nr, n_params);
1899                         arg        = get_call_arg(call, 0, nr);
1900                         param_type = get_method_param_type(method_type, nr);
1901
1902                         if (arg->in_reg) {
1903                                 repl = pmap_get(env->regs, (void *) arg->reg);
1904                         } else if(arg->on_stack) {
1905                                 ir_node *addr = be_new_FrameAddr(sp->reg_class, irg, reg_params_bl, frame_pointer, arg->stack_ent);
1906
1907                                 /* For atomic parameters which are actually used, we create a Load node. */
1908                                 if(is_atomic_type(param_type) && get_irn_n_edges(args[i]) > 0) {
1909                                         ir_mode *mode      = get_type_mode(param_type);
1910                                         ir_mode *load_mode = arg->load_mode;
1911
1912                                         ir_node *load = new_r_Load(irg, reg_params_bl, new_NoMem(), addr, load_mode);
1913                                         set_irn_pinned(load, op_pin_state_floats);
1914                                         repl = new_r_Proj(irg, reg_params_bl, load, load_mode, pn_Load_res);
1915
1916                                         if (mode != load_mode) {
1917                                                 repl = new_r_Conv(irg, reg_params_bl, repl, mode);
1918                                         }
1919                                 } else {
1920                                         /* The stack parameter is not primitive (it is a struct or array),
1921                                          * we thus will create a node representing the parameter's address
1922                                          * on the stack. */
1923                                         repl = addr;
1924                                 }
1925                         }
1926
1927                         assert(repl != NULL);
1928
1929                         /* Beware: the mode of the register parameters is always the mode of the register class
1930                            which may be wrong. Add Conv's then. */
1931                         mode = get_irn_mode(args[i]);
1932                         if (mode != get_irn_mode(repl)) {
1933                                 repl = new_r_Conv(irg, get_irn_n(repl, -1), repl, mode);
1934                         }
1935                         exchange(args[i], repl);
1936                 }
1937         }
1938
1939         /* the arg proj is not needed anymore now and should be only used by the anchor */
1940         assert(get_irn_n_edges(arg_tuple) == 1);
1941         be_kill_node(arg_tuple);
1942         set_irg_args(irg, new_rd_Bad(irg));
1943
1944         /* All Return nodes hang on the End node, so look for them there. */
1945         for (i = 0, n = get_Block_n_cfgpreds(end); i < n; ++i) {
1946                 ir_node *irn = get_Block_cfgpred(end, i);
1947
1948                 if (is_Return(irn)) {
1949                         ir_node *blk = get_nodes_block(irn);
1950                         ir_node *mem = get_Return_mem(irn);
1951                         ir_node *ret = create_be_return(env, irn, blk, mem, get_Return_n_ress(irn));
1952                         exchange(irn, ret);
1953                 }
1954         }
1955         /* if we have endless loops here, n might be <= 0. Do NOT create a be_Return then,
1956            the code is dead and will never be executed. */
1957
1958         del_pset(dont_save);
1959         obstack_free(&env->obst, args);
1960
1961         /* handle start block here (place a jump in the block) */
1962         i = 0;
1963         irg_block_walk_graph(irg, fix_start_block, NULL, &i);
1964 }
1965
1966 /** Fix the state inputs of calls that still hang on unknowns */
1967 static
1968 void fix_call_state_inputs(be_abi_irg_t *env)
1969 {
1970         const arch_env_t *arch_env = env->arch_env;
1971         int i, n, n_states;
1972         arch_register_t **stateregs = NEW_ARR_F(arch_register_t*, 0);
1973
1974         /* Collect caller save registers */
1975         n = arch_env_get_n_reg_class(arch_env);
1976         for(i = 0; i < n; ++i) {
1977                 unsigned j;
1978                 const arch_register_class_t *cls = arch_env_get_reg_class(arch_env, i);
1979                 for(j = 0; j < cls->n_regs; ++j) {
1980                         const arch_register_t *reg = arch_register_for_index(cls, j);
1981                         if(arch_register_type_is(reg, state)) {
1982                                 ARR_APP1(arch_register_t*, stateregs, (arch_register_t *)reg);
1983                         }
1984                 }
1985         }
1986
1987         n = ARR_LEN(env->calls);
1988         n_states = ARR_LEN(stateregs);
1989         for(i = 0; i < n; ++i) {
1990                 int s, arity;
1991                 ir_node *call = env->calls[i];
1992
1993                 arity = get_irn_arity(call);
1994
1995                 /* the state reg inputs are the last n inputs of the calls */
1996                 for(s = 0; s < n_states; ++s) {
1997                         int inp = arity - n_states + s;
1998                         const arch_register_t *reg = stateregs[s];
1999                         ir_node *regnode = be_abi_reg_map_get(env->regs, reg);
2000
2001                         set_irn_n(call, inp, regnode);
2002                 }
2003         }
2004 }
2005
2006 /**
2007  * Create a trampoline entity for the given method.
2008  */
2009 static ir_entity *create_trampoline(be_main_env_t *be, ir_entity *method)
2010 {
2011         ir_type   *type   = get_entity_type(method);
2012         ident     *old_id = get_entity_ld_ident(method);
2013         ident     *id     = mangle3("L", old_id, "$stub");
2014         ir_type   *parent = be->pic_trampolines_type;
2015         ir_entity *ent    = new_entity(parent, old_id, type);
2016         set_entity_ld_ident(ent, id);
2017         set_entity_visibility(ent, visibility_local);
2018         set_entity_variability(ent, variability_uninitialized);
2019
2020         return ent;
2021 }
2022
2023 /**
2024  * Returns the trampoline entity for the given method.
2025  */
2026 static ir_entity *get_trampoline(be_main_env_t *env, ir_entity *method)
2027 {
2028         ir_entity *result = pmap_get(env->ent_trampoline_map, method);
2029         if (result == NULL) {
2030                 result = create_trampoline(env, method);
2031                 pmap_insert(env->ent_trampoline_map, method, result);
2032         }
2033
2034         return result;
2035 }
2036
2037 /**
2038  * Returns non-zero if a given entity can be accessed using a relative address.
2039  */
2040 static int can_address_relative(ir_entity *entity)
2041 {
2042         return get_entity_variability(entity) == variability_initialized
2043                 || get_entity_visibility(entity) == visibility_local;
2044 }
2045
2046 /** patches SymConsts to work in position independent code */
2047 static void fix_pic_symconsts(ir_node *node, void *data)
2048 {
2049         ir_graph     *irg;
2050         ir_node      *pic_base;
2051         ir_node      *add;
2052         ir_node      *block;
2053         ir_node      *unknown;
2054         ir_mode      *mode;
2055         ir_node      *load;
2056         ir_node      *load_res;
2057         be_abi_irg_t *env = data;
2058         int           arity, i;
2059         be_main_env_t *be = env->birg->main_env;
2060
2061         arity = get_irn_arity(node);
2062         for (i = 0; i < arity; ++i) {
2063                 ir_node   *pred = get_irn_n(node, i);
2064                 ir_entity *entity;
2065                 if (!is_SymConst(pred))
2066                         continue;
2067
2068                 entity = get_SymConst_entity(pred);
2069                 block  = get_nodes_block(pred);
2070                 irg    = get_irn_irg(pred);
2071
2072                 /* calls can jump to relative addresses, so we can directly jump to
2073                    the (relatively) known call address or the trampoline */
2074                 if (is_Call(node) && i == 1) {
2075                         dbg_info  *dbgi;
2076                         ir_entity *trampoline;
2077                         ir_node   *trampoline_const;
2078
2079                         if (can_address_relative(entity))
2080                                 continue;
2081
2082                         dbgi             = get_irn_dbg_info(pred);
2083                         trampoline       = get_trampoline(be, entity);
2084                         trampoline_const = new_rd_SymConst_addr_ent(dbgi, irg, mode_P_code, trampoline, NULL);
2085                         set_irn_n(node, i, trampoline_const);
2086                         continue;
2087                 }
2088
2089                 /* everything else is accessed relative to EIP */
2090                 mode     = get_irn_mode(pred);
2091                 unknown  = new_r_Unknown(irg, mode);
2092                 pic_base = arch_code_generator_get_pic_base(env->birg->cg);
2093                 add      = new_r_Add(irg, block, pic_base, pred, mode);
2094
2095                 /* make sure the walker doesn't visit this add again */
2096                 mark_irn_visited(add);
2097
2098                 /* all ok now for locally constructed stuff */
2099                 if (can_address_relative(entity)) {
2100                         set_irn_n(node, i, add);
2101                         continue;
2102                 }
2103
2104                 /* we need an extra indirection for global data outside our current
2105                    module. The loads are always safe and can therefore float
2106                    and need no memory input */
2107                 load     = new_r_Load(irg, block, new_NoMem(), add, mode);
2108                 load_res = new_r_Proj(irg, block, load, mode, pn_Load_res);
2109                 set_irn_pinned(load, op_pin_state_floats);
2110
2111                 set_irn_n(node, i, load_res);
2112         }
2113 }
2114
2115 be_abi_irg_t *be_abi_introduce(be_irg_t *birg)
2116 {
2117         be_abi_irg_t *env  = xmalloc(sizeof(env[0]));
2118         ir_node *old_frame = get_irg_frame(birg->irg);
2119         ir_graph *irg      = birg->irg;
2120
2121         pmap_entry *ent;
2122         ir_node *dummy;
2123         optimization_state_t state;
2124         unsigned *limited_bitset;
2125
2126         be_omit_fp = birg->main_env->options->omit_fp;
2127
2128         obstack_init(&env->obst);
2129
2130         env->arch_env    = birg->main_env->arch_env;
2131         env->method_type = get_entity_type(get_irg_entity(irg));
2132         env->call        = be_abi_call_new(env->arch_env->sp->reg_class);
2133         arch_env_get_call_abi(env->arch_env, env->method_type, env->call);
2134
2135         env->ignore_regs  = pset_new_ptr_default();
2136         env->keep_map     = pmap_create();
2137         env->dce_survivor = new_survive_dce();
2138         env->birg         = birg;
2139
2140         env->sp_req.type    = arch_register_req_type_limited;
2141         env->sp_req.cls     = arch_register_get_class(env->arch_env->sp);
2142         limited_bitset      = rbitset_obstack_alloc(&env->obst, env->sp_req.cls->n_regs);
2143         rbitset_set(limited_bitset, arch_register_get_index(env->arch_env->sp));
2144         env->sp_req.limited = limited_bitset;
2145
2146         env->sp_cls_req.type  = arch_register_req_type_normal;
2147         env->sp_cls_req.cls   = arch_register_get_class(env->arch_env->sp);
2148
2149         /* Beware: later we replace this node by the real one, ensure it is not CSE'd
2150            to another Unknown or the stack pointer gets used */
2151         save_optimization_state(&state);
2152         set_optimize(0);
2153         env->init_sp = dummy  = new_r_Unknown(irg, env->arch_env->sp->reg_class->mode);
2154         restore_optimization_state(&state);
2155         FIRM_DBG_REGISTER(env->dbg, "firm.be.abi");
2156
2157         env->calls = NEW_ARR_F(ir_node*, 0);
2158
2159         if (birg->main_env->options->pic) {
2160                 irg_walk_graph(irg, fix_pic_symconsts, NULL, env);
2161         }
2162
2163         /* Lower all call nodes in the IRG. */
2164         process_calls(env);
2165
2166         /*
2167                 Beware: init backend abi call object after processing calls,
2168                 otherwise some information might be not yet available.
2169         */
2170         env->cb = env->call->cb->init(env->call, birg->main_env->arch_env, irg);
2171
2172         /* Process the IRG */
2173         modify_irg(env);
2174
2175         /* fix call inputs for state registers */
2176         fix_call_state_inputs(env);
2177
2178         /* We don't need the keep map anymore. */
2179         pmap_destroy(env->keep_map);
2180         env->keep_map = NULL;
2181
2182         /* calls array is not needed anymore */
2183         DEL_ARR_F(env->calls);
2184         env->calls = NULL;
2185
2186         /* reroute the stack origin of the calls to the true stack origin. */
2187         exchange(dummy, env->init_sp);
2188         exchange(old_frame, get_irg_frame(irg));
2189
2190         /* Make some important node pointers survive the dead node elimination. */
2191         survive_dce_register_irn(env->dce_survivor, &env->init_sp);
2192         foreach_pmap(env->regs, ent) {
2193                 survive_dce_register_irn(env->dce_survivor, (ir_node **) &ent->value);
2194         }
2195
2196         env->call->cb->done(env->cb);
2197         env->cb = NULL;
2198         return env;
2199 }
2200
2201 void be_abi_free(be_abi_irg_t *env)
2202 {
2203         be_abi_call_free(env->call);
2204         free_survive_dce(env->dce_survivor);
2205         del_pset(env->ignore_regs);
2206         pmap_destroy(env->regs);
2207         obstack_free(&env->obst, NULL);
2208         free(env);
2209 }
2210
2211 void be_abi_put_ignore_regs(be_abi_irg_t *abi, const arch_register_class_t *cls, bitset_t *bs)
2212 {
2213         arch_register_t *reg;
2214
2215         for(reg = pset_first(abi->ignore_regs); reg; reg = pset_next(abi->ignore_regs))
2216                 if(reg->reg_class == cls)
2217                         bitset_set(bs, reg->index);
2218 }
2219
2220 /* Returns the stack layout from a abi environment. */
2221 const be_stack_layout_t *be_abi_get_stack_layout(const be_abi_irg_t *abi) {
2222         return abi->frame;
2223 }
2224
2225 /*
2226
2227   _____ _        ____  _             _
2228  |  ___(_)_  __ / ___|| |_ __ _  ___| | __
2229  | |_  | \ \/ / \___ \| __/ _` |/ __| |/ /
2230  |  _| | |>  <   ___) | || (_| | (__|   <
2231  |_|   |_/_/\_\ |____/ \__\__,_|\___|_|\_\
2232
2233 */
2234
2235 typedef ir_node **node_array;
2236
2237 typedef struct fix_stack_walker_env_t {
2238         node_array sp_nodes;
2239         const arch_env_t *arch_env;
2240 } fix_stack_walker_env_t;
2241
2242 /**
2243  * Walker. Collect all stack modifying nodes.
2244  */
2245 static void collect_stack_nodes_walker(ir_node *node, void *data)
2246 {
2247         fix_stack_walker_env_t *env = data;
2248
2249         if (arch_irn_is(env->arch_env, node, modify_sp)) {
2250                 assert(get_irn_mode(node) != mode_M && get_irn_mode(node) != mode_T);
2251                 ARR_APP1(ir_node*, env->sp_nodes, node);
2252         }
2253 }
2254
2255 void be_abi_fix_stack_nodes(be_abi_irg_t *env)
2256 {
2257         be_ssa_construction_env_t senv;
2258         int i, len;
2259         ir_node **phis;
2260         be_irg_t *birg = env->birg;
2261         be_lv_t *lv = be_get_birg_liveness(birg);
2262         fix_stack_walker_env_t walker_env;
2263
2264         walker_env.sp_nodes = NEW_ARR_F(ir_node*, 0);
2265         walker_env.arch_env = birg->main_env->arch_env;
2266
2267         irg_walk_graph(birg->irg, collect_stack_nodes_walker, NULL, &walker_env);
2268
2269         /* nothing to be done if we didn't find any node, in fact we mustn't
2270          * continue, as for endless loops incsp might have had no users and is bad
2271          * now.
2272          */
2273         len = ARR_LEN(walker_env.sp_nodes);
2274         if(len == 0) {
2275                 DEL_ARR_F(walker_env.sp_nodes);
2276                 return;
2277         }
2278
2279         be_ssa_construction_init(&senv, birg);
2280         be_ssa_construction_add_copies(&senv, walker_env.sp_nodes,
2281                                    ARR_LEN(walker_env.sp_nodes));
2282         be_ssa_construction_fix_users_array(&senv, walker_env.sp_nodes,
2283                                       ARR_LEN(walker_env.sp_nodes));
2284
2285         if(lv != NULL) {
2286                 len = ARR_LEN(walker_env.sp_nodes);
2287                 for(i = 0; i < len; ++i) {
2288                         be_liveness_update(lv, walker_env.sp_nodes[i]);
2289                 }
2290                 be_ssa_construction_update_liveness_phis(&senv, lv);
2291         }
2292
2293         phis = be_ssa_construction_get_new_phis(&senv);
2294
2295         /* set register requirements for stack phis */
2296         len = ARR_LEN(phis);
2297         for(i = 0; i < len; ++i) {
2298                 ir_node *phi = phis[i];
2299                 be_set_phi_reg_req(walker_env.arch_env, phi, &env->sp_req);
2300                 be_set_phi_flags(walker_env.arch_env, phi, arch_irn_flags_ignore | arch_irn_flags_modify_sp);
2301                 arch_set_irn_register(walker_env.arch_env, phi, env->arch_env->sp);
2302         }
2303         be_ssa_construction_destroy(&senv);
2304
2305         DEL_ARR_F(walker_env.sp_nodes);
2306 }
2307
2308 static int process_stack_bias(be_abi_irg_t *env, ir_node *bl, int real_bias)
2309 {
2310         const arch_env_t *arch_env = env->birg->main_env->arch_env;
2311         int               omit_fp  = env->call->flags.bits.try_omit_fp;
2312         ir_node          *irn;
2313         int               wanted_bias = real_bias;
2314
2315         sched_foreach(bl, irn) {
2316                 int ofs;
2317
2318                 /*
2319                    Check, if the node relates to an entity on the stack frame.
2320                    If so, set the true offset (including the bias) for that
2321                    node.
2322                  */
2323                 ir_entity *ent = arch_get_frame_entity(arch_env, irn);
2324                 if(ent) {
2325                         int bias   = omit_fp ? real_bias : 0;
2326                         int offset = get_stack_entity_offset(env->frame, ent, bias);
2327                         arch_set_frame_offset(arch_env, irn, offset);
2328                         DBG((env->dbg, LEVEL_2, "%F has offset %d (including bias %d)\n",
2329                              ent, offset, bias));
2330                 }
2331
2332                 /*
2333                  * If the node modifies the stack pointer by a constant offset,
2334                  * record that in the bias.
2335                  */
2336                 ofs = arch_get_sp_bias(arch_env, irn);
2337
2338                 if(be_is_IncSP(irn)) {
2339                         /* fill in real stack frame size */
2340                         if(ofs == BE_STACK_FRAME_SIZE_EXPAND) {
2341                                 ir_type *frame_type = get_irg_frame_type(env->birg->irg);
2342                                 ofs = (int) get_type_size_bytes(frame_type);
2343                                 be_set_IncSP_offset(irn, ofs);
2344                         } else if(ofs == BE_STACK_FRAME_SIZE_SHRINK) {
2345                                 ir_type *frame_type = get_irg_frame_type(env->birg->irg);
2346                                 ofs = - (int)get_type_size_bytes(frame_type);
2347                                 be_set_IncSP_offset(irn, ofs);
2348                         } else {
2349                                 if (be_get_IncSP_align(irn)) {
2350                                         /* patch IncSP to produce an aligned stack pointer */
2351                                         ir_type *between_type = env->frame->between_type;
2352                                         int      between_size = get_type_size_bytes(between_type);
2353                                         int      alignment    = 1 << env->arch_env->stack_alignment;
2354                                         int      delta        = (real_bias + ofs + between_size) & (alignment - 1);
2355                                         assert(ofs >= 0);
2356                                         if (delta > 0) {
2357                                                 be_set_IncSP_offset(irn, ofs + alignment - delta);
2358                                                 real_bias += alignment - delta;
2359                                         }
2360                                 } else {
2361                                         /* adjust so real_bias corresponds with wanted_bias */
2362                                         int delta = wanted_bias - real_bias;
2363                                         assert(delta <= 0);
2364                                         if(delta != 0) {
2365                                                 be_set_IncSP_offset(irn, ofs + delta);
2366                                                 real_bias += delta;
2367                                         }
2368                                 }
2369                         }
2370                 }
2371
2372                 real_bias   += ofs;
2373                 wanted_bias += ofs;
2374         }
2375
2376         assert(real_bias == wanted_bias);
2377         return real_bias;
2378 }
2379
2380 /**
2381  * A helper struct for the bias walker.
2382  */
2383 struct bias_walk {
2384         be_abi_irg_t *env;     /**< The ABI irg environment. */
2385         int           start_block_bias;  /**< The bias at the end of the start block. */
2386         int           between_size;
2387         ir_node      *start_block;  /**< The start block of the current graph. */
2388 };
2389
2390 /**
2391  * Block-Walker: fix all stack offsets
2392  */
2393 static void stack_bias_walker(ir_node *bl, void *data)
2394 {
2395         struct bias_walk *bw = data;
2396         if (bl != bw->start_block) {
2397                 process_stack_bias(bw->env, bl, bw->start_block_bias);
2398         }
2399 }
2400
2401 void be_abi_fix_stack_bias(be_abi_irg_t *env)
2402 {
2403         ir_graph *irg  = env->birg->irg;
2404         struct bias_walk bw;
2405
2406         stack_frame_compute_initial_offset(env->frame);
2407         // stack_layout_dump(stdout, env->frame);
2408
2409         /* Determine the stack bias at the end of the start block. */
2410         bw.start_block_bias = process_stack_bias(env, get_irg_start_block(irg), 0);
2411         bw.between_size     = get_type_size_bytes(env->frame->between_type);
2412
2413         /* fix the bias is all other blocks */
2414         bw.env = env;
2415         bw.start_block = get_irg_start_block(irg);
2416         irg_block_walk_graph(irg, stack_bias_walker, NULL, &bw);
2417 }
2418
2419 ir_node *be_abi_get_callee_save_irn(be_abi_irg_t *abi, const arch_register_t *reg)
2420 {
2421         assert(arch_register_type_is(reg, callee_save));
2422         assert(pmap_contains(abi->regs, (void *) reg));
2423         return pmap_get(abi->regs, (void *) reg);
2424 }
2425
2426 ir_node *be_abi_get_ignore_irn(be_abi_irg_t *abi, const arch_register_t *reg)
2427 {
2428         assert(arch_register_type_is(reg, ignore));
2429         assert(pmap_contains(abi->regs, (void *) reg));
2430         return pmap_get(abi->regs, (void *) reg);
2431 }
2432
2433 /**
2434  * Returns non-zero if the ABI has omitted the frame pointer in
2435  * the current graph.
2436  */
2437 int be_abi_omit_fp(const be_abi_irg_t *abi) {
2438         return abi->call->flags.bits.try_omit_fp;
2439 }