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