added header file for GVN-PRE
[libfirm] / ir / opt / proc_cloning.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/proc_cloning.c
4  * Purpose:     procedure cloning
5  * Author:      Beyhan Veliev
6  * Created:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 1998-2005 Universität Karlsruhe
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11
12 /**
13  * @file proc_cloning.c
14  *
15  * The purpose is first to find and analyze functions, that are called
16  * with constant parameter(s).
17  * The second step is to optimize the function that are found from our
18  * analyze. Optimize mean to make a new function with parameters, that
19  * aren't be constant. The constant parameters of the function are placed
20  * in the function graph. They aren't be passed as parameters.
21  *
22  */
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <string.h>
28
29 #include "tv.h"
30 #include "set.h"
31 #include "entity.h"
32 #include "irprog_t.h"
33 #include "hashptr.h"
34 #include "irgwalk.h"
35 #include "proc_cloning.h"
36 #include "analyze_irg_args.h"
37 #include "irprintf.h"
38 #include "old_fctnames.h"
39 #include "ircons.h"
40 #include "loop_unrolling.h"
41 #include "irouts.h"
42 #include "mangle.h"
43 #include "irnode_t.h"
44 #include "irtools.h"
45 #include "irgmod.h"
46
47 /* A macro to iterate sets.*/
48 #define ITERATE_SET(set_entries, entry) for(entry = set_first(set_entries); entry; entry = set_next(set_entries))
49
50 /**
51  * This struct contains the information quadruple for a Call, which we need to
52  * decide if this function must be cloned.
53  */
54 typedef struct quadruple {
55   entity          *ent;     /**< The entity of our Call. */
56   int             pos;      /**< Position of a constant argument of our Call. */
57   tarval          *tv;      /**< The tarval of this argument if Const node. */
58   ir_node         **calls;  /**< The list of all calls with the same characteristics */
59 } quad_t;
60
61 /**
62  * The quadruplets are hold in a sorted list
63  */
64 typedef struct entry {
65   quad_t       q;      /**< the quadruple */
66   float        weight; /**< its weight */
67   struct entry *next;  /**< link to the next one */
68 } entry_t;
69
70 typedef struct q_set {
71   struct obstack obst;        /**< an obstack containing all entries */
72   pset           *map;        /**< a hash map containing the quadruples */
73   entry_t        *heavy_uses; /**< the ordered list of heavy uses */
74 } q_set;
75
76 /**
77  * Compare two quadruples.
78  *
79  * @return 0 if they are identically
80  */
81 static int entry_cmp(const void *elt, const void *key)
82 {
83   const entry_t *e1 = elt;
84   const entry_t *e2 = key;
85
86   return (e1->q.ent != e2->q.ent) || (e1->q.pos != e2->q.pos) || (e1->q.tv != e2->q.tv);
87 }
88
89 /**
90  * Hash a element of typ entry_t
91  *
92  * @param entry The element to be hashed.
93  */
94 static int hash_entry(const entry_t *entry)
95 {
96   return HASH_PTR(entry->q.ent) ^ HASH_PTR(entry->q.tv) ^ (entry->q.pos * 9);
97 }
98
99 /**
100  * free memory associated with a quadruplet
101  */
102 static void kill_entry(entry_t *entry) {
103   if (entry->q.calls) {
104     DEL_ARR_F(entry->q.calls);
105     entry->q.calls = NULL;
106   }
107 }
108
109 /**
110  * Process a call node
111  *
112  * @param call    A ir_node to be checked.
113  * @param callee  The entity of the callee
114  * @param hmap    The quadruple-set containing the calls with constant parameters
115  */
116 static void process_call(ir_node *call, entity *callee, q_set *hmap)
117 {
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       }
164       else
165         ARR_APP1(ir_node *, entry->q.calls, call);
166     }
167   }
168 }
169
170 /**
171  * Collect all calls in a ir_graph to a set.
172  *
173  * @param call   A ir_node to be checked.
174  * @param env   The quadruple-set containing the calls with constant parameters
175  */
176 static void collect_irg_calls(ir_node *call, void *env)
177 {
178   q_set *hmap = env;
179   ir_node *call_ptr;
180   entity *callee;
181
182   /* We collect just "Call" nodes*/
183   if (get_irn_op(call) == op_Call) {
184     call_ptr = get_Call_ptr(call);
185
186     /* Call pointer must be a symconst*/
187     if (op_SymConst != get_irn_op(call_ptr))
188       return;
189     /* Call pointer must be the address of an entity.*/
190     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
191       return;
192
193     callee = get_SymConst_entity(call_ptr);
194
195     /* we can only clone calls to existing entities */
196     if (get_entity_visibility(callee) == visibility_external_allocated)
197       return;
198
199     process_call(call, callee, hmap);
200   }
201 }
202
203 /**
204  * Make a name for the clone. The clone name is
205  * the name of the original method advanced with "_cl_pos_nr".
206  * pos is the pos from our quadruplet and nr is a counter.
207  *
208  * @param id  The ident of the cloned function.
209  * @param pos The "pos" from our quadruplet.
210  * @param nr  A counter for the clones.
211  */
212 static ident *get_clone_ident(ident *id, int pos, unsigned nr)
213 {
214   char clone_postfix[32];
215
216   snprintf(clone_postfix, sizeof(clone_postfix), "_cl_%d_%u", pos, nr);
217
218   return mangle(id, new_id_from_str(clone_postfix));
219 }
220
221 /**
222  * The function fill the blocks and nodes, that muss be in
223  * the clone graph, from the original method graph. The cloned method
224  * have one argument few, why it is replaced with a constant.
225  *
226  * @param irn  A node from the original method graph.
227  * @param env  The clone graph.
228  */
229 static void fill_clone_irg(ir_node *irn, void *env)
230 {
231   ir_node *arg, *irg_args, *irn_copy, *link;
232   int proj_nr;
233   ir_graph *clone_irg;
234
235   clone_irg = env;
236   arg       = get_irg_link(clone_irg);
237   irg_args  = get_Proj_pred(arg);
238
239   if (get_irn_op(irn) == op_Call)
240     link = get_irn_link(irn);
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   if (get_irn_op(irn) == op_Call)
249     irn_copy->link = link;
250
251   /* Fix argument numbers */
252   if (get_irn_op(irn) == op_Proj && get_Proj_pred(irn) == irg_args) {
253     proj_nr = get_Proj_proj(irn);
254     if (get_Proj_proj(arg) < proj_nr)
255       set_Proj_proj(irn_copy, proj_nr - 1);
256   }
257 }
258
259 /**
260  * Set the predecessors of the copied nodes.
261  * The copied nodes are set as link of their original nodes. The links of
262  * "irn" predecessors are the predecessors of copied node.
263  */
264 static void set_preds(ir_node *irn, void *env)
265 {
266   int i;
267   ir_node *irn_copy, *pred, *arg;
268   ir_graph *clone_irg = env;
269
270   arg = get_irg_link(clone_irg);
271   /* Arg is the method argument, that we have replaced by a constant.*/
272   if (arg == irn)
273     return;
274
275   irn_copy  = get_irn_link(irn);
276
277   if (is_Block(irn)) {
278     for (i = get_Block_n_cfgpreds(irn) - 1; i >= 0; i--) {
279       pred = get_Block_cfgpred(irn, i);
280       /* "End" block must be handled extra, because it is not matured.*/
281       if (get_irg_end_block(current_ir_graph) == irn)
282         add_immBlock_pred(get_irg_end_block(clone_irg), get_irn_link(pred));
283       else
284         set_Block_cfgpred(irn_copy, i, get_irn_link(pred));
285     }
286   }
287   else {
288     /* First we set the block our copy if it is not a block.*/
289     set_nodes_block(irn_copy, get_irn_link(get_nodes_block(irn)));
290     if (get_irn_op(irn) == op_End) {
291       /* Handle the keep-alives. This must be done separately, because
292          the End node was NOT copied */
293       for (i = 0; i < get_End_n_keepalives(irn); ++i)
294         add_End_keepalive(irn_copy, get_irn_link(get_End_keepalive(irn, i)));
295     }
296     else {
297       for (i = get_irn_arity(irn) - 1; i >= 0; i--) {
298         pred = get_irn_n(irn, i);
299         set_irn_n(irn_copy, i, get_irn_link(pred));
300       }
301     }
302   }
303 }
304
305 /**
306  * Get the method argument at the position "pos".
307  *
308  * @param irg  irg that must be cloned.
309  * @param pos  The position of the argument.
310  */
311 static ir_node *get_irg_arg(ir_graph *irg, int pos)
312 {
313   ir_node *irg_args = get_irg_args(irg), *arg = NULL;
314   int i;
315
316   /* Call algorithm that computes the out edges */
317   if (get_irg_outs_state(irg) != outs_consistent)
318     compute_outs(irg);
319
320   /* Search the argument with the number pos.*/
321   for (i = get_irn_n_outs(irg_args) - 1; i >= 0; --i) {
322     ir_node *proj = get_irn_out(irg_args, i);
323     if (pos == get_Proj_proj(proj)) {
324       if (arg) {
325         /*
326          * More than one arg node found:
327          * We rely on the fact the only one arg exists, so do
328          * a cheap CSE in this case.
329          */
330         set_irn_out(irg_args, i, arg);
331         exchange(proj, arg);
332       }
333       else
334         arg = proj;
335     }
336   }
337   assert(arg && "Argument not found");
338   return arg;
339 }
340
341 /**
342  * Create a new graph for the clone of the method,
343  * that we want to clone.
344  *
345  * @param ent The entity of the method that must be cloned.
346  * @param q   Our quadruple.
347  */
348 static void create_clone_proc_irg(entity *ent, quad_t *q)
349 {
350   ir_graph *method_irg, *clone_irg;
351   ir_node *arg, *const_arg;
352   int loc_n;
353
354   method_irg = get_entity_irg(ent);
355
356   /* The ir graph of the cloned procedure have one local few,
357      because one of the arguments is replaced by a constant. */
358   loc_n      = get_irg_n_loc(method_irg) - 1;
359
360   /* We create the skeleton of the clone irg.*/
361   clone_irg  = new_ir_graph(ent, loc_n);
362
363   arg        = get_irg_arg(get_entity_irg(q->ent), q->pos);
364   /* we will replace the argument in position "q->pos" by this constant. */
365   const_arg  = new_r_Const_type(
366     clone_irg, get_nodes_block(arg), get_irn_mode(arg), q->tv,
367     get_method_param_type(get_entity_type(q->ent), q->pos));
368
369   /* We have this nodes in the new ir_graph, and they must not be copied.*/
370   set_irn_link(arg, const_arg);
371
372   /* I need this, because "irg_walk_graph" change "current_ir_graph" to passed irg.*/
373   set_irg_link(clone_irg, arg);
374
375   /* We fill the blocks and nodes, that must be in
376      the clone graph and set their preds.*/
377   irg_walk_graph(method_irg, fill_clone_irg, set_preds, clone_irg);
378
379   /* The "cloned" ir_graph must be corrected. */
380   mature_block(get_irg_end_block(clone_irg));
381   irg_finalize_cons(clone_irg);
382 }
383
384 /**
385  * The function create a new entity type
386  * for our clone and set it to clone entity.
387  *
388  * @param q   Contains information
389  *            for the method to clone.
390  * @param ent The entity of the clone.
391  * @param nr  A pointer to the counter of clones.
392  **/
393 static void change_entity_type(quad_t *q, entity *ent, unsigned *nr)
394 {
395   ir_type *mtp, *new_mtp, *tp;
396   ident   *tp_name;
397   int     i, j, n_params, n_ress;
398
399   mtp      = get_entity_type(q->ent);
400   tp_name  = get_clone_ident(get_type_ident(mtp), q->pos, (*nr)++);
401   n_params = get_method_n_params(mtp);
402   n_ress   = get_method_n_ress(mtp);
403
404   /* Create the new type for our clone. It must have one parameter
405      less then the original.*/
406   new_mtp  = new_type_method(tp_name, n_params - 1, n_ress);
407
408   /* We must set the type of the methods parameters.*/
409   for (i = j = 0; i < n_params; ++i) {
410     if (i == q->pos)
411       /* This is the position of the argument, that we have
412          replaced. */
413       continue;
414
415     tp = get_method_param_type(mtp, i);
416     set_method_param_type(new_mtp, j++, tp);
417   }
418   /* We must set the type of the methods results.*/
419   for (i = 0; i < n_ress; ++i) {
420     tp = get_method_res_type(mtp, i);
421     set_method_res_type(new_mtp, i, tp);
422   }
423   set_entity_type(ent, new_mtp);
424 }
425
426 /**
427  * Make a clone of a method.
428  *
429  * @param q   Contains information
430  *            for the method to clone.
431  */
432 static entity *clone_method(quad_t *q)
433 {
434   entity *new_entity;
435   ident *clone_ident;
436   ir_graph *rem;
437   symconst_symbol sym;
438   /* A counter for the clones.*/
439   static unsigned nr = 0;
440
441   /* We get a new ident for our clone method.*/
442   clone_ident = get_clone_ident(get_entity_ident(q->ent), q->pos, nr);
443   /* We get our entity for the clone method. */
444   new_entity  = copy_entity_name(q->ent, clone_ident);
445
446   /* a cloned entity is always local */
447   set_entity_visibility(new_entity, visibility_local);
448
449   /* set a ld name here: Should we mangle this ? */
450   set_entity_ld_ident(new_entity, get_entity_ident(new_entity));
451
452   /* set a new type here.*/
453   change_entity_type(q, new_entity, &nr);
454
455   /* We need now a new ir_graph for our clone method. */
456   create_clone_proc_irg(new_entity, q);
457   /* We must set the atomic value of our "new_entity". */
458   sym.entity_p = new_entity;
459   rem = current_ir_graph;
460   current_ir_graph =  get_const_code_irg();
461   new_entity->value = new_SymConst(sym, symconst_addr_ent);
462   current_ir_graph = rem;
463
464   /* The "new_entity" have not this information. */
465   new_entity->param_access = NULL;
466   new_entity->param_weight = NULL;
467
468   return new_entity;
469 }
470
471 /** The function make a new "Call" node and return it.
472  *
473  * @param call        The call, that muss be exchanged.
474  * @param new_entity  The entity of the cloned function.
475  * @param pos         The position of the replaced parameter of this call.
476  **/
477 static ir_node *new_cl_Call(ir_node *call, entity *new_entity, int pos)
478 {
479   ir_node **in;
480   ir_type *mtp;
481   int i, n_params, new_params = 0;
482   ir_node *callee;
483   symconst_symbol sym;
484
485   sym.entity_p = new_entity;
486   callee = new_r_SymConst(get_irn_irg(call), get_nodes_block(call), sym, symconst_addr_ent);
487
488   mtp      = get_entity_type(new_entity);
489   n_params = get_Call_n_params(call);
490   in       = malloc(sizeof(ir_node*) * (n_params - 1));
491
492   /* we save the parameters of the new call in the array "in" without the
493    * parameter in position "pos", that is replaced with a constant.*/
494   for(i = 0; i < n_params; i++){
495     if(pos == i)
496       continue;
497     in[new_params] = get_Call_param(call, i);
498     new_params++;
499   }
500   /* We make and return the new call.*/
501   return new_r_Call(get_irn_irg(call), get_nodes_block(call), get_Call_mem(call),
502                     callee, n_params - 1, in, get_entity_type(new_entity));
503 }
504
505 /**
506  * Exchange all Calls now to Calls of the cloned entity
507  *
508  * @param q             The quadruple
509  * @param cloned_ent    The entity of the new function, that must be called from the new call.
510  */
511 static void exchange_calls(quad_t *q, entity *cloned_ent)
512 {
513   int pos = q->pos;
514   ir_node *new_call, *call;
515   int i;
516
517   /* We iterate the list of the "call".*/
518   for (i = 0; i < ARR_LEN(q->calls); ++i) {
519     call = q->calls[i];
520
521     /* A clone exist and the copy of "call" in this
522      * clone graph must be exchanged with new one.*/
523     new_call = new_cl_Call(call, cloned_ent, pos);
524     exchange(call, new_call);
525   }
526 }
527
528 /**
529  * The weight formula:
530  * We save one instruction in every caller and param_weight instructions
531  * in the callee.
532  */
533 static float calculate_weight(const entry_t *entry) {
534   return ARR_LEN(entry->q.calls) *
535     (get_method_param_weight(entry->q.ent, entry->q.pos) + 1);
536 }
537
538 /*
539  * after we exchanged all calls, some entries on the list for
540  * the next cloned entity may get invalid, so we have to check
541  * them and may even update the list of heavy uses.
542  */
543 static void reorder_weights(q_set *hmap, float threshold)
544 {
545   entry_t **adr, *p, *entry;
546   int i, len;
547   entity *callee;
548
549 restart:
550   entry = hmap->heavy_uses;
551   if (! entry)
552     return;
553
554   len = ARR_LEN(entry->q.calls);
555   for (i = 0; i < len; ++i) {
556     ir_node *ptr, *call = entry->q.calls[i];
557
558     /* might be exchanged */
559     call = skip_Id(call);
560
561     /* we know, that a SymConst is here */
562     ptr = get_Call_ptr(call);
563     assert(get_irn_op(ptr) == op_SymConst);
564
565     callee = get_SymConst_entity(ptr);
566     if (callee != entry->q.ent) {
567       /*
568        * This call is already changed because of a previous
569        * optimization. Remove it from the list.
570        */
571       len -= 1;
572       entry->q.calls[i] = entry->q.calls[len];
573       entry->q.calls[len] = NULL;
574
575       /* the new call should be processed */
576       process_call(call, callee, hmap);
577     }
578   }
579
580   /* the length might be changed */
581   ARR_SHRINKLEN(entry->q.calls, len);
582
583   /* recalculate the weight and resort the heavy uses map */
584   entry->weight = calculate_weight(entry);
585
586   if (len <= 0 || entry->weight < threshold) {
587     hmap->heavy_uses = entry->next;
588     kill_entry(entry);
589
590     /* we have changed the list, check the next one */
591     goto restart;
592   }
593
594   adr = NULL;
595   for (p = entry->next; p && entry->weight < p->weight; p = p->next) {
596     adr = &p->next;
597   }
598
599   if (adr) {
600     hmap->heavy_uses = entry->next;
601     entry->next      = *adr;
602     *adr             = entry;
603     entry            = hmap->heavy_uses;
604
605     /* we have changed the list, check the next one */
606     goto restart;
607   }
608 }
609
610 /*
611  * Do the procedure cloning. Evaluate a heuristic weight for every
612  * call(..., Const, ...). If the weight is bigger than threshold,
613  * clone the entity and fix the calls.
614  */
615 void proc_cloning(float threshold)
616 {
617   entry_t *entry = NULL, *p;
618   ir_graph *irg;
619   int i, count = 0;
620   q_set hmap;
621
622   obstack_init(&hmap.obst);
623   hmap.map        = NULL;
624   hmap.heavy_uses = NULL;
625
626   /* initially fill our map by visiting all irgs */
627   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
628     irg = get_irp_irg(i);
629     irg_walk_graph(irg, collect_irg_calls, NULL, &hmap);
630   }
631
632   /* We have the "Call" nodes to optimize in set "set_entries". Our algorithm
633      replace one constant parameter and make a new "Call" node for all found "Calls". It exchange the
634      old one with the new one and the algorithm is called with the new "Call".
635      */
636   while (hmap.map || hmap.heavy_uses) {
637     /* We iterate the set and arrange the element of the set in a list.
638        The elements are arranged dependent of their value descending.*/
639     if (hmap.map) {
640       for (entry = pset_first(hmap.map); entry; entry = pset_next(hmap.map)) {
641         entry->weight = calculate_weight(entry);
642
643         /*
644          * Do not put entry with a weight < threshold in the list
645          */
646         if (entry->weight < threshold) {
647           kill_entry(entry);
648           continue;
649         }
650
651         /* put entry in the heavy uses list */
652         entry->next = NULL;
653         if (! hmap.heavy_uses)
654           hmap.heavy_uses = entry;
655         else {
656           if (entry->weight >= hmap.heavy_uses->weight) {
657             entry->next     = hmap.heavy_uses;
658             hmap.heavy_uses = entry;
659           }
660           else {
661             for (p = hmap.heavy_uses; p->next; p = p->next) {
662               if (entry->weight >= p->next->weight) {
663                 entry->next = p->next;
664                 p->next     = entry;
665                 break;
666               }
667             }
668             if (! p->next)
669               p->next = entry;
670           }
671         }
672       }
673       del_pset(hmap.map);
674       hmap.map = NULL;
675     }
676
677     /* Print some information about the list. */
678     printf("-----------------\n");
679     for (entry = hmap.heavy_uses; entry; entry = entry->next) {
680       printf("\nweight: is %f\n", entry->weight);
681       ir_printf("Call for Method %E\n", entry->q.ent);
682       printf("Position %i\n", entry->q.pos);
683       ir_printf("Value %T\n", entry->q.tv);
684     }
685
686     entry = hmap.heavy_uses;
687     if (entry) {
688       entity *ent = clone_method(&entry->q);
689
690       hmap.heavy_uses = entry->next;
691
692       /* We must exchange the copies of this call in all clones too.*/
693       exchange_calls(&entry->q, ent);
694       kill_entry(entry);
695
696       /*
697        * after we exchanged all calls, some entries on the list for
698        * the next cloned entity may get invalid, so we have to check
699        * them and may even update the list of heavy uses.
700        */
701       reorder_weights(&hmap, threshold);
702     }
703   }
704   obstack_free(&hmap.obst, NULL);
705 }