- split array.h into array.h/array_t.h and make array.h independent of
[libfirm] / ir / lower / lower_calls.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   Lowering of Calls with compound parameters and return types.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "lowering.h"
32 #include "irprog_t.h"
33 #include "irnode_t.h"
34 #include "type_t.h"
35 #include "irmode_t.h"
36 #include "ircons.h"
37 #include "irgmod.h"
38 #include "irgwalk.h"
39 #include "irmemory.h"
40 #include "irtools.h"
41 #include "iroptimize.h"
42 #include "array_t.h"
43 #include "pmap.h"
44 #include "xmalloc.h"
45 #include "error.h"
46
47 /** A type map for def_find_pointer_type. */
48 static pmap *type_map;
49
50 /**
51  * Default implementation for finding a pointer type for a given element type.
52  * Simple create a new one.
53  */
54 static ir_type *def_find_pointer_type(ir_type *e_type, ir_mode *mode, int alignment)
55 {
56         ir_type *res;
57         pmap_entry *e;
58
59         /* Mode and alignment are always identical in all calls to def_find_pointer_type(), so
60            we simply can use a map from the element type to the pointer type. */
61         e = pmap_find(type_map, e_type);
62         if (e)
63                 res = e->value;
64         else {
65                 res = new_type_pointer(mangle_u(get_type_ident(e_type), new_id_from_chars("Ptr", 3)), e_type, mode);
66                 set_type_alignment_bytes(res, alignment);
67                 pmap_insert(type_map, e_type, res);
68         }
69         return res;
70 }
71
72 /**
73  * Creates a new lowered type for a method type with compound
74  * arguments. The new type is associated to the old one and returned.
75  *
76  * @param lp   parameter struct
77  * @param mtp  the method type to lower
78  *
79  * The current implementation expects that a lowered type already
80  * includes the necessary changes ...
81  */
82 static ir_type *create_modified_mtd_type(const lower_params_t *lp, ir_type *mtp)
83 {
84         ir_type *lowered, *ptr_tp;
85         ir_type **params, **results, *res_tp;
86         ir_mode *modes[MAX_REGISTER_RET_VAL];
87         int n_ress, n_params, nn_ress, nn_params, i, first_variadic;
88         ident *id;
89         add_hidden hidden_params;
90         int        changed = 0;
91         variadicity var;
92
93         if (is_lowered_type(mtp)) {
94                 /* the type is already lowered. Not handled yet. */
95                 assert(0 && "lowered types NYI");
96         }
97
98         lowered = get_associated_type(mtp);
99         if (lowered)
100                 return lowered;
101
102         n_ress   = get_method_n_ress(mtp);
103         NEW_ARR_A(ir_type *, results, n_ress);
104
105         n_params = get_method_n_params(mtp);
106         NEW_ARR_A(ir_type *, params, n_params + n_ress);
107
108         first_variadic = get_method_first_variadic_param_index(mtp);
109
110         hidden_params = lp->hidden_params;
111         if (hidden_params == ADD_HIDDEN_SMART &&
112                 get_method_variadicity(mtp) == variadicity_variadic)
113                 hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
114
115         if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
116                 /* add hidden in front */
117                 for (nn_ress = nn_params = i = 0; i < n_ress; ++i) {
118                         res_tp = get_method_res_type(mtp, i);
119
120                         if (is_compound_type(res_tp)) {
121                                 int n_regs = 0;
122
123                                 if (lp->flags & LF_SMALL_CMP_IN_REGS)
124                                         n_regs = lp->ret_compound_in_regs(res_tp, modes);
125
126                                 if (n_regs > 0) {
127                                         /* this compound will be returned solely in registers */
128                                         panic("Returning compounds in registers not yet implemented");
129                                 }
130                                 else {
131                                         /* this compound will be allocated on callers stack and its
132                                            address will be transmitted as a hidden parameter. */
133                                         ptr_tp = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
134                                         params[nn_params++] = ptr_tp;
135                                         changed++;
136                                         if (lp->flags & LF_RETURN_HIDDEN)
137                                                 results[nn_ress++] = ptr_tp;
138                                 }
139                         }
140                         else
141                                 results[nn_ress++] = res_tp;
142                 }
143
144                 /* move the index of the first variadic parameter */
145                 first_variadic += nn_params;
146
147                 for (i = 0; i < n_params; ++i)
148                         params[nn_params++] = get_method_param_type(mtp, i);
149         }
150         else {
151                 /* add hidden parameters last */
152                 assert(get_method_variadicity(mtp) == variadicity_non_variadic &&
153                         "Cannot add hidden parameters at end of variadic function");
154
155                 for (nn_params = 0; nn_params < n_params; ++nn_params)
156                         params[nn_params] = get_method_param_type(mtp, nn_params);
157
158                 for (nn_ress = i = 0; i < n_ress; ++i) {
159                         res_tp = get_method_res_type(mtp, i);
160
161                         if (is_compound_type(res_tp))
162                                 params[nn_params++] = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
163                         else
164                                 results[nn_ress++] = res_tp;
165                 }
166         }
167
168         /* create the new type */
169         id = mangle_u(new_id_from_chars("L", 1), get_type_ident(mtp));
170         lowered = new_d_type_method(id, nn_params, nn_ress, get_type_dbg_info(mtp));
171
172         /* fill it */
173         for (i = 0; i < nn_params; ++i)
174                 set_method_param_type(lowered, i, params[i]);
175         for (i = 0; i < nn_ress; ++i)
176                 set_method_res_type(lowered, i, results[i]);
177
178         var = get_method_variadicity(mtp);
179         set_method_variadicity(lowered, var);
180         if (var == variadicity_variadic)
181                 set_method_first_variadic_param_index(lowered, first_variadic);
182
183         /* associate the lowered type with the original one for easier access */
184         if(changed) {
185                 set_method_calling_convention(lowered, get_method_calling_convention(mtp) | cc_compound_ret);
186         }
187         set_lowered_type(mtp, lowered);
188
189         return lowered;
190 }
191
192 /**
193  * A call list entry.
194  */
195 typedef struct cl_entry cl_entry;
196 struct cl_entry {
197         cl_entry *next;   /**< Pointer to the next entry. */
198         ir_node  *call;   /**< Pointer to the Call node. */
199         ir_node  *copyb;  /**< List of all CopyB nodes. */
200 };
201
202 /**
203  * Walker environment for fix_args_and_collect_calls().
204  */
205 typedef struct _wlk_env_t {
206         int                  arg_shift;        /**< The Argument index shift for parameters. */
207         int                  first_hidden;     /**< The index of the first hidden argument. */
208         struct obstack       obst;             /**< An obstack to allocate the data on. */
209         cl_entry             *cl_list;         /**< The call list. */
210         pmap                 *dummy_map;       /**< A map for finding the dummy arguments. */
211         unsigned             dnr;              /**< The dummy index number. */
212         const lower_params_t *params;          /**< Lowering parameters. */
213         unsigned             only_local_mem:1; /**< Set if only local memory access was found. */
214         unsigned             changed:1;        /**< Set if the current graph was changed. */
215 } wlk_env;
216
217 /**
218  * Return the call list entry of a call node.
219  * If no entry exists yet, allocate one and enter the node into
220  * the call list of the environment.
221  *
222  * @param call   A Call node.
223  * @param env    The environment.
224  */
225 static cl_entry *get_Call_entry(ir_node *call, wlk_env *env) {
226         cl_entry *res = get_irn_link(call);
227         if (res == NULL) {
228                 cl_entry *res = obstack_alloc(&env->obst, sizeof(*res));
229                 res->next  = env->cl_list;
230                 res->call  = call;
231                 res->copyb = NULL;
232                 set_irn_link(call, res);
233                 env->cl_list = res;
234         }
235         return res;
236 }
237
238 /**
239  * Finds the base address of an address by skipping Sel's and address
240  * calculation.
241  *
242  * @param adr   the address
243  * @param pEnt  points to the base entity if any
244  */
245 static ir_node *find_base_adr(ir_node *ptr, ir_entity **pEnt) {
246         ir_entity *ent = NULL;
247         assert(mode_is_reference(get_irn_mode(ptr)));
248
249         for (;;) {
250                 if (is_Sel(ptr)) {
251                         ent = get_Sel_entity(ptr);
252                         ptr = get_Sel_ptr(ptr);
253                 }
254                 else if (is_Add(ptr)) {
255                         ir_node *left = get_Add_left(ptr);
256                         if (mode_is_reference(get_irn_mode(left)))
257                                 ptr = left;
258                         else
259                                 ptr = get_Add_right(ptr);
260                         ent = NULL;
261                 } else if (is_Sub(ptr)) {
262                         ptr = get_Sub_left(ptr);
263                         ent = NULL;
264                 } else {
265                         *pEnt = ent;
266                         return ptr;
267                 }
268         }
269 }
270
271 /**
272  * Check if a given pointer represents non-local memory.
273  */
274 static void check_ptr(ir_node *ptr, wlk_env *env) {
275         ir_storage_class_class_t sc;
276         ir_entity                *ent;
277
278         /* still alias free */
279         ptr = find_base_adr(ptr, &ent);
280         sc  = classify_pointer(current_ir_graph, ptr, ent);
281         if (sc != ir_sc_localvar && sc != ir_sc_malloced) {
282                 /* non-local memory access */
283                 env->only_local_mem = 0;
284         }
285 }
286
287 /**
288  * Post walker: shift all parameter indexes
289  * and collect Calls with compound returns in the call list.
290  * If a non-alias free memory access is found, reset the alias free
291  * flag.
292  */
293 static void fix_args_and_collect_calls(ir_node *n, void *ctx) {
294         wlk_env *env = ctx;
295         int      i;
296         ir_type *ctp;
297         ir_node *ptr;
298
299         switch (get_irn_opcode(n)) {
300         case iro_Load:
301         case iro_Store:
302                 if (env->only_local_mem) {
303                         ptr = get_irn_n(n, 1);
304                         check_ptr(ptr, env);
305                 }
306                 break;
307         case iro_Proj:
308                 if (env->arg_shift > 0) {
309                         ir_node *pred = get_Proj_pred(n);
310
311                         /* Fix the argument numbers */
312                         if (pred == get_irg_args(current_ir_graph)) {
313                                 long pnr = get_Proj_proj(n);
314                                 set_Proj_proj(n, pnr + env->arg_shift);
315                                 env->changed = 1;
316                         }
317                 }
318                 break;
319         case iro_Call:
320                 if (! is_self_recursive_Call(n)) {
321                         /* any non self recursive call might access global memory */
322                         env->only_local_mem = 0;
323                 }
324
325                 ctp = get_Call_type(n);
326                 if (env->params->flags & LF_COMPOUND_RETURN) {
327                         /* check for compound returns */
328                         for (i = get_method_n_ress(ctp) -1; i >= 0; --i) {
329                                 if (is_compound_type(get_method_res_type(ctp, i))) {
330                                         /*
331                                          * This is a call with a compound return. As the result
332                                          * might be ignored, we must put it in the list.
333                                          */
334                                         (void)get_Call_entry(n, env);
335                                         break;
336                                 }
337                         }
338                 }
339                 break;
340         case iro_CopyB:
341                 if (env->only_local_mem) {
342                         check_ptr(get_CopyB_src(n), env);
343                         if (env->only_local_mem)
344                                 check_ptr(get_CopyB_dst(n), env);
345                 }
346                 if (env->params->flags & LF_COMPOUND_RETURN) {
347                         /* check for compound returns */
348                         ir_node *src = get_CopyB_src(n);
349                         /* older scheme using value_res_ent */
350                         if (is_Sel(src)) {
351                                 ir_node *proj = get_Sel_ptr(src);
352                                 if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_P_value_res_base) {
353                                         ir_node *call = get_Proj_pred(proj);
354                                         if (is_Call(call)) {
355                                                 /* found a CopyB from compound Call result */
356                                                 cl_entry *e = get_Call_entry(call, env);
357                                                 set_irn_link(n, e->copyb);
358                                                 e->copyb = n;
359                                         }
360                                 }
361                         } else {
362                                 /* new scheme: compound results are determined by the call type only */
363                                 if (is_Proj(src)) {
364                                         ir_node *proj = get_Proj_pred(src);
365                                         if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_T_result) {
366                                                 ir_node *call = get_Proj_pred(proj);
367                                                 if (is_Call(call)) {
368                                                         ctp = get_Call_type(call);
369                                                         if (is_compound_type(get_method_res_type(ctp, get_Proj_proj(src)))) {
370                                                                 /* found a CopyB from compound Call result */
371                                                                 cl_entry *e = get_Call_entry(call, env);
372                                                                 set_irn_link(n, e->copyb);
373                                                                 e->copyb = n;
374                                                         }
375                                                 }
376                                         }
377                                 }
378                         }
379                 }
380                 break;
381         default:
382                 /* do nothing */
383                 break;
384         }
385 }
386
387 /**
388  * Returns non-zero if a node is a compound address
389  * of a frame-type entity.
390  *
391  * @param ft   the frame type
392  * @param adr  the node
393  */
394 static int is_compound_address(ir_type *ft, ir_node *adr)
395 {
396         ir_entity *ent;
397
398         if (! is_Sel(adr))
399                 return 0;
400         if (get_Sel_n_indexs(adr) != 0)
401                 return 0;
402         ent = get_Sel_entity(adr);
403         return get_entity_owner(ent) == ft;
404 }
405
406 /** A pair for the copy-return-optimization. */
407 typedef struct cr_pair {
408         ir_entity *ent; /**< the entity than can be removed from the frame */
409         ir_node *arg;   /**< the argument that replaces the entities address */
410 } cr_pair;
411
412 /**
413  * Post walker: fixes all entities addresses for the copy-return
414  * optimization.
415  *
416  * Note: We expect the length of the cr_pair array (ie number of compound
417  * return values) to be 1 (C, C++) in almost all cases, so ignore the
418  * linear search complexity here.
419  */
420 static void do_copy_return_opt(ir_node *n, void *ctx) {
421         cr_pair *arr = ctx;
422         int i;
423
424         if (is_Sel(n)) {
425                 ir_entity *ent = get_Sel_entity(n);
426
427                 for (i = ARR_LEN(arr) - 1; i >= 0; --i) {
428                         if (ent == arr[i].ent) {
429                                 exchange(n, arr[i].arg);
430                                 break;
431                         }
432                 }
433         }
434 }
435
436 /**
437  * Return a Sel node that selects a dummy argument of type tp.
438  * Dummy arguments are only needed once and we use a map
439  * to store them.
440  * We could even assign all dummy arguments the same offset
441  * in the frame type ...
442  *
443  * @param irg    the graph
444  * @param block  the block where a newly create Sel should be placed
445  * @param tp     the type of the dummy entity that should be create
446  * @param env    the environment
447  */
448 static ir_node *get_dummy_sel(ir_graph *irg, ir_node *block, ir_type *tp, wlk_env *env)
449 {
450         ir_entity *ent;
451         pmap_entry *e;
452
453         /* use a map the check if we already create such an entity */
454         e = pmap_find(env->dummy_map, tp);
455         if (e)
456                 ent = e->value;
457         else {
458                 ir_type *ft = get_irg_frame_type(irg);
459                 char buf[16];
460
461                 snprintf(buf, sizeof(buf), "dummy.%u", env->dnr++);
462                 ent = new_entity(ft, new_id_from_str(buf), tp);
463                 pmap_insert(env->dummy_map, tp, ent);
464
465                 if (get_type_state(ft) == layout_fixed) {
466                         /* Fix the layout again */
467                         assert(0 && "Fixed layout not implemented");
468                 }
469         }
470         return new_r_simpleSel(
471                 irg,
472                 block,
473                 get_irg_no_mem(irg),
474                 get_irg_frame(irg),
475                 ent);
476 }
477
478 /**
479  * Add the hidden parameter from the CopyB node to the Call node.
480  *
481  * @param irg    the graph
482  * @param n_com  number of compound results (will be number of hidden parameters)
483  * @param ins    in array to store the hidden parameters into
484  * @param entry  the call list
485  * @param env    the environment
486  */
487 static void add_hidden_param(ir_graph *irg, int n_com, ir_node **ins, cl_entry *entry, wlk_env *env)
488 {
489         ir_node *p, *n, *src, *mem, *blk;
490         ir_entity *ent;
491         ir_type *owner;
492         int idx, n_args;
493
494         n_args = 0;
495         for (p = entry->copyb; p; p = n) {
496                 n   = get_irn_link(p);
497                 src = get_CopyB_src(p);
498
499                 /* old scheme using value_res_ent */
500                 if (is_Sel(src)) {
501                         ent = get_Sel_entity(src);
502                         owner = get_entity_owner(ent);
503
504                         /* find the hidden parameter index */
505                         for (idx = 0; idx < get_struct_n_members(owner); ++idx)
506                                 if (get_struct_member(owner, idx) == ent)
507                                         break;
508                         assert(idx < get_struct_n_members(owner));
509                 } else {
510                         /* new scheme: compound returns are determined by the call type and are Proj's */
511                         idx = get_Proj_proj(src);
512                 }
513
514                 ins[idx] = get_CopyB_dst(p);
515                 mem      = get_CopyB_mem(p);
516                 blk      = get_nodes_block(p);
517
518                 /* get rid of the CopyB */
519                 turn_into_tuple(p, pn_CopyB_max);
520                 set_Tuple_pred(p, pn_CopyB_M_regular, mem);
521                 set_Tuple_pred(p, pn_CopyB_M_except,  get_irg_bad(irg));
522                 set_Tuple_pred(p, pn_CopyB_X_regular, new_r_Jmp(irg, blk));
523                 set_Tuple_pred(p, pn_CopyB_X_except,  get_irg_bad(irg));
524                 ++n_args;
525         }
526
527         /* now create dummy entities for function with ignored return value */
528         if (n_args < n_com) {
529                 ir_type *ctp = get_Call_type(entry->call);
530                 int i, j;
531
532                 if (is_lowered_type(ctp))
533                         ctp = get_associated_type(ctp);
534
535                 for (j = i = 0; i < get_method_n_ress(ctp); ++i) {
536                         ir_type *rtp = get_method_res_type(ctp, i);
537                         if (is_compound_type(rtp)) {
538                                 if (ins[j] == NULL)
539                                         ins[j] = get_dummy_sel(irg, get_nodes_block(entry->call), rtp, env);
540                                 ++j;
541                         }
542                 }
543         }
544 }
545
546 /**
547  * Fix all calls on a call list by adding hidden parameters.
548  *
549  * @param irg  the graph
550  * @param env  the environment
551  */
552 static void fix_call_list(ir_graph *irg, wlk_env *env) {
553         const lower_params_t *lp = env->params;
554         cl_entry *p;
555         ir_node *call, **new_in;
556         ir_type *ctp, *lowered_mtp;
557         add_hidden hidden_params;
558         int i, n_params, n_com, pos;
559
560         new_in = NEW_ARR_F(ir_node *, 0);
561         for (p = env->cl_list; p; p = p->next) {
562                 call = p->call;
563                 ctp = get_Call_type(call);
564                 lowered_mtp = create_modified_mtd_type(lp, ctp);
565                 set_Call_type(call, lowered_mtp);
566
567                 hidden_params = lp->hidden_params;
568                 if (hidden_params == ADD_HIDDEN_SMART &&
569                         get_method_variadicity(ctp) == variadicity_variadic)
570                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
571
572                 n_params = get_Call_n_params(call);
573
574                 n_com = 0;
575                 for (i = get_method_n_ress(ctp) - 1; i >= 0; --i) {
576                         if (is_compound_type(get_method_res_type(ctp, i)))
577                                 ++n_com;
578                 }
579                 pos = 2;
580                 ARR_RESIZE(ir_node *, new_in, n_params + n_com + pos);
581                 memset(new_in, 0, sizeof(*new_in) * (n_params + n_com + pos));
582                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
583                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
584                         pos += n_com;
585                 }
586                 /* copy all other parameters */
587                 for (i = 0; i < n_params; ++i)
588                         new_in[pos++] = get_Call_param(call, i);
589                 if (hidden_params == ADD_HIDDEN_ALWAYS_LAST) {
590                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
591                         pos += n_com;
592                 }
593                 new_in[0] = get_Call_mem(call);
594                 new_in[1] = get_Call_ptr(call);
595
596                 set_irn_in(call, n_params + n_com + 2, new_in);
597         }
598 }
599
600 /**
601  * Transform a graph. If it has compound parameter returns,
602  * remove them and use the hidden parameter instead.
603  * If it calls methods with compound parameter returns, add hidden
604  * parameters.
605  *
606  * @param lp   parameter struct
607  * @param irg  the graph to transform
608  */
609 static void transform_irg(const lower_params_t *lp, ir_graph *irg)
610 {
611         ir_graph   * rem = current_ir_graph;
612         ir_entity  *ent = get_irg_entity(irg);
613         ir_type    *mtp, *lowered_mtp, *tp, *ft;
614         int        i, j, k, n_ress = 0, n_ret_com = 0, n_cr_opt;
615         ir_node    **new_in, *ret, *endbl, *bl, *mem, *copy;
616         cr_pair    *cr_opt;
617         wlk_env    env;
618         add_hidden hidden_params;
619
620         current_ir_graph = irg;
621
622         assert(ent && "Cannot transform graph without an entity");
623         assert(get_irg_phase_state(irg) == phase_high && "call lowering must be done in phase high");
624
625         mtp = get_entity_type(ent);
626
627         if (lp->flags & LF_COMPOUND_RETURN) {
628                 /* calculate the number of compound returns */
629                 n_ress = get_method_n_ress(mtp);
630                 for (n_ret_com = i = 0; i < n_ress; ++i) {
631                         tp = get_method_res_type(mtp, i);
632
633                         if (is_compound_type(tp))
634                                 ++n_ret_com;
635                 }
636         }
637
638         if (n_ret_com) {
639                 /* much easier if we have only one return */
640                 normalize_one_return(irg);
641
642                 /* This graph has a compound argument. Create a new type */
643                 lowered_mtp = create_modified_mtd_type(lp, mtp);
644                 set_entity_type(ent, lowered_mtp);
645
646                 hidden_params = lp->hidden_params;
647                 if (hidden_params == ADD_HIDDEN_SMART &&
648                         get_method_variadicity(mtp) == variadicity_variadic)
649                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
650
651                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
652                         /* hidden arguments are added first */
653                         env.arg_shift    = n_ret_com;
654                         env.first_hidden = 0;
655                 } else {
656                         /* hidden arguments are added last */
657                         env.arg_shift    = 0;
658                         env.first_hidden = get_method_n_params(mtp);
659                 }
660         } else {
661                 /* we must only search for calls */
662                 env.arg_shift = 0;
663         }
664         obstack_init(&env.obst);
665         env.cl_list        = NULL;
666         env.dummy_map      = pmap_create_ex(8);
667         env.dnr            = 0;
668         env.params         = lp;
669         env.only_local_mem = 1;
670         env.changed        = 0;
671
672         /* scan the code, fix argument numbers and collect calls. */
673         irg_walk_graph(irg, firm_clear_link, fix_args_and_collect_calls, &env);
674
675         /* fix all calls */
676         if (env.cl_list) {
677                 fix_call_list(irg, &env);
678                 env.changed = 1;
679         }
680
681         if (n_ret_com) {
682                 /*
683                  * Now fix the Return node of the current graph.
684                  */
685                 env.changed = 1;
686
687                 /* STEP 1: find the return. This is simple, we have normalized the graph. */
688                 endbl = get_irg_end_block(irg);
689                 ret = NULL;
690                 for (i = get_Block_n_cfgpreds(endbl) - 1; i >= 0; --i) {
691                         ir_node *pred = get_Block_cfgpred(endbl, i);
692
693                         if (is_Return(pred)) {
694                                 ret = pred;
695                                 break;
696                         }
697                 }
698                 /* there should always be a return */
699                 assert(ret);
700
701                 /*
702                  * STEP 2: fix it. For all compound return values add a CopyB,
703                  * all others are copied.
704                  */
705                 NEW_ARR_A(ir_node *, new_in, n_ress + 1);
706
707                 bl  = get_nodes_block(ret);
708                 mem = get_Return_mem(ret);
709
710                 ft = get_irg_frame_type(irg);
711                 NEW_ARR_A(cr_pair, cr_opt, n_ret_com);
712                 n_cr_opt = 0;
713                 for (j = 1, i = k = 0; i < n_ress; ++i) {
714                         ir_node *pred = get_Return_res(ret, i);
715                         tp = get_method_res_type(mtp, i);
716
717                         if (is_compound_type(tp)) {
718                                 ir_node *arg = get_irg_args(irg);
719                                 arg = new_r_Proj(irg, get_nodes_block(arg), arg, mode_P_data, env.first_hidden + k);
720                                 ++k;
721
722                                 if (is_Unknown(pred)) {
723                                         /* The Return(Unknown) is the Firm construct for a missing return.
724                                            Do nothing. */
725                                 } else {
726                                         /**
727                                          * Sorrily detecting that copy-return is possible isn't that simple.
728                                          * We must check, that the hidden address is alias free during the whole
729                                          * function.
730                                          * A simple heuristic: all Loads/Stores inside
731                                          * the function access only local frame.
732                                          */
733                                         if (env.only_local_mem && is_compound_address(ft, pred)) {
734                                                 /* we can do the copy-return optimization here */
735                                                 cr_opt[n_cr_opt].ent = get_Sel_entity(pred);
736                                                 cr_opt[n_cr_opt].arg = arg;
737                                                 ++n_cr_opt;
738                                         } else { /* copy-return optimization is impossible, do the copy. */
739                                                 copy = new_r_CopyB(
740                                                         irg, bl,
741                                                         mem,
742                                                         arg,
743                                                         pred,
744                                                         tp
745                                                         );
746                                                 mem = new_r_Proj(irg, bl, copy, mode_M, pn_CopyB_M_regular);
747                                         }
748                                 }
749                                 if (lp->flags & LF_RETURN_HIDDEN) {
750                                         new_in[j] = arg;
751                                         ++j;
752                                 }
753                         } else { /* scalar return value */
754                                 new_in[j] = pred;
755                                 ++j;
756                         }
757                 }
758                 /* replace the in of the Return */
759                 new_in[0] = mem;
760                 set_irn_in(ret, j, new_in);
761
762                 if (n_cr_opt > 0) {
763                         irg_walk_graph(irg, NULL, do_copy_return_opt, cr_opt);
764
765                         for (i = ARR_LEN(cr_opt) - 1; i >= 0; --i) {
766                                 remove_class_member(ft, cr_opt[i].ent);
767                         }
768                 }
769         } /* if (n_ret_com) */
770
771         pmap_destroy(env.dummy_map);
772         obstack_free(&env.obst, NULL);
773
774         if (env.changed) {
775                 /* invalidate the analysis info */
776                 set_irg_outs_inconsistent(irg);
777                 set_irg_loopinfo_state(irg, loopinfo_inconsistent);
778         }
779         current_ir_graph = rem;
780 }
781
782 /**
783  * Returns non-zero if the given type is a method
784  * type that must be lowered.
785  *
786  * @param lp  lowering parameters
787  * @param tp  The type.
788  */
789 static int must_be_lowered(const lower_params_t *lp, ir_type *tp) {
790   int i, n_ress;
791   ir_type *res_tp;
792
793   if (is_Method_type(tp)) {
794     if (lp->flags & LF_COMPOUND_RETURN) {
795       /* check for compound returns */
796       n_ress = get_method_n_ress(tp);
797       for (i = 0; i < n_ress; ++i) {
798         res_tp = get_method_res_type(tp, i);
799
800         if (is_compound_type(res_tp))
801           return 1;
802       }
803     }
804   }
805   return 0;
806 }
807
808 /**
809  * type-walker: lower all method types of entities
810  * and points-to types.
811  */
812 static void lower_method_types(type_or_ent tore, void *env)
813 {
814         const lower_params_t *lp = env;
815         ir_type *tp;
816
817         /* fix method entities */
818         if (is_entity(tore.ent)) {
819                 ir_entity *ent = tore.ent;
820                 tp = get_entity_type(ent);
821
822                 if (must_be_lowered(lp, tp)) {
823                         tp = create_modified_mtd_type(lp, tp);
824                         set_entity_type(ent, tp);
825                 }
826         } else {
827                 tp = tore.typ;
828
829                 /* fix pointer to methods */
830                 if (is_Pointer_type(tp)) {
831                         ir_type *etp = get_pointer_points_to_type(tp);
832                         if (must_be_lowered(lp, etp)) {
833                                 etp = create_modified_mtd_type(lp, etp);
834                                 set_pointer_points_to_type(tp, etp);
835                         }
836                 }
837         }
838 }
839
840 /*
841  * Lower calls with compound parameters and return types.
842  * This function does the following transformations:
843  *
844  * - Adds a new (hidden) pointer parameter for
845  *   any return compound type.
846  *
847  * - Use of the hidden parameters in the function code.
848  *
849  * - Change all calls to functions with compound return
850  *   by providing space for the hidden parameter on the callers
851  *   stack.
852  *
853  * - Replace a possible block copy after the function call.
854  */
855 void lower_calls_with_compounds(const lower_params_t *params)
856 {
857         int i;
858         ir_graph *irg;
859         lower_params_t param = *params;
860
861         if (param.find_pointer_type == NULL) {
862                 param.find_pointer_type = def_find_pointer_type;
863                 type_map = pmap_create_ex(8);
864         } else
865                 type_map = NULL;
866
867         /* first step: Transform all graphs */
868         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
869                 irg = get_irp_irg(i);
870
871                 if (irg == get_const_code_irg())
872                         continue;
873
874                 transform_irg(&param, irg);
875         }
876
877         /* second step: Lower all method types of visible entities */
878         type_walk(NULL, lower_method_types, &param);
879
880         if (type_map)
881                 pmap_destroy(type_map);
882 }