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