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