Fixes
[libfirm] / ir / be / beabi.c
1 /**
2  * ABI lowering.
3  *
4  *
5  *
6  */
7
8 #ifdef HAVE_CONFIG_H
9 # include "config.h"
10 #endif
11 #include "obst.h"
12
13 #include "type.h"
14 #include "survive_dce.h"
15
16 #include "irgraph_t.h"
17 #include "irnode_t.h"
18 #include "ircons_t.h"
19 #include "iredges_t.h"
20 #include "irgmod.h"
21 #include "irgwalk.h"
22 #include "irprintf_t.h"
23
24 #include "be.h"
25 #include "beabi.h"
26 #include "bearch.h"
27 #include "benode_t.h"
28 #include "besched_t.h"
29
30 #define MAX(x, y) ((x) > (y) ? (x) : (y))
31 #define MIN(x, y) ((x) < (y) ? (x) : (y))
32
33 typedef struct _be_abi_call_arg_t {
34         unsigned is_res : 1;
35         unsigned in_reg : 1;
36
37         int pos;
38         const arch_register_t *reg;
39         entity *stack_ent;
40 } be_abi_call_arg_t;
41
42 struct _be_abi_call_t {
43         be_abi_call_flags_t flags;
44         type *between_type;
45         set *params;
46 };
47
48 #define N_FRAME_TYPES 3
49
50 typedef struct _be_stack_frame_t {
51         type *arg_type;
52         type *between_type;
53         type *frame_type;
54
55         type *order[N_FRAME_TYPES];        /**< arg, between and frame types ordered. */
56
57         int initial_offset;
58         int stack_dir;
59 } be_stack_frame_t;
60
61 struct _be_stack_slot_t {
62         struct _be_stack_frame_t *frame;
63         entity *ent;
64 };
65
66 struct _be_abi_irg_t {
67         struct obstack       obst;
68         firm_dbg_module_t    *dbg;            /**< The debugging module. */
69         be_stack_frame_t     *frame;
70         const be_irg_t       *birg;
71         const arch_isa_t     *isa;          /**< The isa. */
72         survive_dce_t        *dce_survivor;
73
74         be_abi_call_t        *call;
75         type                 *method_type;
76
77         ir_node              *init_sp;      /**< The node representing the stack pointer
78                                                                              at the start of the function. */
79
80         ir_node              *reg_params;
81         pmap                 *regs;
82         pset                 *stack_phis;
83         int                  start_block_bias;
84
85         arch_irn_handler_t irn_handler;
86         arch_irn_ops_t     irn_ops;
87 };
88
89 #define abi_offset_of(type,member) ((char *) &(((type *) 0)->member) - (char *) 0)
90 #define abi_get_relative(ptr, member) ((void *) ((char *) (ptr) - abi_offset_of(be_abi_irg_t, member)))
91 #define get_abi_from_handler(ptr) abi_get_relative(ptr, irn_handler)
92 #define get_abi_from_ops(ptr)     abi_get_relative(ptr, irn_ops)
93
94 /* Forward, since be need it in be_abi_introduce(). */
95 static const arch_irn_ops_if_t abi_irn_ops;
96 static const arch_irn_handler_t abi_irn_handler;
97
98 /*
99      _    ____ ___    ____      _ _ _                _
100     / \  | __ )_ _|  / ___|__ _| | | |__   __ _  ___| | _____
101    / _ \ |  _ \| |  | |   / _` | | | '_ \ / _` |/ __| |/ / __|
102   / ___ \| |_) | |  | |__| (_| | | | |_) | (_| | (__|   <\__ \
103  /_/   \_\____/___|  \____\__,_|_|_|_.__/ \__,_|\___|_|\_\___/
104
105   These callbacks are used by the backend to set the parameters
106   for a specific call type.
107 */
108
109 static int cmp_call_arg(const void *a, const void *b, size_t n)
110 {
111         const be_abi_call_arg_t *p = a, *q = b;
112         return !(p->is_res == q->is_res && p->pos == q->pos);
113 }
114
115 static be_abi_call_arg_t *get_or_set_call_arg(be_abi_call_t *call, int is_res, int pos, int do_insert)
116 {
117         be_abi_call_arg_t arg;
118         unsigned hash;
119
120         arg.is_res = is_res;
121         arg.pos    = pos;
122
123         hash = is_res * 100 + pos;
124
125         return do_insert
126                 ? set_insert(call->params, &arg, sizeof(arg), hash)
127                 : set_find(call->params, &arg, sizeof(arg), hash);
128 }
129
130 static INLINE be_abi_call_arg_t *get_call_arg(be_abi_call_t *call, int is_res, int pos)
131 {
132         return get_or_set_call_arg(call, is_res, pos, 0);
133 }
134
135 void be_abi_call_set_flags(be_abi_call_t *call, be_abi_call_flags_t flags, ir_type *between_type)
136 {
137         call->flags            = flags;
138         call->between_type     = between_type;
139 }
140
141 void be_abi_call_param_stack(be_abi_call_t *call, int arg_pos)
142 {
143         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 0, arg_pos, 1);
144 }
145
146 void be_abi_call_param_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg)
147 {
148         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 0, arg_pos, 1);
149         arg->in_reg = 1;
150         arg->reg = reg;
151 }
152
153 void be_abi_call_res_reg(be_abi_call_t *call, int arg_pos, const arch_register_t *reg)
154 {
155         be_abi_call_arg_t *arg = get_or_set_call_arg(call, 1, arg_pos, 1);
156         arg->in_reg = 1;
157         arg->reg = reg;
158 }
159
160 be_abi_call_t *be_abi_call_new(void)
161 {
162         be_abi_call_t *call = malloc(sizeof(call[0]));
163         call->flags.val = 0;
164         call->params    = new_set(cmp_call_arg, 16);
165         return call;
166 }
167
168 void be_abi_call_free(be_abi_call_t *call)
169 {
170         del_set(call->params);
171         free(call);
172 }
173
174 /*
175   _____                           _   _                 _ _ _
176  |  ___| __ __ _ _ __ ___   ___  | | | | __ _ _ __   __| | (_)_ __   __ _
177  | |_ | '__/ _` | '_ ` _ \ / _ \ | |_| |/ _` | '_ \ / _` | | | '_ \ / _` |
178  |  _|| | | (_| | | | | | |  __/ |  _  | (_| | | | | (_| | | | | | | (_| |
179  |_|  |_|  \__,_|_| |_| |_|\___| |_| |_|\__,_|_| |_|\__,_|_|_|_| |_|\__, |
180                                                                     |___/
181
182   Handling of the stack frame. It is composed of three types:
183   1) The type of the arguments which are pushed on the stack.
184   2) The "between type" which consists of stuff the call of the
185      function pushes on the stack (like the return address and
186          the old base pointer for ia32).
187   3) The Firm frame type which consists of all local variables
188      and the spills.
189 */
190
191 static int get_stack_entity_offset(be_stack_frame_t *frame, entity *ent, int bias)
192 {
193         type *t = get_entity_owner(ent);
194         int ofs = get_entity_offset_bytes(ent);
195
196         int i, index;
197
198         /* Find the type the entity is contained in. */
199         for(index = 0; index < N_FRAME_TYPES; ++index) {
200                 if(frame->order[index] == t)
201                         break;
202         }
203
204         /* Add the size of all the types below the one of the entity to the entity's offset */
205         for(i = 0; i < index; ++i)
206                 ofs += get_type_size_bytes(frame->order[i]);
207
208         /* correct the offset by the initial position of the frame pointer */
209         ofs -= frame->initial_offset;
210
211         /* correct the offset with the current bias. */
212         ofs += bias;
213
214         return ofs;
215 }
216
217 static entity *search_ent_with_offset(type *t, int offset)
218 {
219         int i, n;
220
221         for(i = 0, n = get_class_n_members(t); i < n; ++i) {
222                 entity *ent = get_class_member(t, i);
223                 if(get_entity_offset_bytes(ent) == offset)
224                         return ent;
225         }
226
227         return NULL;
228 }
229
230 static int stack_frame_compute_initial_offset(be_stack_frame_t *frame)
231 {
232         type   *base = frame->stack_dir < 0 ? frame->between_type : frame->frame_type;
233         entity *ent  = search_ent_with_offset(base, 0);
234         frame->initial_offset = 0;
235         frame->initial_offset = get_stack_entity_offset(frame, ent, 0);
236         return frame->initial_offset;
237 }
238
239 static be_stack_frame_t *stack_frame_init(be_stack_frame_t *frame, type *args, type *between, type *locals, int stack_dir)
240 {
241         frame->arg_type       = args;
242         frame->between_type   = between;
243         frame->frame_type     = locals;
244         frame->initial_offset = 0;
245         frame->stack_dir      = stack_dir;
246         frame->order[1]       = between;
247
248         if(stack_dir > 0) {
249                 frame->order[0] = args;
250                 frame->order[2] = locals;
251         }
252
253         else {
254                 frame->order[0] = locals;
255                 frame->order[2] = args;
256         }
257
258         return frame;
259 }
260
261 static void stack_frame_dump(FILE *file, be_stack_frame_t *frame)
262 {
263         int i, j, n;
264
265         ir_fprintf(file, "initial offset: %d\n", frame->initial_offset);
266         for(j = 0; j < N_FRAME_TYPES; ++j) {
267                 type *t = frame->order[j];
268
269                 ir_fprintf(file, "type %d: %Fm size: %d\n", j, t, get_type_size_bytes(t));
270                 for(i = 0, n = get_class_n_members(t); i < n; ++i) {
271                         entity *ent = get_class_member(t, i);
272                         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));
273                 }
274         }
275 }
276
277 /**
278  * If irn is a Sel node computing the address of an entity
279  * on the frame type return the entity, else NULL.
280  */
281 static INLINE entity *get_sel_ent(ir_node *irn)
282 {
283         if(get_irn_opcode(irn) == iro_Sel
284                 && get_Sel_ptr(irn) == get_irg_frame(get_irn_irg(irn))) {
285
286                 return get_Sel_entity(irn);
287         }
288
289         return NULL;
290 }
291
292 /**
293  * Walker: Replaces Loads, Stores and Sels of frame type entities
294  * by FrameLoad, FrameStore and FrameAdress.
295  */
296 static void lower_frame_sels_walker(ir_node *irn, void *data)
297 {
298         const arch_register_class_t *cls;
299         be_abi_irg_t *env = data;
300         const arch_isa_t *isa = env->birg->main_env->arch_env->isa;
301         ir_graph *irg = get_irn_irg(irn);
302         ir_node *frame = get_irg_frame(irg);
303         ir_node *nw  = NULL;
304         opcode opc   = get_irn_opcode(irn);
305
306         if(opc == iro_Load) {
307                 ir_node *bl  = get_nodes_block(irn);
308                 ir_node *sel = get_Load_ptr(irn);
309                 entity *ent  = get_sel_ent(sel);
310                 cls = arch_isa_get_reg_class_for_mode(isa, get_Load_mode(irn));
311                 if(ent != NULL)
312                         nw = be_new_FrameLoad(isa->sp->reg_class, cls, irg, bl, get_Load_mem(irn), frame, ent);
313         }
314
315         else if(opc == iro_Store) {
316                 ir_node *bl  = get_nodes_block(irn);
317                 ir_node *val = get_Store_value(irn);
318                 ir_node *sel = get_Store_ptr(irn);
319                 entity *ent  = get_sel_ent(sel);
320                 cls = arch_isa_get_reg_class_for_mode(isa, get_irn_mode(val));
321                 if(ent != NULL)
322                         nw = be_new_FrameStore(isa->sp->reg_class, cls, irg, bl, get_Store_mem(irn), frame, val, ent);
323         }
324
325         else {
326                 entity *ent = get_sel_ent(irn);
327                 if(ent != NULL) {
328                         ir_node *bl  = get_nodes_block(irn);
329                         nw = be_new_FrameAddr(isa->sp->reg_class, irg, bl, frame, ent);
330                 }
331         }
332
333         if(nw != NULL)
334                 exchange(irn, nw);
335 }
336
337 static INLINE int is_on_stack(be_abi_call_t *call, int pos)
338 {
339         be_abi_call_arg_t *arg = get_call_arg(call, 0, pos);
340         return arg && !arg->in_reg;
341 }
342
343 /**
344  * Transform a call node.
345  * @param env The ABI environment for the current irg.
346  * @param irn THe call node.
347  */
348 static void adjust_call(be_abi_irg_t *env, ir_node *irn)
349 {
350         ir_graph *irg             = env->birg->irg;
351         const arch_isa_t *isa     = env->birg->main_env->arch_env->isa;
352         be_abi_call_t *call       = be_abi_call_new();
353         ir_type *mt               = get_Call_type(irn);
354         int n_params              = get_method_n_params(mt);
355         ir_node *curr_sp          = env->init_sp;
356         ir_node *curr_mem         = get_Call_mem(irn);
357         ir_node *bl               = get_nodes_block(irn);
358         pset *results             = pset_new_ptr(8);
359         pset *caller_save         = pset_new_ptr(8);
360         int stack_size            = 0;
361         int stack_dir             = arch_isa_stack_dir(isa);
362         const arch_register_t *sp = arch_isa_sp(isa);
363         ir_mode *mach_mode        = sp->reg_class->mode;
364         struct obstack *obst      = &env->obst;
365         ir_node *no_mem           = get_irg_no_mem(irg);
366
367         ir_node *res_proj = NULL;
368         int curr_res_proj = -1;
369         int n_low_args    = 0;
370         int n_pos         = 0;
371
372         ir_node *low_call;
373         ir_node **in;
374         ir_node *sp_proj;
375         const ir_edge_t *edge;
376         int *low_args;
377         int *pos;
378         int i, n;
379
380         /* Let the isa fill out the abi description for that call node. */
381         arch_isa_get_call_abi(isa, mt, call);
382
383         /* Insert code to put the stack arguments on the stack. */
384         assert(get_Call_n_params(irn) == n_params);
385         for(i = 0; i < n_params; ++i) {
386                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
387                 assert(arg);
388                 if(!arg->in_reg) {
389                         stack_size += get_type_size_bytes(get_method_param_type(mt, i));
390                         obstack_int_grow(obst, i);
391                         n_pos++;
392                 }
393         }
394         pos = obstack_finish(obst);
395
396         /* Collect all arguments which are passed in registers. */
397         for(i = 0, n = get_Call_n_params(irn); i < n; ++i) {
398                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
399                 if(arg && arg->in_reg) {
400                         obstack_int_grow(obst, i);
401                         n_low_args++;
402                 }
403         }
404         low_args = obstack_finish(obst);
405
406         /* If there are some parameters which shall be passed on the stack. */
407         if(n_pos > 0) {
408                 int curr_ofs      = 0;
409                 int do_seq        = call->flags.bits.store_args_sequential;
410
411                 /* Reverse list of stack parameters if call arguments are from left to right */
412                 if(call->flags.bits.left_to_right) {
413                         for(i = 0; i < n_pos / 2; ++i) {
414                                 int other  = n_pos - i - 1;
415                                 int tmp    = pos[i];
416                                 pos[i]     = pos[other];
417                                 pos[other] = tmp;
418                         }
419                 }
420
421                 /*
422                  * If the stack is decreasing and we do not want to store sequentially,
423                  * we allocate as much space on the stack all parameters need, by
424                  * moving the stack pointer along the stack's direction.
425                  */
426                 if(stack_dir < 0 && !do_seq) {
427                         curr_sp = be_new_IncSP(sp, irg, bl, curr_sp, no_mem, stack_size, be_stack_dir_along);
428                 }
429
430                 assert(mode_is_reference(mach_mode) && "machine mode must be pointer");
431                 for(i = 0; i < n_pos; ++i) {
432                         int p            = pos[i];
433                         ir_node *param   = get_Call_param(irn, p);
434                         ir_node *addr    = curr_sp;
435                         ir_node *mem     = NULL;
436                         type *param_type = get_method_param_type(mt, p);
437                         int param_size   = get_type_size_bytes(param_type);
438
439                         /* Make the expression to compute the argument's offset. */
440                         if(curr_ofs > 0) {
441                                 addr = new_r_Const_long(irg, bl, mode_Is, curr_ofs);
442                                 addr = new_r_Add(irg, bl, curr_sp, addr, mach_mode);
443                         }
444
445                         /* Insert a store for primitive arguments. */
446                         if(is_atomic_type(param_type)) {
447                                 mem = new_r_Store(irg, bl, curr_mem, addr, param);
448                                 mem = new_r_Proj(irg, bl, mem, mode_M, pn_Store_M);
449                         }
450
451                         /* Make a memcopy for compound arguments. */
452                         else {
453                                 assert(mode_is_reference(get_irn_mode(param)));
454                                 mem = new_r_CopyB(irg, bl, curr_mem, addr, param, param_type);
455                                 mem = new_r_Proj(irg, bl, mem, mode_M, pn_CopyB_M_regular);
456                         }
457
458                         obstack_ptr_grow(obst, mem);
459
460                         curr_ofs += param_size;
461
462                         /*
463                         * If we wanted to build the arguments sequentially,
464                         * the stack pointer for the next must be incremented,
465                         * and the memory value propagated.
466                         */
467                         if(do_seq) {
468                                 curr_ofs = 0;
469                                 curr_sp  = be_new_IncSP(sp, irg, bl, curr_sp, no_mem, param_size, be_stack_dir_along);
470                                 curr_mem = mem;
471                         }
472                 }
473
474                 in = (ir_node **) obstack_finish(obst);
475
476                 /* We need the sync only, if we didn't build the stores sequentially. */
477                 if(!do_seq)
478                         curr_mem = new_r_Sync(irg, bl, n_pos, in);
479                 obstack_free(obst, in);
480         }
481
482         /* Collect caller save registers */
483         for(i = 0, n = arch_isa_get_n_reg_class(isa); i < n; ++i) {
484                 int j;
485                 const arch_register_class_t *cls = arch_isa_get_reg_class(isa, i);
486                 for(j = 0; j < cls->n_regs; ++j) {
487                         const arch_register_t *reg = arch_register_for_index(cls, j);
488                         if(arch_register_type_is(reg, caller_save))
489                                 pset_insert_ptr(caller_save, (void *) reg);
490                 }
491         }
492
493         /* search the greatest result proj number */
494         foreach_out_edge(irn, edge) {
495                 const ir_edge_t *res_edge;
496                 ir_node *irn = get_edge_src_irn(edge);
497
498                 if(is_Proj(irn) && get_irn_mode(irn) == mode_T) {
499                         res_proj = irn;
500                         foreach_out_edge(irn, res_edge) {
501                                 int proj;
502                                 be_abi_call_arg_t *arg;
503                                 ir_node *res = get_edge_src_irn(res_edge);
504
505                                 assert(is_Proj(res));
506                                 proj = get_Proj_proj(res);
507                                 arg = get_call_arg(call, 1, proj);
508                                 if(proj > curr_res_proj)
509                                         curr_res_proj = proj;
510                                 if(arg->in_reg)
511                                         pset_remove_ptr(caller_save, arg->reg);
512                         }
513                 }
514         }
515         curr_res_proj++;
516
517         /* make the back end call node and set its register requirements. */
518         for(i = 0; i < n_low_args; ++i)
519                 obstack_ptr_grow(obst, get_Call_param(irn, low_args[i]));
520
521         in = obstack_finish(obst);
522         low_call = be_new_Call(irg, bl, curr_mem, curr_sp, get_Call_ptr(irn), curr_res_proj, n_low_args, in);
523         obstack_free(obst, in);
524         exchange(irn, low_call);
525
526         /* Make additional projs for the caller save registers
527            and the Keep node which keeps them alive. */
528         if(pset_count(caller_save) > 0) {
529                 const arch_register_t *reg;
530                 ir_node **in, *keep;
531                 int i, n;
532
533                 if(!res_proj)
534                         res_proj = new_r_Proj(irg, bl, low_call, mode_T, pn_Call_T_result);
535
536                 for(reg = pset_first(caller_save), n = 0; reg; reg = pset_next(caller_save), ++n) {
537                         ir_node *proj = new_r_Proj(irg, bl, res_proj, reg->reg_class->mode, curr_res_proj++);
538
539                         /* memorize the register in the link field. we need afterwards to set the register class of the keep correctly. */
540                         set_irn_link(proj, (void *) reg);
541                         obstack_ptr_grow(obst, proj);
542                 }
543
544                 in   = (ir_node **) obstack_finish(obst);
545                 keep = be_new_Keep(NULL, irg, bl, n, in);
546                 for(i = 0; i < n; ++i) {
547                         const arch_register_t *reg = get_irn_link(in[i]);
548                         be_node_set_reg_class(keep, i, reg->reg_class);
549                 }
550                 obstack_free(obst, in);
551         }
552
553         /* Clean up the stack. */
554         if(stack_size > 0) {
555                 ir_node *last_inc_sp;
556
557                 /* Get the result ProjT */
558                 if(!res_proj)
559                         res_proj = new_r_Proj(irg, bl, low_call, mode_T, pn_Call_T_result);
560
561                 /* Make a Proj for the stack pointer. */
562                 sp_proj     = new_r_Proj(irg, bl, res_proj, sp->reg_class->mode, curr_res_proj++);
563                 last_inc_sp = be_new_IncSP(sp, irg, bl, sp_proj, no_mem, stack_size, be_stack_dir_against);
564         }
565
566         be_abi_call_free(call);
567         obstack_free(obst, pos);
568         del_pset(results);
569         del_pset(caller_save);
570 }
571
572 static void adjust_call_walker(ir_node *irn, void *data)
573 {
574         if(get_irn_opcode(irn) == iro_Call)
575                 adjust_call(data, irn);
576 }
577
578 /**
579  * Walker to implement alloca-style allocations.
580  * They are implemented using an add to the stack pointer
581  * and a copy instruction.
582  */
583 static void implement_stack_alloc(be_abi_irg_t *env, ir_node *irn)
584 {
585         const arch_isa_t *isa = env->birg->main_env->arch_env->isa;
586         ir_node *bl           = get_nodes_block(irn);
587         ir_node *res          = env->init_sp;
588         ir_node *size;
589
590         assert(get_irn_opcode(irn) == iro_Alloc && get_Alloc_where(irn) == stack_alloc);
591
592         size = get_Alloc_size(irn);
593         if(isa->stack_dir > 0)
594                 res = be_new_Copy(isa->sp->reg_class, env->birg->irg, bl, res);
595
596         res = be_new_AddSP(isa->sp, env->birg->irg, bl, res, size);
597
598         if(isa->stack_dir < 0)
599                 res = be_new_Copy(isa->sp->reg_class, env->birg->irg, bl, res);
600
601 }
602
603 static void collect_return_walker(ir_node *irn, void *data)
604 {
605         if(get_irn_opcode(irn) == iro_Return) {
606                 struct obstack *obst = data;
607                 obstack_ptr_grow(obst, irn);
608         }
609 }
610
611 static ir_node *setup_frame(be_abi_irg_t *env)
612 {
613         const arch_isa_t *isa = env->birg->main_env->arch_env->isa;
614         const arch_register_t *sp = isa->sp;
615         const arch_register_t *bp = isa->bp;
616         be_abi_call_flags_bits_t flags = env->call->flags.bits;
617         ir_graph *irg      = env->birg->irg;
618         ir_node *bl        = get_irg_start_block(irg);
619         ir_node *no_mem    = get_irg_no_mem(irg);
620         ir_node *old_frame = get_irg_frame(irg);
621         ir_node *stack     = pmap_get(env->regs, (void *) sp);
622         ir_node *frame     = pmap_get(env->regs, (void *) bp);
623
624         int stack_nr       = get_Proj_proj(stack);
625
626         if(flags.try_omit_fp) {
627                 stack = be_new_IncSP(sp, irg, bl, stack, no_mem, BE_STACK_FRAME_SIZE, be_stack_dir_along);
628                 frame = stack;
629         }
630
631         else {
632                 frame = be_new_Copy(bp->reg_class, irg, bl, stack);
633
634                 be_node_set_flags(frame, -1, arch_irn_flags_dont_spill);
635                 if(!flags.fp_free) {
636                         be_set_constr_single_reg(frame, -1, bp);
637                         be_node_set_flags(frame, -1, arch_irn_flags_ignore);
638                         arch_set_irn_register(env->birg->main_env->arch_env, frame, bp);
639                 }
640
641                 stack = be_new_IncSP(sp, irg, bl, stack, frame, BE_STACK_FRAME_SIZE, be_stack_dir_along);
642         }
643
644         be_node_set_flags(env->reg_params, -(stack_nr + 1), arch_irn_flags_ignore);
645         env->init_sp = stack;
646         set_irg_frame(irg, frame);
647         edges_reroute(old_frame, frame, irg);
648
649         return frame;
650 }
651
652 static void clearup_frame(be_abi_irg_t *env, ir_node *ret, struct obstack *obst)
653 {
654         const arch_isa_t *isa = env->birg->main_env->arch_env->isa;
655         const arch_register_t *sp = isa->sp;
656         const arch_register_t *bp = isa->bp;
657         ir_graph *irg      = env->birg->irg;
658         ir_node *no_mem    = get_irg_no_mem(irg);
659         ir_node *frame     = get_irg_frame(irg);
660         ir_node *stack     = env->init_sp;
661         ir_node *bl        = get_nodes_block(ret);
662
663         pmap_entry *ent;
664
665         if(env->call->flags.bits.try_omit_fp) {
666                 stack = be_new_IncSP(sp, irg, bl, stack, no_mem, BE_STACK_FRAME_SIZE, be_stack_dir_against);
667         }
668
669         else {
670                 stack = be_new_SetSP(sp, irg, bl, stack, frame, get_Return_mem(ret));
671                 be_set_constr_single_reg(stack, -1, sp);
672                 be_node_set_flags(stack, -1, arch_irn_flags_ignore);
673         }
674
675         pmap_foreach(env->regs, ent) {
676                 const arch_register_t *reg = ent->key;
677                 ir_node *irn               = ent->value;
678
679                 if(reg == sp)
680                         irn = stack;
681                 else if(reg == bp)
682                         irn = frame;
683
684                 obstack_ptr_grow(obst, irn);
685         }
686 }
687
688 static ir_type *compute_arg_type(be_abi_irg_t *env, be_abi_call_t *call, ir_type *method_type)
689 {
690         int dir  = env->call->flags.bits.left_to_right ? 1 : -1;
691         int inc  = env->birg->main_env->arch_env->isa->stack_dir * dir;
692         int n    = get_method_n_params(method_type);
693         int curr = inc > 0 ? 0 : n - 1;
694         int ofs  = 0;
695
696         char buf[128];
697         ir_type *res;
698         int i;
699
700         snprintf(buf, sizeof(buf), "%s_arg_type", get_entity_name(get_irg_entity(env->birg->irg)));
701         res = new_type_class(new_id_from_str(buf));
702
703         for(i = 0; i < n; ++i, curr += inc) {
704                 type *param_type       = get_method_param_type(method_type, curr);
705                 be_abi_call_arg_t *arg = get_call_arg(call, 0, curr);
706
707                 if(!arg->in_reg) {
708                         snprintf(buf, sizeof(buf), "param_%d", i);
709                         arg->stack_ent = new_entity(res, new_id_from_str(buf), param_type);
710                         set_entity_offset_bytes(arg->stack_ent, ofs);
711                         ofs += get_type_size_bytes(param_type);
712                 }
713         }
714
715         set_type_size_bytes(res, ofs);
716         return res;
717 }
718
719 static type *get_bp_type(const arch_register_t *bp)
720 {
721         static type *bp_type = NULL;
722         if(!bp_type) {
723                 bp_type = new_type_primitive(new_id_from_str("bp_type"), bp->reg_class->mode);
724                 set_type_size_bytes(bp_type, get_mode_size_bytes(bp->reg_class->mode));
725         }
726         return bp_type;
727 }
728
729 /**
730  * Modify the irg itself and the frame type.
731  */
732 static void modify_irg(be_abi_irg_t *env)
733 {
734         firm_dbg_module_t *dbg    = env->dbg;
735         be_abi_call_t *call       = be_abi_call_new();
736         const arch_isa_t *isa     = env->birg->main_env->arch_env->isa;
737         const arch_register_t *sp = arch_isa_sp(isa);
738         ir_graph *irg             = env->birg->irg;
739         ir_node *bl               = get_irg_start_block(irg);
740         ir_node *end              = get_irg_end_block(irg);
741         ir_node *arg_tuple        = get_irg_args(irg);
742         ir_node *no_mem           = get_irg_no_mem(irg);
743         type *method_type         = get_entity_type(get_irg_entity(irg));
744         int n_params              = get_method_n_params(method_type);
745         int max_arg               = 0;
746         int reg_params_nr         = 0;
747         int arg_offset            = 0;
748
749         int i, j, n;
750
751         ir_node *frame_pointer;
752         ir_node *reg_params_bl;
753         ir_node **args, **args_repl;
754         const ir_edge_t *edge;
755         ir_type *arg_type;
756
757         pmap_entry *ent;
758
759         DBG((dbg, LEVEL_1, "introducing abi on %+F\n", irg));
760
761         /* Convert the Sel nodes in the irg to frame load/store/addr nodes. */
762         irg_walk_graph(irg, lower_frame_sels_walker, NULL, env);
763
764         env->frame = obstack_alloc(&env->obst, sizeof(env->frame[0]));
765         env->regs  = pmap_create();
766
767         /* Find the maximum proj number of the argument tuple proj */
768         foreach_out_edge(arg_tuple, edge)  {
769                 ir_node *irn = get_edge_src_irn(edge);
770                 int nr       = get_Proj_proj(irn);
771                 max_arg      = MAX(max_arg, nr);
772         }
773         max_arg += 1;
774         args      = obstack_alloc(&env->obst, max_arg * sizeof(args[0]));
775         args_repl = obstack_alloc(&env->obst, max_arg * sizeof(args[0]));
776         memset(args, 0, max_arg * sizeof(args[0]));
777         memset(args_repl, 0, max_arg * sizeof(args[0]));
778
779         /* Fill the argument vector */
780         foreach_out_edge(arg_tuple, edge) {
781                 ir_node *irn = get_edge_src_irn(edge);
782                 int nr       = get_Proj_proj(irn);
783                 args[nr]     = irn;
784                 DBG((dbg, LEVEL_2, "\treading arg: %d -> %+F\n", nr, irn));
785         }
786
787         /* Get the ABI constraints from the ISA */
788         arch_isa_get_call_abi(isa, method_type, call);
789
790         arg_type     = compute_arg_type(env, call, method_type);
791         stack_frame_init(env->frame, arg_type, call->between_type, get_irg_frame_type(irg), isa->stack_dir);
792
793         /* Count the register params and add them to the number of Projs for the RegParams node */
794         for(i = 0; i < n_params; ++i) {
795                 be_abi_call_arg_t *arg = get_call_arg(call, 0, i);
796                 if(arg->in_reg) {
797                         assert(arg->reg != sp && "cannot use stack pointer as parameter register");
798                         pmap_insert(env->regs, (void *) arg->reg, NULL);
799                         DBG((dbg, LEVEL_2, "\targ #%d -> reg %s\n", i, arg->reg->name));
800                 }
801         }
802
803         /* Collect all callee-save registers */
804         for(i = 0, n = arch_isa_get_n_reg_class(isa); i < n; ++i) {
805                 const arch_register_class_t *cls = arch_isa_get_reg_class(isa, i);
806                 for(j = 0; j < cls->n_regs; ++j) {
807                         const arch_register_t *reg = &cls->regs[j];
808                         if(arch_register_type_is(reg, callee_save))
809                                 pmap_insert(env->regs, (void *) reg, NULL);
810                 }
811         }
812
813         pmap_insert(env->regs, (void *) sp, NULL);
814         pmap_insert(env->regs, (void *) isa->bp, NULL);
815         reg_params_nr   = 0;
816         reg_params_bl   = get_irg_start_block(irg);
817         env->reg_params = be_new_RegParams(irg, reg_params_bl, pmap_count(env->regs));
818
819         /*
820          * make proj nodes for the callee save registers.
821          * memorize them, since Return nodes get those as inputs.
822          */
823         for(ent = pmap_first(env->regs); ent; ent = pmap_next(env->regs)) {
824                 arch_register_t *reg = ent->key;
825                 int pos = -(reg_params_nr + 1);
826                 ent->value = new_r_Proj(irg, reg_params_bl, env->reg_params, reg->reg_class->mode, reg_params_nr);
827                 be_set_constr_single_reg(env->reg_params, pos, reg);
828                 arch_set_irn_register(env->birg->main_env->arch_env, ent->value, reg);
829
830                 /*
831                  * If the register is an ignore register,
832                  * The Proj for that register shall also be ignored during register allocation.
833                  */
834                 if(arch_register_type_is(reg, ignore))
835                         be_node_set_flags(env->reg_params, pos, arch_irn_flags_ignore);
836
837                 reg_params_nr++;
838
839                 DBG((dbg, LEVEL_2, "\tregister save proj #%d -> reg %s\n", reg_params_nr - 1, reg->name));
840         }
841
842         /* Insert the code to set up the stack frame */
843         frame_pointer = setup_frame(env);
844
845         /* Now, introduce stack param nodes for all parameters passed on the stack */
846         for(i = 0; i < max_arg; ++i) {
847                 ir_node *arg_proj = args[i];
848                 if(arg_proj != NULL) {
849                         be_abi_call_arg_t *arg;
850                         ir_type *param_type;
851                         int nr = get_Proj_proj(arg_proj);
852
853                         nr         = MIN(nr, n_params);
854                         arg        = get_call_arg(call, 0, nr);
855                         param_type = get_method_param_type(method_type, nr);
856
857                         if(arg->in_reg) {
858                                 args_repl[i] = new_r_Proj(irg, reg_params_bl, env->reg_params, get_irn_mode(arg_proj), reg_params_nr);
859                                 be_set_constr_single_reg(env->reg_params, -(reg_params_nr + 1), arg->reg);
860                                 reg_params_nr++;
861                         }
862
863                         /* when the (stack) parameter is primitive, we insert a StackParam
864                         node representing the load of that parameter */
865                         else {
866
867                                 /* For atomic parameters which are actually used, we create a StackParam node. */
868                                 if(is_atomic_type(param_type) && get_irn_n_edges(args[i]) > 0) {
869                                         ir_mode *mode                    = get_type_mode(param_type);
870                                         const arch_register_class_t *cls = arch_isa_get_reg_class_for_mode(isa, mode);
871                                         args_repl[i] = be_new_StackParam(cls, isa->bp->reg_class, irg, reg_params_bl, mode, frame_pointer, arg->stack_ent);
872                                 }
873
874                                 /* The stack parameter is not primitive (it is a struct or array),
875                                 we thus will create a node representing the parameter's address
876                                 on the stack. */
877                                 else {
878                                         args_repl[i] = be_new_FrameAddr(sp->reg_class, irg, reg_params_bl, frame_pointer, arg->stack_ent);
879                                 }
880                         }
881                 }
882         }
883
884         /* reroute the edges from the original argument projs to the RegParam ones. */
885         for(i = 0; i < max_arg; ++i) {
886                 if(args[i] != NULL) {
887                         assert(args_repl[i] != NULL);
888                         edges_reroute(args[i], args_repl[i], irg);
889                 }
890         }
891
892         /* All Return nodes hang on the End node, so look for them there. */
893         for(i = 0, n = get_irn_arity(end); i < n; ++i) {
894                 ir_node *irn = get_irn_n(end, i);
895
896                 if(get_irn_opcode(irn) == iro_Return) {
897                         ir_node *bl   = get_nodes_block(irn);
898                         int n_res     = get_Return_n_ress(irn);
899                         pmap *reg_map = pmap_create_ex(n_res);
900                         ir_node *ret;
901                         int i, n;
902                         ir_node **in;
903
904                         /* collect all arguments of the return */
905                         obstack_ptr_grow(&env->obst, get_Return_mem(irn));
906                         for(i = 0; i < n_res; ++i) {
907                                 ir_node *res           = get_Return_res(irn, i);
908                                 be_abi_call_arg_t *arg = get_call_arg(call, 1, i);
909
910                                 assert(arg->in_reg && "return value must be passed in register");
911                                 pmap_insert(reg_map, res, (void *) arg->reg);
912                                 obstack_ptr_grow(&env->obst, res);
913                         }
914
915                         /* generate the clean up code and add additional parameters to the return. */
916                         clearup_frame(env, irn, &env->obst);
917
918                         /* The in array for the new back end return is now ready. */
919                         n   = obstack_object_size(&env->obst) / sizeof(in[0]);
920                         in  = obstack_finish(&env->obst);
921                         ret = be_new_Return(irg, bl, n, in);
922
923                         /* Set the constraints for some arguments of the return. */
924                         for(i = 0; i < n; i++) {
925                                 const arch_register_t *reg = pmap_get(reg_map, in[i]);
926                                 if(reg != NULL)
927                                         be_set_constr_single_reg(ret, i, reg);
928                         }
929                         exchange(irn, ret);
930                         obstack_free(&env->obst, in);
931                         pmap_destroy(reg_map);
932                 }
933         }
934
935         obstack_free(&env->obst, args);
936         be_abi_call_free(call);
937 }
938
939 /**
940  * Walker: puts all Alloc(stack_alloc) on a obstack
941  */
942 static void collect_alloca_walker(ir_node *irn, void *data)
943 {
944         be_abi_irg_t *env = data;
945         if(get_irn_opcode(irn) == iro_Alloc && get_Alloc_where(irn) == stack_alloc)
946                 obstack_ptr_grow(&env->obst, irn);
947 }
948
949 be_abi_irg_t *be_abi_introduce(be_irg_t *birg)
950 {
951         be_abi_irg_t *env = malloc(sizeof(env[0]));
952
953         int i;
954         ir_node **stack_allocs;
955         pmap_entry *ent;
956
957         env->isa           = birg->main_env->arch_env->isa;
958         env->method_type   = get_entity_type(get_irg_entity(birg->irg));
959         env->call          = be_abi_call_new();
960         arch_isa_get_call_abi(env->isa, env->method_type, env->call);
961
962         env->dce_survivor  = new_survive_dce();
963         env->birg          = birg;
964         env->dbg           = firm_dbg_register("firm.be.abi");
965         env->stack_phis    = pset_new_ptr_default();
966         obstack_init(&env->obst);
967
968         memcpy(&env->irn_handler, &abi_irn_handler, sizeof(abi_irn_handler));
969         env->irn_ops.impl = &abi_irn_ops;
970
971         /* search for stack allocation nodes and record them */
972         irg_walk_graph(env->birg->irg, collect_alloca_walker, NULL, env);
973         obstack_ptr_grow(&env->obst, NULL);
974         stack_allocs = obstack_finish(&env->obst);
975
976         /* If there are stack allocations in the irg, we need a frame pointer */
977         if(stack_allocs[0] != NULL)
978                 env->call->flags.bits.try_omit_fp = 0;
979
980         modify_irg(env);
981
982         /* Make some important node pointers survive the dead node elimination. */
983         survive_dce_register_irn(env->dce_survivor, &env->init_sp);
984         for(ent = pmap_first(env->regs); ent; ent = pmap_next(env->regs))
985                 survive_dce_register_irn(env->dce_survivor, (ir_node **) &ent->value);
986
987         /* Fix the alloca-style allocations */
988         for(i = 0; stack_allocs[i] != NULL; ++i)
989                 implement_stack_alloc(env, stack_allocs[i]);
990
991         /* Lower all call nodes in the IRG. */
992         irg_walk_graph(env->birg->irg, NULL, adjust_call_walker, env);
993
994         arch_env_push_irn_handler(env->birg->main_env->arch_env, &env->irn_handler);
995
996         return env;
997 }
998
999 static void collect_stack_nodes(ir_node *irn, void *data)
1000 {
1001         pset *s = data;
1002
1003         switch(be_get_irn_opcode(irn)) {
1004         case beo_IncSP:
1005         case beo_AddSP:
1006         case beo_SetSP:
1007                 pset_insert_ptr(s, irn);
1008         default:
1009                 break;
1010         }
1011 }
1012
1013 void be_abi_fix_stack_nodes(be_abi_irg_t *env)
1014 {
1015         dom_front_info_t *df;
1016         pset *stack_ops;
1017
1018         /* We need dominance frontiers for fix up */
1019         df = be_compute_dominance_frontiers(env->birg->irg);
1020
1021         stack_ops = pset_new_ptr_default();
1022         pset_insert_ptr(stack_ops, env->init_sp);
1023         irg_walk_graph(env->birg->irg, collect_stack_nodes, NULL, stack_ops);
1024         be_ssa_constr_set_phis(df, stack_ops, env->stack_phis);
1025         del_pset(stack_ops);
1026
1027         /* free these dominance frontiers */
1028         be_free_dominance_frontiers(df);
1029 }
1030
1031 /**
1032  * Translates a direction of an IncSP node (either be_stack_dir_against, or ...along)
1033  * into -1 or 1, respectively.
1034  * @param irn The node.
1035  * @return 1, if the direction of the IncSP was along, -1 if against.
1036  */
1037 static int get_dir(ir_node *irn)
1038 {
1039         return 1 - 2 * (be_get_IncSP_direction(irn) == be_stack_dir_against);
1040 }
1041
1042 static int process_stack_bias(be_abi_irg_t *env, ir_node *bl, int bias)
1043 {
1044         const arch_env_t *aenv = env->birg->main_env->arch_env;
1045         ir_node *irn;
1046         int start_bias = bias;
1047         int omit_fp    = env->call->flags.bits.try_omit_fp;
1048
1049         sched_foreach(bl, irn) {
1050
1051                 /*
1052                         If the node modifies the stack pointer by a constant offset,
1053                         record that in the bias.
1054                 */
1055                 if(be_is_IncSP(irn)) {
1056                         int ofs = be_get_IncSP_offset(irn);
1057                         int dir = get_dir(irn);
1058
1059                         if(ofs == BE_STACK_FRAME_SIZE) {
1060                                 ofs = get_type_size_bytes(get_irg_frame_type(env->birg->irg));
1061                                 be_set_IncSP_offset(irn, ofs);
1062                         }
1063
1064                         if(omit_fp)
1065                                 bias += dir * ofs;
1066                 }
1067
1068                 /*
1069                         Else check, if the node relates to an entity on the stack frame.
1070                         If so, set the true offset (including the bias) for that
1071                         node.
1072                 */
1073                 else {
1074                         entity *ent = arch_get_frame_entity(aenv, irn);
1075                         if(ent) {
1076                                 int offset = get_stack_entity_offset(env->frame, ent, bias);
1077                                 arch_set_frame_offset(aenv, irn, offset);
1078                                 DBG((env->dbg, LEVEL_2, "%F has offset %d\n", ent, offset));
1079                         }
1080                 }
1081         }
1082
1083         return bias;
1084 }
1085
1086 /**
1087  * A helper struct for the bias walker.
1088  */
1089 struct bias_walk {
1090         be_abi_irg_t *env;     /**< The ABI irg environment. */
1091         int start_block_bias;  /**< The bias at the end of the start block. */
1092 };
1093
1094 static void stack_bias_walker(ir_node *bl, void *data)
1095 {
1096         if(bl != get_irg_start_block(get_irn_irg(bl))) {
1097                 struct bias_walk *bw = data;
1098                 process_stack_bias(bw->env, bl, bw->start_block_bias);
1099         }
1100 }
1101
1102 void be_abi_fix_stack_bias(be_abi_irg_t *env)
1103 {
1104         ir_graph *irg  = env->birg->irg;
1105         struct bias_walk bw;
1106
1107         stack_frame_compute_initial_offset(env->frame);
1108         stack_frame_dump(stdout, env->frame);
1109
1110         /* Determine the stack bias at the and of the start block. */
1111         bw.start_block_bias = process_stack_bias(env, get_irg_start_block(irg), 0);
1112
1113         /* fix the bias is all other blocks */
1114         bw.env = env;
1115         irg_block_walk_graph(irg, stack_bias_walker, NULL, &bw);
1116 }
1117
1118 void be_abi_free(be_abi_irg_t *env)
1119 {
1120         free_survive_dce(env->dce_survivor);
1121         del_pset(env->stack_phis);
1122         pmap_destroy(env->regs);
1123         obstack_free(&env->obst, NULL);
1124         arch_env_pop_irn_handler(env->birg->main_env->arch_env);
1125         free(env);
1126 }
1127
1128 ir_node *be_abi_get_callee_save_irn(be_abi_irg_t *abi, const arch_register_t *reg)
1129 {
1130         assert(arch_register_type_is(reg, callee_save));
1131         assert(pmap_contains(abi->regs, (void *) reg));
1132         return pmap_get(abi->regs, (void *) reg);
1133 }
1134
1135 /*
1136   _____ _____  _   _   _    _                 _ _
1137  |_   _|  __ \| \ | | | |  | |               | | |
1138    | | | |__) |  \| | | |__| | __ _ _ __   __| | | ___ _ __
1139    | | |  _  /| . ` | |  __  |/ _` | '_ \ / _` | |/ _ \ '__|
1140   _| |_| | \ \| |\  | | |  | | (_| | | | | (_| | |  __/ |
1141  |_____|_|  \_\_| \_| |_|  |_|\__,_|_| |_|\__,_|_|\___|_|
1142
1143   for Phi nodes which are created due to stack modifying nodes
1144   such as IncSP, AddSP and SetSP.
1145
1146   These Phis are always to be ignored by the reg alloc and are
1147   fixed on the SP register of the ISA.
1148 */
1149
1150 static const arch_irn_ops_t *abi_get_irn_ops(const arch_irn_handler_t *handler, const ir_node *irn)
1151 {
1152         const be_abi_irg_t *abi = get_abi_from_handler(handler);
1153         return is_Phi(irn) && pset_find_ptr(abi->stack_phis, (void *) irn) != NULL ? &abi->irn_ops : NULL;
1154 }
1155
1156 static void be_abi_limited(bitset_t *bs, void *data)
1157 {
1158         be_abi_irg_t *abi = data;
1159         bitset_clear_all(bs);
1160         bitset_set(bs, abi->isa->sp->index);
1161 }
1162
1163 static const arch_register_req_t *abi_get_irn_reg_req(const void *self, arch_register_req_t *req, const ir_node *irn, int pos)
1164 {
1165         be_abi_irg_t *abi          = get_abi_from_ops(self);
1166         const arch_register_t *reg = abi->isa->sp;
1167
1168         req->cls         = reg->reg_class;
1169         req->type        = arch_register_req_type_limited;
1170         req->limited     = be_abi_limited;
1171         req->limited_env = abi;
1172         return req;
1173 }
1174
1175 static void abi_set_irn_reg(const void *self, ir_node *irn, const arch_register_t *reg)
1176 {
1177 }
1178
1179 static const arch_register_t *abi_get_irn_reg(const void *self, const ir_node *irn)
1180 {
1181         const be_abi_irg_t *abi = get_abi_from_ops(self);
1182         return abi->isa->sp;
1183 }
1184
1185 static arch_irn_class_t abi_classify(const void *_self, const ir_node *irn)
1186 {
1187         return arch_irn_class_normal;
1188 }
1189
1190 static arch_irn_flags_t abi_get_flags(const void *_self, const ir_node *irn)
1191 {
1192         return arch_irn_flags_ignore;
1193 }
1194
1195 static entity *abi_get_frame_entity(const void *_self, const ir_node *irn)
1196 {
1197         return NULL;
1198 }
1199
1200 static void abi_set_stack_bias(const void *_self, ir_node *irn, int bias)
1201 {
1202 }
1203
1204 static const arch_irn_ops_if_t abi_irn_ops = {
1205         abi_get_irn_reg_req,
1206         abi_set_irn_reg,
1207         abi_get_irn_reg,
1208         abi_classify,
1209         abi_get_flags,
1210         abi_get_frame_entity,
1211         abi_set_stack_bias
1212 };
1213
1214 static const arch_irn_handler_t abi_irn_handler = {
1215         abi_get_irn_ops
1216 };