doxygen docu improved
[libfirm] / ir / opt / scalar_replace.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/scalar_replace.c
4  * Purpose:     scalar replacement of arrays and compounds
5  * Author:      Beyhan Veliev
6  * Modified by: Michael Beck
7  * Created:
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1998-2005 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12 #ifdef HAVE_CONFIG_H
13 #include "config.h"
14 #endif
15
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19
20 #ifdef HAVE_MALLOC_H
21 #include <malloc.h>
22 #endif
23
24 #ifdef HAVE_STRING_H
25 #include <string.h>
26 #endif
27
28 #include "scalar_replace.h"
29 #include "irflag_t.h"
30 #include "irouts.h"
31 #include "set.h"
32 #include "pset.h"
33 #include "array.h"
34 #include "tv.h"
35 #include "ircons_t.h"
36 #include "hashptr.h"
37 #include "irgwalk.h"
38 #include "irgmod.h"
39 #include "irnode_t.h"
40 #include "irtools.h"
41
42 #define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
43 #define GET_VNUM(node)       (unsigned)PTR_TO_INT(get_irn_link(node))
44
45 /**
46  * A path element entry: it is either an entity
47  * or a tarval, because we evaluate only constant array
48  * accesses like a.b.c[8].d
49  */
50 typedef union {
51   entity *ent;
52   tarval *tv;
53 } path_elem_t;
54
55 /**
56  * An access path, used to assign value numbers
57  * to variables that will be scalar replaced
58  */
59 typedef struct _path_t {
60   unsigned    vnum;      /**< the value number */
61   unsigned    path_len;  /**< the length of the access path */
62   path_elem_t path[1];   /**< the path */
63 } path_t;
64
65 typedef struct _scalars_t {
66   entity *ent;                 /**< A entity for scalar replacement. */
67   ir_type *ent_owner;          /**< The owner of this entity. */
68 } scalars_t;
69
70
71 /**
72  * Compare two pathes.
73  *
74  * @return 0 if they are identically
75  */
76 static int path_cmp(const void *elt, const void *key, size_t size)
77 {
78   const path_t *p1 = elt;
79   const path_t *p2 = key;
80
81   /* we can use memcmp here, because identical tarvals should have identical addresses */
82   return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
83 }
84
85 /**
86  * Compare two elements of the scalars_t set.
87  *
88  * @return 0 if they are identically
89  */
90 static int ent_cmp(const void *elt, const void *key, size_t size)
91 {
92   const scalars_t *c1 = elt;
93   const scalars_t *c2 = key;
94
95   return c1->ent != c2->ent;
96 }
97
98 /**
99  * Calculate a hash value for a path.
100  */
101 static unsigned path_hash(const path_t *path)
102 {
103   unsigned hash = 0;
104   unsigned i;
105
106   for (i = 0; i < path->path_len; ++i)
107     hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
108
109   return hash >> 4;
110 }
111
112 /**
113  * Returns non-zero, if all indeces of a Sel node are constants.
114  *
115  * @param sel  the Sel node that will be checked
116  */
117 static int is_const_sel(ir_node *sel) {
118   int i, n = get_Sel_n_indexs(sel);
119
120   for (i = 0; i < n; ++i) {
121     ir_node *idx = get_Sel_index(sel, i);
122
123     if (get_irn_op(idx) != op_Const)
124       return 0;
125   }
126   return 1;
127 }
128
129 /*
130  * Returns non-zero, if the address of an entity
131  * represented by a Sel node (or it's successor Sels) is taken.
132  */
133 int is_address_taken(ir_node *sel)
134 {
135   int i;
136
137   if (! is_const_sel(sel))
138     return 1;
139
140   for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
141     ir_node *succ = get_irn_out(sel, i);
142
143     switch (get_irn_opcode(succ)) {
144     case iro_Load:
145       /* ok, we just load from that entity */
146       break;
147
148     case iro_Store:
149       /* check that Sel is not the Store's value */
150       if (get_Store_value(succ) == sel)
151         return 1;
152       break;
153
154     case iro_Sel: {
155       /* Check the Sel successor of Sel */
156       int res = is_address_taken(succ);
157
158       if (res)
159         return 1;
160       break;
161     }
162
163     case iro_Call:
164       /* The address of an entity is given as a parameter.
165        * As long as we do not have analyses that can tell what
166        * is done with parameters, think is taken.
167        */
168       return 1;
169
170     default:
171       /* another op, the address is taken */
172       return 1;
173     }
174   }
175   return 0;
176 }
177
178 /**
179  * Link all leave Sels with the entity.
180  *
181  * @param ent  the entity that will be scalar replaced
182  * @param sel  a Sel node that selects some fields of this entity
183  */
184 static void link_all_leave_sels(entity *ent, ir_node *sel)
185 {
186   int i, n, flag = 1;
187
188   n = get_irn_n_outs(sel);
189   for (i = 0; i < n; ++i) {
190     ir_node *succ = get_irn_out(sel, i);
191
192     if (is_Sel(succ)) {
193       link_all_leave_sels(ent, succ);
194       flag = 0;
195     }
196   }
197
198   if (flag) {
199     /* if Sel nodes with memory inputs are used, a entity can be
200      * visited more than once causing a ring here, so we use the
201      * node flag to mark linked nodes
202      */
203     if (irn_visited(sel))
204       return;
205
206     /* we know we are at a leave, because this function is only
207      * called if the address is NOT taken, so succ must be a Load
208      * or a Store node
209      */
210     set_irn_link(sel, get_entity_link(ent));
211     set_entity_link(ent, sel);
212
213     mark_irn_visited(sel);
214   }
215 }
216
217 /* we need a special address that serves as an address taken marker */
218 static char _x;
219 static void *ADDRESS_TAKEN = &_x;
220
221 /**
222  * Find possible scalar replacements.
223  *
224  * @param irg  an IR graph
225  *
226  * This function finds variables on the (members of the) frame type
227  * that can be scalar replaced, because their address is never taken.
228  * If such a variable is found, it's entity link will hold a list of all
229  * Sel nodes, that selects the atomic fields of this entity.
230  * Otherwise, the link will be ADDRESS_TAKEN or NULL.
231  *
232  * @return  non-zero if at least one entity could be replaced
233  *          potentially
234  */
235 static int find_possible_replacements(ir_graph *irg)
236 {
237   ir_node *irg_frame = get_irg_frame(irg);
238   int i, n;
239   int res = 0;
240
241   inc_irg_visited(irg);
242
243   n = get_irn_n_outs(irg_frame);
244
245   /*
246    * First, clear the link field of all interesting entities.
247    * Note that we did not rely on the fact that there is only
248    * one Sel node per entity, so we might access one entity
249    * more than once here.
250    * That's why we have need two loops.
251    */
252   for (i = 0; i < n; ++i) {
253     ir_node *succ = get_irn_out(irg_frame, i);
254
255     if (is_Sel(succ)) {
256       entity *ent = get_Sel_entity(succ);
257       set_entity_link(ent, NULL);
258     }
259   }
260
261   /*
262    * Check the ir_graph for Sel nodes. If the entity of Sel
263    * isn't a scalar replacement set the link of this entity
264    * equal ADDRESS_TAKEN.
265    */
266   for (i = 0; i < n; ++i) {
267     ir_node *succ = get_irn_out(irg_frame, i);
268
269     if (is_Sel(succ)) {
270       entity *ent = get_Sel_entity(succ);
271       ir_type *ent_type;
272
273       if (get_entity_link(ent) == ADDRESS_TAKEN)
274         continue;
275
276       /*
277        * Beware: in rare cases even entities on the frame might be
278        * volatile. This might happen if the entity serves as a store
279        * to a value that must survive a exception. Do not optimize
280        * such entities away.
281        */
282       if (get_entity_volatility(ent) == volatility_is_volatile) {
283         set_entity_link(ent, ADDRESS_TAKEN);
284         continue;
285       }
286
287       ent_type = get_entity_type(ent);
288
289       /* we can handle arrays, structs and atomic types yet */
290       if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
291         if (is_address_taken(succ)) {
292           if (get_entity_link(ent)) /* killing one */
293             --res;
294           set_entity_link(ent, ADDRESS_TAKEN);
295         }
296         else {
297           /* possible found one */
298           if (get_entity_link(ent) == NULL)
299             ++res;
300           link_all_leave_sels(ent, succ);
301         }
302       }
303     }
304   }
305
306   return res;
307 }
308
309 /**
310  * Return a path from the Sel node sel to it's root.
311  *
312  * @param sel  the Sel node
313  * @param len  the length of the path so far
314  */
315 static path_t *find_path(ir_node *sel, unsigned len)
316 {
317   int pos, i, n;
318   path_t *res;
319   ir_node *pred = get_Sel_ptr(sel);
320
321   /* the current Sel node will add some path elements */
322   n    = get_Sel_n_indexs(sel);
323   len += n + 1;
324
325   if (! is_Sel(pred)) {
326     /* we found the root */
327
328     res = xmalloc(sizeof(*res) + (len - 1) * sizeof(res->path));
329     res->path_len = len;
330   }
331   else
332     res = find_path(pred, len);
333
334   pos = res->path_len - len;
335
336   res->path[pos++].ent = get_Sel_entity(sel);
337   for (i = 0; i < n; ++i) {
338     ir_node *index = get_Sel_index(sel, i);
339
340     res->path[pos++].tv = get_Const_tarval(index);
341   }
342   return res;
343 }
344
345
346 /**
347  * Allocate value numbers for the leaves
348  * in our found entities.
349  *
350  * @param sels  a set that will contain all Sels that have a value number
351  * @param ent   the entity that will be scalar replaced
352  * @param vnum  the first value number we can assign
353  * @param modes a flexible array, containing all the modes of
354  *              the value numbers.
355  *
356  * @return the next free value number
357  */
358 static unsigned allocate_value_numbers(pset *sels, entity *ent, unsigned vnum, ir_mode ***modes)
359 {
360   ir_node *sel, *next;
361   path_t *key, *path;
362   set *pathes = new_set(path_cmp, 8);
363
364   /* visit all Sel nodes in the chain of the entity */
365   for (sel = get_entity_link(ent); sel; sel = next) {
366     next = get_irn_link(sel);
367
368     /* we must mark this sel for later */
369     pset_insert_ptr(sels, sel);
370
371     key  = find_path(sel, 0);
372     path = set_find(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
373
374     if (path)
375       SET_VNUM(sel, path->vnum);
376     else {
377       unsigned i;
378
379       key->vnum = vnum++;
380
381       set_insert(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
382
383       SET_VNUM(sel, key->vnum);
384       ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
385
386       (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
387
388       assert((*modes)[key->vnum] && "Value is not atomic");
389
390 #ifdef DEBUG_libfirm
391       /* Debug output */
392       if (get_opt_scalar_replacement_verbose() && get_firm_verbosity() > 1) {
393         printf("  %s", get_entity_name(ent));
394         for (i = 1; i < key->path_len; ++i) {
395           if (is_entity(key->path[i].ent))
396             printf(".%s", get_entity_name(key->path[i].ent));
397           else
398             printf("[%ld]", get_tarval_long(key->path[i].tv));
399         }
400         printf(" = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum]));
401       }
402 #endif /* DEBUG_libfirm */
403     }
404     free(key);
405   }
406
407   del_set(pathes);
408   set_entity_link(ent, NULL);
409   return vnum;
410 }
411
412 /**
413  * A list entry for the fixing lists
414  */
415 typedef struct _list_entry_t {
416   ir_node  *node;   /**< the node that must be fixed */
417   unsigned vnum;    /**< the value number of this node */
418 } list_entry_t;
419
420 /**
421  * environment for memory walker
422  */
423 typedef struct _env_t {
424   struct obstack obst;      /**< a obstack for the value blocks */
425   int          nvals;       /**< number of values */
426   ir_mode      **modes;     /**< the modes of the values */
427   list_entry_t *fix_phis;   /**< list of all Phi nodes that must be fixed */
428   list_entry_t *fix_loads;  /**< list of all Load nodes that must be fixed */
429   pset         *sels;       /**< A set of all Sel nodes that have a value number */
430 } env_t;
431
432 /**
433  * Walker
434  */
435 static void handle_first(ir_node *node, void *ctx)
436 {
437   env_t        *env = ctx;
438   ir_op        *op = get_irn_op(node);
439   ir_node      *adr, *block, *mem, *unk, **value_arr, **in;
440   unsigned     vnum;
441   int          i, j, n;
442   list_entry_t *l;
443
444   if (op == op_Load) {
445     /* a load, check if we can resolve it */
446     adr = get_Load_ptr(node);
447
448     if (! is_Sel(adr))
449       return;
450
451     if (! pset_find_ptr(env->sels, adr))
452       return;
453
454     /* ok, we have a Load that will be replaced */
455     vnum = GET_VNUM(adr);
456
457     assert(vnum < (unsigned)env->nvals);
458
459     block     = get_nodes_block(node);
460     value_arr = get_irn_link(block);
461
462     /* check, if we can replace this Load */
463     if (value_arr[vnum]) {
464       mem = get_Load_mem(node);
465
466       turn_into_tuple(node, pn_Load_max);
467       set_Tuple_pred(node, pn_Load_M,        mem);
468       set_Tuple_pred(node, pn_Load_res,      value_arr[vnum]);
469       set_Tuple_pred(node, pn_Load_X_except, new_Bad());
470     }
471     else {
472       l = obstack_alloc(&env->obst, sizeof(*l));
473       l->node = node;
474       l->vnum = vnum;
475
476       set_irn_link(node, env->fix_loads);
477       env->fix_loads = l;
478     }
479   }
480   else if (op == op_Store) {
481     /* a Store always can be replaced */
482     adr = get_Store_ptr(node);
483
484     if (! is_Sel(adr))
485       return;
486
487     if (! pset_find_ptr(env->sels, adr))
488       return;
489
490     vnum = GET_VNUM(adr);
491
492     assert(vnum < (unsigned)env->nvals);
493
494     block     = get_nodes_block(node);
495     value_arr = get_irn_link(block);
496
497     value_arr[vnum] = get_Store_value(node);
498
499     mem = get_Store_mem(node);
500
501     turn_into_tuple(node, pn_Store_max);
502     set_Tuple_pred(node, pn_Store_M,        mem);
503     set_Tuple_pred(node, pn_Store_X_except, new_Bad());
504   }
505   else if (op == op_Phi && get_irn_mode(node) == mode_M) {
506     /*
507      * found a memory Phi: Here, we must create new Phi nodes
508      */
509     block     = get_nodes_block(node);
510     value_arr = get_irn_link(block);
511
512     n = get_Block_n_cfgpreds(block);
513
514     in = alloca(sizeof(*in) * n);
515
516     for (i = env->nvals - 1; i >= 0; --i) {
517       unk = new_Unknown(env->modes[i]);
518       for (j = n - 1; j >= 0; --j)
519         in[j] = unk;
520
521       value_arr[i] = new_r_Phi(current_ir_graph, block, n, in, env->modes[i]);
522
523       l = obstack_alloc(&env->obst, sizeof(*l));
524       l->node = value_arr[i];
525       l->vnum = i;
526
527       set_irn_link(value_arr[i], env->fix_phis);
528       env->fix_phis = l;
529     }
530   }
531 }
532
533 /**
534  * Walker: allocate the value array for every block.
535  */
536 static void alloc_value_arr(ir_node *block, void *ctx)
537 {
538   env_t *env = ctx;
539   ir_node **var_arr = obstack_alloc(&env->obst, sizeof(*var_arr) * env->nvals);
540
541   /* the value array is empty at start */
542   memset(var_arr, 0, sizeof(*var_arr) * env->nvals);
543   set_irn_link(block, var_arr);
544 }
545
546 /**
547  * searches through blocks beginning from block for value
548  * vnum and return it.
549  */
550 static ir_node *find_value(ir_node *block, unsigned vnum)
551 {
552   ir_node **value_arr;
553   int i;
554   ir_node *res;
555
556   if (Block_not_block_visited(block)) {
557     mark_Block_block_visited(block);
558
559     value_arr = get_irn_link(block);
560
561     if (value_arr[vnum])
562       return value_arr[vnum];
563
564     for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
565       ir_node *pred = get_Block_cfgpred(block, i);
566
567       res = find_value(get_nodes_block(pred), vnum);
568       if (res)
569         return res;
570     }
571   }
572   return NULL;
573 }
574
575 /**
576  * fix the Phi list
577  */
578 static void fix_phis(env_t *env)
579 {
580   list_entry_t *l;
581   ir_node      *phi, *block, *pred, *val;
582   int          i;
583
584   for (l = env->fix_phis; l; l = get_irn_link(phi)) {
585     phi = l->node;
586
587     block = get_nodes_block(phi);
588     for (i = get_irn_arity(phi) - 1; i >= 0; --i) {
589       pred = get_Block_cfgpred(block, i);
590       pred = get_nodes_block(pred);
591
592       inc_irg_block_visited(current_ir_graph);
593       val = find_value(pred, l->vnum);
594
595       if (val)
596         set_irn_n(phi, i, val);
597     }
598   }
599 }
600
601 /**
602  * fix the Load list
603  */
604 static void fix_loads(env_t *env)
605 {
606   list_entry_t *l;
607   ir_node      *load, *block, *pred, *val, *mem;
608   int          i;
609
610   for (l = env->fix_loads; l; l = get_irn_link(load)) {
611     load = l->node;
612
613     block = get_nodes_block(load);
614     for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
615       pred = get_Block_cfgpred(block, i);
616       pred = get_nodes_block(pred);
617
618       inc_irg_block_visited(current_ir_graph);
619       val = find_value(pred, l->vnum);
620
621       if (val)
622         break;
623     }
624
625     if (! val) {
626       /* access of an uninitialized value */
627       val = new_Unknown(env->modes[l->vnum]);
628     }
629
630     mem = get_Load_mem(load);
631
632     turn_into_tuple(load, pn_Load_max);
633     set_Tuple_pred(load, pn_Load_M,        mem);
634     set_Tuple_pred(load, pn_Load_res,      val);
635     set_Tuple_pred(load, pn_Load_X_except, new_Bad());
636   }
637 }
638
639 /**
640  *  Make scalar replacement.
641  *
642  * @param sels    A set containing all Sel nodes that have a value number
643  * @param nvals   The number of scalars.
644  * @param modes   A flexible array, containing all the modes of
645  *                the value numbers.
646  */
647 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes)
648 {
649   env_t env;
650
651   obstack_init(&env.obst);
652   env.nvals     = nvals;
653   env.modes     = modes;
654   env.fix_phis  = NULL;
655   env.fix_loads = NULL;
656   env.sels      = sels;
657
658   /* first step: allocate the value arrays for every block */
659   irg_block_walk_graph(current_ir_graph, NULL, alloc_value_arr, &env);
660
661   /*
662    * second step: walk over the graph blockwise in topological order
663    * and fill the array as much as possible.
664    */
665   irg_walk_blkwise_graph(current_ir_graph, NULL, handle_first, &env);
666
667   /* third, fix the list of Phis, then the list of Loads */
668   fix_phis(&env);
669   fix_loads(&env);
670
671   obstack_free(&env.obst, NULL);
672 }
673
674 /*
675  * Find possible scalar replacements
676  *
677  * @param irg  The current ir graph.
678  */
679 void scalar_replacement_opt(ir_graph *irg)
680 {
681   unsigned  nvals;
682   int       i;
683   scalars_t key, *value;
684   ir_node   *irg_frame;
685   ir_mode   **modes;
686   set       *set_ent;
687   pset      *sels;
688   ir_type   *ent_type;
689   ir_graph  *rem;
690
691   if (! get_opt_scalar_replacement())
692     return;
693
694   rem = current_ir_graph;
695
696   /* Call algorithm that computes the out edges */
697   if (get_irg_outs_state(irg) != outs_consistent)
698     compute_irg_outs(irg);
699
700   /* Find possible scalar replacements */
701   if (find_possible_replacements(irg)) {
702
703     if (get_opt_scalar_replacement_verbose()) {
704       printf("Scalar Replacement: %s\n", get_entity_name(get_irg_entity(irg)));
705     }
706
707     /* Insert in set the scalar replacements. */
708     irg_frame = get_irg_frame(irg);
709     nvals = 0;
710     modes = NEW_ARR_F(ir_mode *, 16);
711     set_ent = new_set(ent_cmp, 8);
712     sels    = pset_new_ptr(8);
713
714     for (i = 0 ; i < get_irn_n_outs(irg_frame); i++) {
715       ir_node *succ = get_irn_out(irg_frame, i);
716
717       if (is_Sel(succ)) {
718         entity *ent = get_Sel_entity(succ);
719
720         if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
721           continue;
722
723         ent_type = get_entity_type(ent);
724
725         key.ent       = ent;
726         key.ent_owner = get_entity_owner(ent);
727         set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
728
729         if (get_opt_scalar_replacement_verbose()) {
730           if (is_Array_type(ent_type)) {
731             printf("  found array %s\n", get_entity_name(ent));
732           }
733           else if (is_Struct_type(ent_type)) {
734             printf("  found struct %s\n", get_entity_name(ent));
735           }
736           else if (is_atomic_type(ent_type))
737             printf("  found atomic value %s\n", get_entity_name(ent));
738           else {
739             assert(0 && "Neither an array nor a struct or atomic value");
740           }
741         }
742
743         nvals = allocate_value_numbers(sels, ent, nvals, &modes);
744       }
745     }
746
747     if (get_opt_scalar_replacement_verbose()) {
748       printf("  %u values will be needed\n", nvals);
749     }
750
751     /* If scalars were found. */
752     if (nvals) {
753       do_scalar_replacements(sels, nvals, modes);
754
755       for (value = set_first(set_ent); value; value = set_next(set_ent)) {
756         remove_class_member(value->ent_owner, value->ent);
757       }
758     }
759
760     del_pset(sels);
761     del_set(set_ent);
762     DEL_ARR_F(modes);
763
764     if (nvals) {
765       /*
766        * We changed the graph, but did NOT introduce new blocks
767        * neither changed control flow, cf-backedges should be still
768        * consistent.
769        */
770       set_irg_outs_inconsistent(irg);
771       set_irg_loopinfo_inconsistent(irg);
772     }
773   }
774
775   current_ir_graph = rem;
776 }