- activated WITH_UNKNOWN
[libfirm] / ir / opt / proc_cloning.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Procedure cloning.
23  * @author  Beyhan Veliev, Michael Beck
24  * @version $Id$
25  * @summary
26  *
27  * The purpose is first to find and analyze functions, that are called
28  * with constant parameter(s).
29  * The second step is to optimize the function that are found from our
30  * analyze. Optimize mean to make a new function with parameters, that
31  * aren't be constant. The constant parameters of the function are placed
32  * in the function graph. They aren't be passed as parameters.
33  */
34 #include "config.h"
35
36 #include <string.h>
37
38 #include "iroptimize.h"
39 #include "tv.h"
40 #include "set.h"
41 #include "irprog_t.h"
42 #include "hashptr.h"
43 #include "irgwalk.h"
44 #include "analyze_irg_args.h"
45 #include "irprintf.h"
46 #include "ircons.h"
47 #include "irouts.h"
48 #include "irnode_t.h"
49 #include "irtools.h"
50 #include "irgmod.h"
51 #include "array_t.h"
52
53 /**
54  * This struct contains the information quadruple for a Call, which we need to
55  * decide if this function must be cloned.
56  */
57 typedef struct quadruple {
58         ir_entity       *ent;     /**< The entity of our Call. */
59         int             pos;      /**< Position of a constant argument of our Call. */
60         tarval          *tv;      /**< The tarval of this argument if Const node. */
61         ir_node         **calls;  /**< The list of all calls with the same characteristics */
62 } quadruple_t;
63
64 /**
65  * The quadruplets are hold in a sorted list
66  */
67 typedef struct entry {
68         quadruple_t  q;      /**< the quadruple */
69         float        weight; /**< its weight */
70         struct entry *next;  /**< link to the next one */
71 } entry_t;
72
73 typedef struct q_set {
74         struct obstack obst;        /**< an obstack containing all entries */
75         pset           *map;        /**< a hash map containing the quadruples */
76         entry_t        *heavy_uses; /**< the ordered list of heavy uses */
77 } q_set;
78
79 /**
80  * Compare two quadruplets.
81  *
82  * @return zero if they are identically, non-zero else
83  */
84 static int entry_cmp(const void *elt, const void *key) {
85         const entry_t *e1 = elt;
86         const entry_t *e2 = key;
87
88         return (e1->q.ent != e2->q.ent) || (e1->q.pos != e2->q.pos) || (e1->q.tv != e2->q.tv);
89 }
90
91 /**
92  * Hash an element of type entry_t.
93  *
94  * @param entry  The element to be hashed.
95  */
96 static int hash_entry(const entry_t *entry) {
97         return HASH_PTR(entry->q.ent) ^ HASH_PTR(entry->q.tv) ^ (entry->q.pos * 9);
98 }
99
100 /**
101  * Free memory associated with a quadruplet.
102  */
103 static void kill_entry(entry_t *entry) {
104         if (entry->q.calls) {
105                 DEL_ARR_F(entry->q.calls);
106                 entry->q.calls = NULL;
107         }
108 }
109
110 /**
111  * Process a call node.
112  *
113  * @param call    A ir_node to be checked.
114  * @param callee  The entity of the callee
115  * @param hmap    The quadruple-set containing the calls with constant parameters
116  */
117 static void process_call(ir_node *call, ir_entity *callee, q_set *hmap) {
118         ir_type *mtp;
119         entry_t *key, *entry;
120         ir_node *call_param;
121         int i, n_params;
122
123         n_params = get_Call_n_params(call);
124
125         /* Beware: we cannot clone variadic parameters as well as the
126          * last non-variadic one, which might be needed for the va_start()
127          * magic
128          */
129         mtp = get_Call_type(call);
130         if (get_method_variadicity(mtp) != variadicity_non_variadic) {
131                 n_params = get_method_first_variadic_param_index(mtp) - 1;
132         }
133
134         /* In this for loop we collect the calls, that have
135            an constant parameter. */
136         for (i = n_params - 1; i >= 0; --i) {
137                 call_param = get_Call_param(call, i);
138                 if (is_Const(call_param)) {
139                         /* we have found a Call to collect and we save the informations,
140                            which we need.*/
141                         if (! hmap->map)
142                                 hmap->map = new_pset(entry_cmp, 8);
143
144                         key = obstack_alloc(&hmap->obst, sizeof(*key));
145
146                         key->q.ent   = callee;
147                         key->q.pos   = i;
148                         key->q.tv    = get_Const_tarval(call_param);
149                         key->q.calls = NULL;
150                         key->weight  = 0.0F;
151                         key->next    = NULL;
152
153                         /* We insert our information in the set, where we collect the calls.*/
154                         entry = pset_insert(hmap->map, key, hash_entry(key));
155
156                         if (entry != key)
157                                 obstack_free(&hmap->obst, key);
158
159                         /* add the call to the list */
160                         if (! entry->q.calls) {
161                                 entry->q.calls = NEW_ARR_F(ir_node *, 1);
162                                 entry->q.calls[0] = call;
163                         } else
164                                 ARR_APP1(ir_node *, entry->q.calls, call);
165                 }
166         }
167 }
168
169 /**
170  * Collect all calls in a ir_graph to a set.
171  *
172  * @param call   A ir_node to be checked.
173  * @param env   The quadruple-set containing the calls with constant parameters
174  */
175 static void collect_irg_calls(ir_node *call, void *env) {
176         q_set *hmap = env;
177         ir_node *call_ptr;
178         ir_entity *callee;
179
180         /* We collect just "Call" nodes */
181         if (is_Call(call)) {
182                 call_ptr = get_Call_ptr(call);
183
184                 if (! is_Global(call_ptr))
185                         return;
186
187                 callee = get_Global_entity(call_ptr);
188
189                 /* we can only clone calls to existing entities */
190                 if (get_entity_visibility(callee) == visibility_external_allocated)
191                         return;
192
193                 /* we cannot clone calls to weak functions */
194                 if (get_entity_additional_properties(callee) & mtp_property_weak)
195                         return;
196
197                 process_call(call, callee, hmap);
198         }
199 }
200
201 /**
202  * Make a name for a clone. The clone name is
203  * the name of the original method suffixed with "_cl_pos_nr".
204  * pos is the pos from our quadruplet and nr is a counter.
205  *
206  * @param id  The ident of the cloned function.
207  * @param pos The "pos" from our quadruplet.
208  * @param nr  A counter for the clones.
209  */
210 static ident *get_clone_ident(ident *id, int pos, unsigned nr) {
211         char clone_postfix[32];
212
213         snprintf(clone_postfix, sizeof(clone_postfix), "_cl_%d_%u", pos, nr);
214
215         return mangle(id, new_id_from_str(clone_postfix));
216 }
217
218 /**
219  * Pre-Walker: Copies blocks and nodes from the original method graph
220  * to the cloned graph. Fixes the argument projection numbers for
221  * all arguments behind the removed one.
222  *
223  * @param irn  A node from the original method graph.
224  * @param env  The clone graph.
225  */
226 static void copy_nodes(ir_node *irn, void *env) {
227         ir_node *arg, *irg_args, *irn_copy;
228         int proj_nr;
229         ir_graph *clone_irg = env;
230
231         arg      = get_irg_link(clone_irg);
232         irg_args = get_Proj_pred(arg);
233
234         /* Copy all nodes except the arg. */
235         if (irn != arg)
236                 copy_irn_to_irg(irn, clone_irg);
237
238         irn_copy = get_irn_link(irn);
239
240         /* Fix argument numbers */
241         if (is_Proj(irn) && get_Proj_pred(irn) == irg_args) {
242                 proj_nr = get_Proj_proj(irn);
243                 if (get_Proj_proj(arg) < proj_nr)
244                         set_Proj_proj(irn_copy, proj_nr - 1);
245         }
246 }
247
248 /**
249  * Post-walker: Set the predecessors of the copied nodes.
250  * The copied nodes are set as link of their original nodes. The links of
251  * "irn" predecessors are the predecessors of copied node.
252  */
253 static void set_preds(ir_node *irn, void *env) {
254         int i;
255         ir_node *irn_copy, *pred, *arg;
256         ir_graph *clone_irg = env;
257
258         arg = get_irg_link(clone_irg);
259         /* Arg is the method argument, that we have replaced by a constant.*/
260         if (arg == irn)
261                 return;
262
263         irn_copy  = get_irn_link(irn);
264
265         if (is_Block(irn)) {
266                 set_Block_MacroBlock(irn_copy, get_irn_link(get_Block_MacroBlock(irn)));
267                 for (i = get_Block_n_cfgpreds(irn) - 1; i >= 0; i--) {
268                         pred = get_Block_cfgpred(irn, i);
269                         /* "End" block must be handled extra, because it is not matured.*/
270                         if (get_irg_end_block(current_ir_graph) == irn)
271                                 add_immBlock_pred(get_irg_end_block(clone_irg), get_irn_link(pred));
272                         else
273                                 set_Block_cfgpred(irn_copy, i, get_irn_link(pred));
274                 }
275         } else {
276                 /* First we set the block our copy if it is not a block.*/
277                 set_nodes_block(irn_copy, get_irn_link(get_nodes_block(irn)));
278                 if (is_End(irn)) {
279                         /* Handle the keep-alives. This must be done separately, because
280                            the End node was NOT copied */
281                         for (i = 0; i < get_End_n_keepalives(irn); ++i)
282                                 add_End_keepalive(irn_copy, get_irn_link(get_End_keepalive(irn, i)));
283                 } else {
284                         for (i = get_irn_arity(irn) - 1; i >= 0; i--) {
285                                 pred = get_irn_n(irn, i);
286                                 set_irn_n(irn_copy, i, get_irn_link(pred));
287                         }
288                 }
289         }
290 }
291
292 /**
293  * Get the method argument at the position "pos".
294  *
295  * @param irg  irg that must be cloned.
296  * @param pos  The position of the argument.
297  */
298 static ir_node *get_irg_arg(ir_graph *irg, int pos) {
299         ir_node *irg_args = get_irg_args(irg), *arg = NULL;
300         int i;
301
302         /* Call algorithm that computes the out edges */
303         assure_irg_outs(irg);
304
305         /* Search the argument with the number pos.*/
306         for (i = get_irn_n_outs(irg_args) - 1; i >= 0; --i) {
307                 ir_node *proj = get_irn_out(irg_args, i);
308                 if (pos == get_Proj_proj(proj)) {
309                         if (arg) {
310                                 /*
311                                  * More than one arg node found:
312                                  * We rely on the fact the only one arg exists, so do
313                                  * a cheap CSE in this case.
314                                  */
315                                 set_irn_out(irg_args, i, arg, 0);
316                                 exchange(proj, arg);
317                         } else
318                                 arg = proj;
319                 }
320         }
321         assert(arg && "Argument not found");
322         return arg;
323 }
324
325 /**
326  * Create a new graph for the clone of the method,
327  * that we want to clone.
328  *
329  * @param ent The entity of the method that must be cloned.
330  * @param q   Our quadruplet.
331  */
332 static void create_clone_proc_irg(ir_entity *ent, quadruple_t *q) {
333         ir_graph *method_irg, *clone_irg;
334         ir_node *arg, *const_arg;
335
336         method_irg = get_entity_irg(ent);
337
338         /* We create the skeleton of the clone irg.*/
339         clone_irg  = new_ir_graph(ent, 0);
340
341         arg        = get_irg_arg(get_entity_irg(q->ent), q->pos);
342         /* we will replace the argument in position "q->pos" by this constant. */
343         const_arg  = new_r_Const_type(
344                 clone_irg, get_nodes_block(arg), get_irn_mode(arg), q->tv,
345                 get_method_param_type(get_entity_type(q->ent), q->pos));
346
347         /* args copy in the cloned graph will be the const. */
348         set_irn_link(arg, const_arg);
349
350         /* Store the arg that will be replaced here, so we can easily detect it. */
351         set_irg_link(clone_irg, arg);
352
353         /* We copy the blocks and nodes, that must be in
354         the clone graph and set their predecessors. */
355         irg_walk_graph(method_irg, copy_nodes, set_preds, clone_irg);
356
357         /* The "cloned" graph must be matured. */
358         mature_immBlock(get_irg_end_block(clone_irg));
359         irg_finalize_cons(clone_irg);
360 }
361
362 /**
363  * The function create a new entity type
364  * for our clone and set it to clone entity.
365  *
366  * @param q   Contains information for the method to clone.
367  * @param ent The entity of the clone.
368  * @param nr  A pointer to the counter of clones.
369  **/
370 static void change_entity_type(quadruple_t *q, ir_entity *ent, unsigned *nr) {
371         ir_type *mtp, *new_mtp, *tp;
372         ident   *tp_name;
373         int     i, j, n_params, n_ress;
374
375         mtp      = get_entity_type(q->ent);
376         tp_name  = get_clone_ident(get_type_ident(mtp), q->pos, (*nr)++);
377         n_params = get_method_n_params(mtp);
378         n_ress   = get_method_n_ress(mtp);
379
380         /* Create the new type for our clone. It must have one parameter
381            less then the original.*/
382         new_mtp  = new_type_method(tp_name, n_params - 1, n_ress);
383
384         /* We must set the type of the methods parameters.*/
385         for (i = j = 0; i < n_params; ++i) {
386                 if (i == q->pos)
387                 /* This is the position of the argument, that we have
388                 replaced. */
389                 continue;
390
391                 tp = get_method_param_type(mtp, i);
392                 set_method_param_type(new_mtp, j++, tp);
393         }
394         /* Copy the methods result types. */
395         for (i = 0; i < n_ress; ++i) {
396                 tp = get_method_res_type(mtp, i);
397                 set_method_res_type(new_mtp, i, tp);
398         }
399         set_entity_type(ent, new_mtp);
400 }
401
402 /**
403  * Make a clone of a method.
404  *
405  * @param q   Contains information for the method to clone.
406  */
407 static ir_entity *clone_method(quadruple_t *q) {
408         ir_entity *new_entity;
409         ident *clone_ident;
410         ir_graph *rem;
411         symconst_symbol sym;
412         /* A counter for the clones.*/
413         static unsigned nr = 0;
414
415         /* We get a new ident for our clone method.*/
416         clone_ident = get_clone_ident(get_entity_ident(q->ent), q->pos, nr);
417         /* We get our entity for the clone method. */
418         new_entity  = copy_entity_name(q->ent, clone_ident);
419
420         /* a cloned entity is always local */
421         set_entity_visibility(new_entity, visibility_local);
422
423         /* set a ld name here: Should we mangle this ? */
424         set_entity_ld_ident(new_entity, get_entity_ident(new_entity));
425
426         /* set a new type here. */
427         change_entity_type(q, new_entity, &nr);
428
429         /* We need now a new ir_graph for our clone method. */
430         create_clone_proc_irg(new_entity, q);
431
432         /* We must set the atomic value of our "new_entity". */
433         sym.entity_p = new_entity;
434         rem = current_ir_graph;
435         current_ir_graph =  get_const_code_irg();
436         new_entity->value = new_SymConst(mode_P_code, sym, symconst_addr_ent);
437         current_ir_graph = rem;
438
439         /* The "new_entity" don't have this information. */
440         new_entity->attr.mtd_attr.param_access = NULL;
441         new_entity->attr.mtd_attr.param_weight = NULL;
442
443         return new_entity;
444 }
445
446 /**
447  * Creates a new "cloned" Call node and return it.
448  *
449  * @param call        The call that must be cloned.
450  * @param new_entity  The entity of the cloned function.
451  * @param pos         The position of the replaced parameter of this call.
452  **/
453 static ir_node *new_cl_Call(ir_node *call, ir_entity *new_entity, int pos) {
454         ir_node **in;
455         ir_type *mtp;
456         int i, n_params, new_params = 0;
457         ir_node *callee;
458         symconst_symbol sym;
459         ir_graph *irg = get_irn_irg(call);
460         ir_node *bl = get_nodes_block(call);
461
462         sym.entity_p = new_entity;
463         callee = new_r_SymConst(irg, bl, mode_P_code, sym, symconst_addr_ent);
464
465         mtp      = get_entity_type(new_entity);
466         n_params = get_Call_n_params(call);
467         NEW_ARR_A(ir_node *, in, n_params - 1);
468
469         /* we save the parameters of the new call in the array "in" without the
470          * parameter in position "pos", that is replaced with a constant.*/
471         for (i = 0; i < n_params; i++){
472                 if (pos != i)
473                         in[new_params++] = get_Call_param(call, i);
474         }
475         /* Create and return the new Call. */
476         return new_r_Call(irg, bl, get_Call_mem(call),
477                 callee, n_params - 1, in, get_entity_type(new_entity));
478 }
479
480 /**
481  * Exchange all Calls stored in the quadruplet to Calls of the cloned entity.
482  *
483  * @param q             The quadruple
484  * @param cloned_ent    The entity of the new function that must be called
485  *                      from the new Call.
486  */
487 static void exchange_calls(quadruple_t *q, ir_entity *cloned_ent) {
488         int pos = q->pos;
489         ir_node *new_call, *call;
490         int i;
491
492         /* We iterate the list of the "call".*/
493         for (i = 0; i < ARR_LEN(q->calls); ++i) {
494                 call = q->calls[i];
495
496                 /* A clone exist and the copy of "call" in this
497                  * clone graph must be exchanged with new one.*/
498                 new_call = new_cl_Call(call, cloned_ent, pos);
499                 exchange(call, new_call);
500         }
501 }
502
503 /**
504  * The weight formula:
505  * We save one instruction in every caller and param_weight instructions
506  * in the callee.
507  */
508 static float calculate_weight(const entry_t *entry) {
509         return ARR_LEN(entry->q.calls) *
510                 (float)(get_method_param_weight(entry->q.ent, entry->q.pos) + 1);
511 }
512
513 /**
514  * After we exchanged all calls, some entries on the list for
515  * the next cloned entity may get invalid, so we have to check
516  * them and may even update the list of heavy uses.
517  */
518 static void reorder_weights(q_set *hmap, float threshold) {
519         entry_t **adr, *p, *entry;
520         int i, len;
521         ir_entity *callee;
522
523 restart:
524         entry = hmap->heavy_uses;
525         if (! entry)
526                 return;
527
528         len = ARR_LEN(entry->q.calls);
529         for (i = 0; i < len; ++i) {
530                 ir_node *ptr, *call = entry->q.calls[i];
531
532                 /* might be exchanged, so skip Id nodes here. */
533                 call = skip_Id(call);
534
535                 /* we know, that a SymConst is here */
536                 ptr = get_Call_ptr(call);
537                 assert(is_SymConst(ptr));
538
539                 callee = get_SymConst_entity(ptr);
540                 if (callee != entry->q.ent) {
541                         /*
542                          * This call is already changed because of a previous
543                          * optimization. Remove it from the list.
544                          */
545                         --len;
546                         entry->q.calls[i] = entry->q.calls[len];
547                         entry->q.calls[len] = NULL;
548
549                         /* the new call should be processed */
550                         process_call(call, callee, hmap);
551                         --i;
552                 }
553         }
554
555         /* the length might be changed */
556         ARR_SHRINKLEN(entry->q.calls, len);
557
558         /* recalculate the weight and resort the heavy uses map */
559         entry->weight = calculate_weight(entry);
560
561         if (len <= 0 || entry->weight < threshold) {
562                 hmap->heavy_uses = entry->next;
563                 kill_entry(entry);
564
565                 /* we have changed the list, check the next one */
566                 goto restart;
567         }
568
569         adr = NULL;
570         for (p = entry->next; p && entry->weight < p->weight; p = p->next) {
571                 adr = &p->next;
572         }
573
574         if (adr) {
575                 hmap->heavy_uses = entry->next;
576                 entry->next      = *adr;
577                 *adr             = entry;
578                 entry            = hmap->heavy_uses;
579
580                 /* we have changed the list, check the next one */
581                 goto restart;
582         }
583 }
584
585 /*
586  * Do the procedure cloning. Evaluate a heuristic weight for every
587  * call(..., Const, ...). If the weight is bigger than threshold,
588  * clone the entity and fix the calls.
589  */
590 void proc_cloning(float threshold) {
591         entry_t *entry = NULL, *p;
592         ir_graph *irg;
593         int i;
594         q_set hmap;
595
596         obstack_init(&hmap.obst);
597         hmap.map        = NULL;
598         hmap.heavy_uses = NULL;
599
600         /* initially fill our map by visiting all irgs */
601         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
602                 irg = get_irp_irg(i);
603                 irg_walk_graph(irg, collect_irg_calls, NULL, &hmap);
604         }
605
606         /* We have the "Call" nodes to optimize in set "set_entries". Our algorithm
607            replace one constant parameter and make a new "Call" node for all found "Calls". It exchange the
608            old one with the new one and the algorithm is called with the new "Call".
609          */
610         while (hmap.map || hmap.heavy_uses) {
611                 /* We iterate the set and arrange the element of the set in a list.
612                    The elements are arranged dependent of their value descending.*/
613                 if (hmap.map) {
614                         foreach_pset(hmap.map, entry) {
615                                 entry->weight = calculate_weight(entry);
616
617                                 /*
618                                  * Do not put entry with a weight < threshold in the list
619                                  */
620                                 if (entry->weight < threshold) {
621                                         kill_entry(entry);
622                                         continue;
623                                 }
624
625                                 /* put entry in the heavy uses list */
626                                 entry->next = NULL;
627                                 if (! hmap.heavy_uses)
628                                         hmap.heavy_uses = entry;
629                                 else {
630                                         if (entry->weight >= hmap.heavy_uses->weight) {
631                                                 entry->next     = hmap.heavy_uses;
632                                                 hmap.heavy_uses = entry;
633                                         } else {
634                                                 for (p = hmap.heavy_uses; p->next; p = p->next) {
635                                                         if (entry->weight >= p->next->weight) {
636                                                                 entry->next = p->next;
637                                                                 p->next     = entry;
638                                                                 break;
639                                                         }
640                                                 }
641                                                 if (! p->next)
642                                                         p->next = entry;
643                                         }
644                                 }
645                         }
646                         del_pset(hmap.map);
647                         hmap.map = NULL;
648                 }
649
650                 /* Print some information about the list. */
651                 printf("-----------------\n");
652                 for (entry = hmap.heavy_uses; entry; entry = entry->next) {
653                         printf("\nweight: is %f\n", entry->weight);
654                         ir_printf("Call for Method %E\n", entry->q.ent);
655                         printf("Position %i\n", entry->q.pos);
656                         ir_printf("Value %T\n", entry->q.tv);
657                 }
658
659                 entry = hmap.heavy_uses;
660                 if (entry) {
661                         ir_entity *ent = clone_method(&entry->q);
662
663                         hmap.heavy_uses = entry->next;
664
665                         /* We must exchange the copies of this call in all clones too.*/
666                         exchange_calls(&entry->q, ent);
667                         kill_entry(entry);
668
669                         /*
670                          * after we exchanged all calls, some entries on the list for
671                          * the next cloned entity may get invalid, so we have to check
672                          * them and may even update the list of heavy uses.
673                          */
674                         reorder_weights(&hmap, threshold);
675                 }
676         }
677         obstack_free(&hmap.obst, NULL);
678 }