remove names from parameters of method_types - it is pure debug info and should alrea...
[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                         /* older scheme using value_res_ent */
368                         if (is_Sel(src)) {
369                                 ir_node *proj = get_Sel_ptr(src);
370                                 if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_P_value_res_base) {
371                                         ir_node *call = get_Proj_pred(proj);
372                                         if (is_Call(call)) {
373                                                 /* found a CopyB from compound Call result */
374                                                 cl_entry *e = get_Call_entry(call, env);
375                                                 set_irn_link(n, e->copyb);
376                                                 e->copyb = n;
377                                         }
378                                 }
379                         } else {
380                                 /* new scheme: compound results are determined by the call type only */
381                                 if (is_Proj(src)) {
382                                         ir_node *proj = get_Proj_pred(src);
383                                         if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_T_result) {
384                                                 ir_node *call = get_Proj_pred(proj);
385                                                 if (is_Call(call)) {
386                                                         ctp = get_Call_type(call);
387                                                         if (is_compound_type(get_method_res_type(ctp, get_Proj_proj(src)))) {
388                                                                 /* found a CopyB from compound Call result */
389                                                                 cl_entry *e = get_Call_entry(call, env);
390                                                                 set_irn_link(n, e->copyb);
391                                                                 e->copyb = n;
392                                                         }
393                                                 }
394                                         }
395                                 }
396                         }
397                 }
398                 break;
399         default:
400                 /* do nothing */
401                 break;
402         }
403 }
404
405 /**
406  * Returns non-zero if a node is a compound address
407  * of a frame-type entity.
408  *
409  * @param ft   the frame type
410  * @param adr  the node
411  */
412 static int is_compound_address(ir_type *ft, ir_node *adr)
413 {
414         ir_entity *ent;
415
416         if (! is_Sel(adr))
417                 return 0;
418         if (get_Sel_n_indexs(adr) != 0)
419                 return 0;
420         ent = get_Sel_entity(adr);
421         return get_entity_owner(ent) == ft;
422 }
423
424 /** A pair for the copy-return-optimization. */
425 typedef struct cr_pair {
426         ir_entity *ent; /**< the entity than can be removed from the frame */
427         ir_node *arg;   /**< the argument that replaces the entities address */
428 } cr_pair;
429
430 /**
431  * Post walker: fixes all entities addresses for the copy-return
432  * optimization.
433  *
434  * Note: We expect the length of the cr_pair array (i.e. number of compound
435  * return values) to be 1 (C, C++) in almost all cases, so ignore the
436  * linear search complexity here.
437  */
438 static void do_copy_return_opt(ir_node *n, void *ctx)
439 {
440         if (is_Sel(n)) {
441                 ir_entity *ent = get_Sel_entity(n);
442                 cr_pair   *arr = (cr_pair*)ctx;
443                 size_t    i, l;
444
445                 for (i = 0, l = ARR_LEN(arr); i < l; ++i) {
446                         if (ent == arr[i].ent) {
447                                 exchange(n, arr[i].arg);
448                                 break;
449                         }
450                 }
451         }
452 }
453
454 /**
455  * Return a Sel node that selects a dummy argument of type tp.
456  * Dummy arguments are only needed once and we use a map
457  * to store them.
458  * We could even assign all dummy arguments the same offset
459  * in the frame type ...
460  *
461  * @param irg    the graph
462  * @param block  the block where a newly create Sel should be placed
463  * @param tp     the type of the dummy entity that should be create
464  * @param env    the environment
465  */
466 static ir_node *get_dummy_sel(ir_graph *irg, ir_node *block, ir_type *tp, wlk_env *env)
467 {
468         ir_entity *ent;
469         pmap_entry *e;
470
471         /* use a map the check if we already create such an entity */
472         e = pmap_find(env->dummy_map, tp);
473         if (e)
474                 ent = (ir_entity*)e->value;
475         else {
476                 ir_type *ft = get_irg_frame_type(irg);
477                 char buf[16];
478
479                 snprintf(buf, sizeof(buf), "dummy.%u", env->dnr++);
480                 ent = new_entity(ft, new_id_from_str(buf), tp);
481                 pmap_insert(env->dummy_map, tp, ent);
482
483                 if (get_type_state(ft) == layout_fixed) {
484                         /* Fix the layout again */
485                         assert(0 && "Fixed layout not implemented");
486                 }
487         }
488         return new_r_simpleSel(
489                 block,
490                 get_irg_no_mem(irg),
491                 get_irg_frame(irg),
492                 ent);
493 }
494
495 /**
496  * Add the hidden parameter from the CopyB node to the Call node.
497  *
498  * @param irg    the graph
499  * @param n_com  number of compound results (will be number of hidden parameters)
500  * @param ins    in array to store the hidden parameters into
501  * @param entry  the call list
502  * @param env    the environment
503  */
504 static void add_hidden_param(ir_graph *irg, size_t n_com, ir_node **ins, cl_entry *entry, wlk_env *env)
505 {
506         ir_node *p, *n, *src, *mem, *blk;
507         ir_entity *ent;
508         ir_type *owner;
509         size_t n_args;
510
511         n_args = 0;
512         for (p = entry->copyb; p; p = n) {
513                 size_t idx;
514                 n   = (ir_node*)get_irn_link(p);
515                 src = get_CopyB_src(p);
516
517                 /* old scheme using value_res_ent */
518                 if (is_Sel(src)) {
519                         ent = get_Sel_entity(src);
520                         owner = get_entity_owner(ent);
521
522                         /* find the hidden parameter index */
523                         for (idx = 0; idx < get_struct_n_members(owner); ++idx)
524                                 if (get_struct_member(owner, idx) == ent)
525                                         break;
526                         assert(idx < get_struct_n_members(owner));
527                 } else {
528                         /* new scheme: compound returns are determined by the call type and are Proj's */
529                         idx = get_Proj_proj(src);
530                 }
531
532                 ins[idx] = get_CopyB_dst(p);
533                 mem      = get_CopyB_mem(p);
534                 blk      = get_nodes_block(p);
535
536                 /* get rid of the CopyB */
537                 turn_into_tuple(p, pn_CopyB_max);
538                 set_Tuple_pred(p, pn_CopyB_M,         mem);
539                 set_Tuple_pred(p, pn_CopyB_X_regular, new_r_Jmp(blk));
540                 set_Tuple_pred(p, pn_CopyB_X_except,  get_irg_bad(irg));
541                 ++n_args;
542         }
543
544         /* now create dummy entities for function with ignored return value */
545         if (n_args < n_com) {
546                 ir_type *ctp = get_Call_type(entry->call);
547                 size_t   i;
548                 size_t   j;
549
550                 if (is_lowered_type(ctp))
551                         ctp = get_associated_type(ctp);
552
553                 for (j = i = 0; i < get_method_n_ress(ctp); ++i) {
554                         ir_type *rtp = get_method_res_type(ctp, i);
555                         if (is_compound_type(rtp)) {
556                                 if (ins[j] == NULL)
557                                         ins[j] = get_dummy_sel(irg, get_nodes_block(entry->call), rtp, env);
558                                 ++j;
559                         }
560                 }
561         }
562 }
563
564 /**
565  * Fix all calls on a call list by adding hidden parameters.
566  *
567  * @param irg  the graph
568  * @param env  the environment
569  */
570 static void fix_call_list(ir_graph *irg, wlk_env *env)
571 {
572         const lower_params_t *lp = env->params;
573         cl_entry *p;
574         ir_node *call, **new_in;
575         ir_type *ctp, *lowered_mtp;
576         add_hidden hidden_params;
577         size_t i, n_res, n_params, n_com, pos;
578
579         new_in = NEW_ARR_F(ir_node *, 0);
580         for (p = env->cl_list; p; p = p->next) {
581                 call = p->call;
582                 ctp = get_Call_type(call);
583                 lowered_mtp = create_modified_mtd_type(lp, ctp);
584                 set_Call_type(call, lowered_mtp);
585
586                 hidden_params = lp->hidden_params;
587                 if (hidden_params == ADD_HIDDEN_SMART &&
588                         get_method_variadicity(ctp) == variadicity_variadic)
589                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
590
591                 n_params = get_Call_n_params(call);
592
593                 n_com = 0;
594                 for (i = 0, n_res = get_method_n_ress(ctp); i < n_res; ++i) {
595                         if (is_compound_type(get_method_res_type(ctp, i)))
596                                 ++n_com;
597                 }
598                 pos = 2;
599                 ARR_RESIZE(ir_node *, new_in, n_params + n_com + pos);
600                 memset(new_in, 0, sizeof(*new_in) * (n_params + n_com + pos));
601                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
602                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
603                         pos += n_com;
604                 }
605                 /* copy all other parameters */
606                 for (i = 0; i < n_params; ++i)
607                         new_in[pos++] = get_Call_param(call, i);
608                 if (hidden_params == ADD_HIDDEN_ALWAYS_LAST) {
609                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
610                         pos += n_com;
611                 }
612                 new_in[0] = get_Call_mem(call);
613                 new_in[1] = get_Call_ptr(call);
614
615                 set_irn_in(call, n_params + n_com + 2, new_in);
616         }
617 }
618
619 /**
620  * Transform a graph. If it has compound parameter returns,
621  * remove them and use the hidden parameter instead.
622  * If it calls methods with compound parameter returns, add hidden
623  * parameters.
624  *
625  * @param lp   parameter struct
626  * @param irg  the graph to transform
627  */
628 static void transform_irg(const lower_params_t *lp, ir_graph *irg)
629 {
630         ir_graph   *rem = current_ir_graph;
631         ir_entity  *ent = get_irg_entity(irg);
632         ir_type    *mtp, *lowered_mtp, *tp, *ft;
633         size_t     i, j, k, n_ress = 0, n_ret_com = 0;
634         size_t     n_cr_opt;
635         ir_node    **new_in, *ret, *endbl, *bl, *mem, *copy;
636         cr_pair    *cr_opt;
637         wlk_env    env;
638         add_hidden hidden_params;
639
640         current_ir_graph = irg;
641
642         assert(ent && "Cannot transform graph without an entity");
643         assert(get_irg_phase_state(irg) == phase_high && "call lowering must be done in phase high");
644
645         mtp = get_entity_type(ent);
646
647         if (lp->flags & LF_COMPOUND_RETURN) {
648                 /* calculate the number of compound returns */
649                 n_ress = get_method_n_ress(mtp);
650                 for (n_ret_com = i = 0; i < n_ress; ++i) {
651                         tp = get_method_res_type(mtp, i);
652
653                         if (is_compound_type(tp))
654                                 ++n_ret_com;
655                 }
656         }
657
658         if (n_ret_com) {
659                 /* much easier if we have only one return */
660                 normalize_one_return(irg);
661
662                 /* This graph has a compound argument. Create a new type */
663                 lowered_mtp = create_modified_mtd_type(lp, mtp);
664                 set_entity_type(ent, lowered_mtp);
665
666                 hidden_params = lp->hidden_params;
667                 if (hidden_params == ADD_HIDDEN_SMART &&
668                         get_method_variadicity(mtp) == variadicity_variadic)
669                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
670
671                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
672                         /* hidden arguments are added first */
673                         env.arg_shift    = n_ret_com;
674                         env.first_hidden = 0;
675                 } else {
676                         /* hidden arguments are added last */
677                         env.arg_shift    = 0;
678                         env.first_hidden = get_method_n_params(mtp);
679                 }
680         } else {
681                 /* we must only search for calls */
682                 env.arg_shift = 0;
683                 lowered_mtp   = NULL;
684         }
685         obstack_init(&env.obst);
686         env.cl_list        = NULL;
687         env.dummy_map      = pmap_create_ex(8);
688         env.dnr            = 0;
689         env.params         = lp;
690         env.lowered_mtp    = lowered_mtp;
691         env.value_params   = get_method_value_param_type(mtp);
692         env.only_local_mem = 1;
693         env.changed        = 0;
694
695         /* scan the code, fix argument numbers and collect calls. */
696         irg_walk_graph(irg, firm_clear_link, fix_args_and_collect_calls, &env);
697
698         /* fix all calls */
699         if (env.cl_list) {
700                 fix_call_list(irg, &env);
701                 env.changed = 1;
702         }
703
704         if (n_ret_com) {
705                 int idx;
706
707                 /*
708                  * Now fix the Return node of the current graph.
709                  */
710                 env.changed = 1;
711
712                 /* STEP 1: find the return. This is simple, we have normalized the graph. */
713                 endbl = get_irg_end_block(irg);
714                 ret = NULL;
715                 for (idx = get_Block_n_cfgpreds(endbl) - 1; idx >= 0; --idx) {
716                         ir_node *pred = get_Block_cfgpred(endbl, idx);
717
718                         if (is_Return(pred)) {
719                                 ret = pred;
720                                 break;
721                         }
722                 }
723                 /* there should always be a return */
724                 assert(ret);
725
726                 /*
727                  * STEP 2: fix it. For all compound return values add a CopyB,
728                  * all others are copied.
729                  */
730                 NEW_ARR_A(ir_node *, new_in, n_ress + 1);
731
732                 bl  = get_nodes_block(ret);
733                 mem = get_Return_mem(ret);
734
735                 ft = get_irg_frame_type(irg);
736                 NEW_ARR_A(cr_pair, cr_opt, n_ret_com);
737                 n_cr_opt = 0;
738                 for (j = 1, i = k = 0; i < n_ress; ++i) {
739                         ir_node *pred = get_Return_res(ret, i);
740                         tp = get_method_res_type(mtp, i);
741
742                         if (is_compound_type(tp)) {
743                                 ir_node *arg = get_irg_args(irg);
744                                 arg = new_r_Proj(arg, mode_P_data, env.first_hidden + k);
745                                 ++k;
746
747                                 if (is_Unknown(pred)) {
748                                         /* The Return(Unknown) is the Firm construct for a missing return.
749                                            Do nothing. */
750                                 } else {
751                                         /**
752                                          * Sorrily detecting that copy-return is possible isn't that simple.
753                                          * We must check, that the hidden address is alias free during the whole
754                                          * function.
755                                          * A simple heuristic: all Loads/Stores inside
756                                          * the function access only local frame.
757                                          */
758                                         if (env.only_local_mem && is_compound_address(ft, pred)) {
759                                                 /* we can do the copy-return optimization here */
760                                                 cr_opt[n_cr_opt].ent = get_Sel_entity(pred);
761                                                 cr_opt[n_cr_opt].arg = arg;
762                                                 ++n_cr_opt;
763                                         } else { /* copy-return optimization is impossible, do the copy. */
764                                                 copy = new_r_CopyB(
765                                                         bl,
766                                                         mem,
767                                                         arg,
768                                                         pred,
769                                                         tp
770                                                         );
771                                                 mem = new_r_Proj(copy, mode_M, pn_CopyB_M);
772                                         }
773                                 }
774                                 if (lp->flags & LF_RETURN_HIDDEN) {
775                                         new_in[j] = arg;
776                                         ++j;
777                                 }
778                         } else { /* scalar return value */
779                                 new_in[j] = pred;
780                                 ++j;
781                         }
782                 }
783                 /* replace the in of the Return */
784                 new_in[0] = mem;
785                 set_irn_in(ret, j, new_in);
786
787                 if (n_cr_opt > 0) {
788                         size_t i, n;
789
790                         irg_walk_graph(irg, NULL, do_copy_return_opt, cr_opt);
791
792                         for (i = 0, n = ARR_LEN(cr_opt); i < n; ++i) {
793                                 free_entity(cr_opt[i].ent);
794                         }
795                 }
796         } /* if (n_ret_com) */
797
798         pmap_destroy(env.dummy_map);
799         obstack_free(&env.obst, NULL);
800
801         if (env.changed) {
802                 /* invalidate the analysis info */
803                 set_irg_outs_inconsistent(irg);
804                 set_irg_loopinfo_state(irg, loopinfo_inconsistent);
805         }
806         current_ir_graph = rem;
807 }
808
809 /**
810  * Returns non-zero if the given type is a method
811  * type that must be lowered.
812  *
813  * @param lp  lowering parameters
814  * @param tp  The type.
815  */
816 static int must_be_lowered(const lower_params_t *lp, ir_type *tp)
817 {
818   size_t i, n_ress;
819   ir_type *res_tp;
820
821   if (is_Method_type(tp)) {
822     if (lp->flags & LF_COMPOUND_RETURN) {
823       /* check for compound returns */
824       n_ress = get_method_n_ress(tp);
825       for (i = 0; i < n_ress; ++i) {
826         res_tp = get_method_res_type(tp, i);
827
828         if (is_compound_type(res_tp))
829           return 1;
830       }
831     }
832   }
833   return 0;
834 }
835
836 /**
837  * type-walker: lower all method types of entities
838  * and points-to types.
839  */
840 static void lower_method_types(type_or_ent tore, void *env)
841 {
842         const lower_params_t *lp = (const lower_params_t*)env;
843         ir_type *tp;
844
845         /* fix method entities */
846         if (is_entity(tore.ent)) {
847                 ir_entity *ent = tore.ent;
848                 tp = get_entity_type(ent);
849
850                 if (must_be_lowered(lp, tp)) {
851                         tp = create_modified_mtd_type(lp, tp);
852                         set_entity_type(ent, tp);
853                 }
854         } else {
855                 tp = tore.typ;
856
857                 /* fix pointer to methods */
858                 if (is_Pointer_type(tp)) {
859                         ir_type *etp = get_pointer_points_to_type(tp);
860                         if (must_be_lowered(lp, etp)) {
861                                 etp = create_modified_mtd_type(lp, etp);
862                                 set_pointer_points_to_type(tp, etp);
863                         }
864                 }
865         }
866 }
867
868 /*
869  * Lower calls with compound parameters and return types.
870  * This function does the following transformations:
871  *
872  * - Adds a new (hidden) pointer parameter for
873  *   any return compound type.
874  *
875  * - Use of the hidden parameters in the function code.
876  *
877  * - Change all calls to functions with compound return
878  *   by providing space for the hidden parameter on the callers
879  *   stack.
880  *
881  * - Replace a possible block copy after the function call.
882  */
883 void lower_calls_with_compounds(const lower_params_t *params)
884 {
885         size_t i, n;
886         ir_graph *irg;
887         lower_params_t param = *params;
888
889         if (param.find_pointer_type == NULL) {
890                 param.find_pointer_type = def_find_pointer_type;
891                 type_map = pmap_create_ex(8);
892         } else
893                 type_map = NULL;
894
895         /* first step: Transform all graphs */
896         for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
897                 irg = get_irp_irg(i);
898
899                 transform_irg(&param, irg);
900         }
901
902         /* second step: Lower all method types of visible entities */
903         type_walk(NULL, lower_method_types, &param);
904
905         if (type_map)
906                 pmap_destroy(type_map);
907 }
908