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