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