renamed get_opt_redundant_LoadStore() into get_opt_redundant_loadstore()
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/ldstopt.c
4  * Purpose:     load store optimizations
5  * Author:
6  * Created:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 1998-2004 Universit\81ät Karlsruhe
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11 #ifdef HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_MALLOC_H
19 #include <malloc.h>
20 #endif
21 #ifdef HAVE_STRING_H
22 # include <string.h>
23 #endif
24
25 # include "irnode_t.h"
26 # include "irgraph_t.h"
27 # include "irmode_t.h"
28 # include "iropt_t.h"
29 # include "ircons_t.h"
30 # include "irgmod.h"
31 # include "irgwalk.h"
32 # include "irvrfy.h"
33 # include "tv_t.h"
34 # include "dbginfo_t.h"
35 # include "iropt_dbg.h"
36 # include "irflag_t.h"
37 # include "array.h"
38 # include "irhooks.h"
39 # include "irtools.h"
40 # include "opt_polymorphy.h"
41
42 #ifdef DO_CACHEOPT
43 #include "cacheopt/cachesim.h"
44 #endif
45
46 #undef IMAX
47 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
48
49 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
50
51 enum changes_t {
52   DF_CHANGED = 1,       /**< data flow changed */
53   CF_CHANGED = 2,       /**< control flow changed */
54 };
55
56 /**
57  * walker environment
58  */
59 typedef struct _walk_env_t {
60   struct obstack obst;          /**< list of all stores */
61   unsigned changes;             /**< a bitmask of graph changes */
62 } walk_env_t;
63
64 /**
65  * flags for Load/Store
66  */
67 enum ldst_flags_t {
68   LDST_VISITED = 1              /**< if set, this Load/Store is already visited */
69 };
70
71 /**
72  * a Load/Store info
73  */
74 typedef struct _ldst_info_t {
75   ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
76   ir_node  *exc_block;          /**< the exception block if available */
77   int      exc_idx;             /**< predecessor index in the exception block */
78   unsigned flags;               /**< flags */
79   unsigned visited;             /**< visited counter for breaking loops */
80 } ldst_info_t;
81
82 /**
83  * flags for control flow
84  */
85 enum block_flags_t {
86   BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
87   BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
88 };
89
90 /**
91  * a Block info
92  */
93 typedef struct _block_info_t {
94   unsigned flags;               /**< flags for the block */
95 } block_info_t;
96
97 /** the master visited flag for loop detection. */
98 static unsigned master_visited = 0;
99
100 #define INC_MASTER()       ++master_visited
101 #define MARK_NODE(info)    (info)->visited = master_visited
102 #define NODE_VISITED(info) (info)->visited >= master_visited
103
104 /**
105  * get the Load/Store info of a node
106  */
107 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env)
108 {
109   ldst_info_t *info = get_irn_link(node);
110
111   if (! info) {
112     info = obstack_alloc(&env->obst, sizeof(*info));
113
114     memset(info, 0, sizeof(*info));
115
116     set_irn_link(node, info);
117   }
118   return info;
119 }
120
121 /**
122  * get the Block info of a node
123  */
124 static block_info_t *get_block_info(ir_node *node, walk_env_t *env)
125 {
126   block_info_t *info = get_irn_link(node);
127
128   if (! info) {
129     info = obstack_alloc(&env->obst, sizeof(*info));
130
131     memset(info, 0, sizeof(*info));
132
133     set_irn_link(node, info);
134   }
135   return info;
136 }
137
138 /**
139  * update the projection info for a Load/Store
140  */
141 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
142 {
143   long nr = get_Proj_proj(proj);
144
145   assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
146
147   if (info->projs[nr]) {
148     /* there is already one, do CSE */
149     exchange(proj, info->projs[nr]);
150     return DF_CHANGED;
151   }
152   else {
153     info->projs[nr] = proj;
154     return 0;
155   }
156 }
157
158 /**
159  * update the exception block info for a Load/Store node.
160  *
161  * @param info   the load/store info struct
162  * @param block  the exception handler block for this load/store
163  * @param pos    the control flow input of the block
164  */
165 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
166 {
167   assert(info->exc_block == NULL && "more than one exception block found");
168
169   info->exc_block = block;
170   info->exc_idx   = pos;
171   return 0;
172 }
173
174 #define get_irn_out_n(node)     (unsigned)PTR_TO_INT(get_irn_link(node))
175 #define set_irn_out_n(node, n)  set_irn_link(adr, INT_TO_PTR(n))
176
177 /**
178  * walker, collects all Load/Store/Proj nodes
179  *
180  * walks from Start -> End
181  */
182 static void collect_nodes(ir_node *node, void *env)
183 {
184   ir_op       *op = get_irn_op(node);
185   ir_node     *pred, *blk, *pred_blk;
186   ldst_info_t *ldst_info;
187   walk_env_t  *wenv = env;
188
189   if (op == op_Proj) {
190     ir_node *adr;
191     ir_op *op;
192
193     pred = get_Proj_pred(node);
194     op   = get_irn_op(pred);
195
196     if (op == op_Load) {
197       ldst_info = get_ldst_info(pred, wenv);
198
199       wenv->changes |= update_projs(ldst_info, node);
200
201       if ((ldst_info->flags & LDST_VISITED) == 0) {
202         adr = get_Load_ptr(pred);
203         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
204
205         ldst_info->flags |= LDST_VISITED;
206       }
207
208       /*
209        * Place the Proj's to the same block as the
210        * predecessor Load. This is always ok and prevents
211        * "non-SSA" form after optimizations if the Proj
212        * is in a wrong block.
213        */
214       blk      = get_nodes_block(node);
215       pred_blk = get_nodes_block(pred);
216       if (blk != pred_blk) {
217         wenv->changes |= DF_CHANGED;
218         set_nodes_block(node, pred_blk);
219       }
220     }
221     else if (op == op_Store) {
222       ldst_info = get_ldst_info(pred, wenv);
223
224       wenv->changes |= update_projs(ldst_info, node);
225
226       if ((ldst_info->flags & LDST_VISITED) == 0) {
227         adr = get_Store_ptr(pred);
228         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
229
230         ldst_info->flags |= LDST_VISITED;
231       }
232
233       /*
234        * Place the Proj's to the same block as the
235        * predecessor Store. This is always ok and prevents
236        * "non-SSA" form after optimizations if the Proj
237        * is in a wrong block.
238        */
239       blk      = get_nodes_block(node);
240       pred_blk = get_nodes_block(pred);
241       if (blk != pred_blk) {
242         wenv->changes |= DF_CHANGED;
243         set_nodes_block(node, pred_blk);
244       }
245     }
246   }
247   else if (op == op_Block) { /* check, if it's an exception block */
248     int i;
249
250     for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
251       ir_node      *pred_block;
252       block_info_t *bl_info;
253
254       pred = skip_Proj(get_Block_cfgpred(node, i));
255
256       /* ignore Bad predecessors, they will be removed later */
257       if (is_Bad(pred))
258         continue;
259
260       pred_block = get_nodes_block(pred);
261       bl_info    = get_block_info(pred_block, wenv);
262
263       if (is_fragile_op(pred))
264               bl_info->flags |= BLOCK_HAS_EXC;
265       else if (is_irn_forking(pred))
266         bl_info->flags |= BLOCK_HAS_COND;
267
268       if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
269         ldst_info = get_ldst_info(pred, wenv);
270
271         wenv->changes |= update_exc(ldst_info, node, i);
272       }
273     }
274   }
275 }
276
277 /**
278  * Returns an entity if the address ptr points to a constant one.
279  */
280 static entity *find_constant_entity(ir_node *ptr)
281 {
282   for (;;) {
283     ir_op *op = get_irn_op(ptr);
284
285     if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
286       return get_SymConst_entity(ptr);
287     }
288     else if (op == op_Sel) {
289       entity *ent = get_Sel_entity(ptr);
290       type *tp    = get_entity_owner(ent);
291
292       /* Do not fiddle about polymorphy. */
293       if (is_Class_type(get_entity_owner(ent)) &&
294           ((get_entity_n_overwrites(ent)    != 0) ||
295            (get_entity_n_overwrittenby(ent) != 0)   ) )
296         return NULL;
297
298       if (variability_constant == get_entity_variability(ent))
299         return ent;
300
301       if (is_Array_type(tp)) {
302         /* check bounds */
303         int i, n;
304
305         for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
306           ir_node *bound;
307           tarval *tlower, *tupper;
308           ir_node *index = get_Sel_index(ptr, i);
309           tarval *tv     = computed_value(index);
310
311           /* check if the index is constant */
312           if (tv == tarval_bad)
313             return NULL;
314
315           bound  = get_array_lower_bound(tp, i);
316           tlower = computed_value(bound);
317           bound  = get_array_upper_bound(tp, i);
318           tupper = computed_value(bound);
319
320           if (tlower == tarval_bad || tupper == tarval_bad)
321             return NULL;
322
323           if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
324             return NULL;
325           if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
326             return NULL;
327
328           /* ok, bounds check finished */
329         }
330       }
331
332       /* try next */
333       ptr = get_Sel_ptr(ptr);
334     }
335     else
336       return NULL;
337   }
338 }
339
340 /**
341  * Return the Selection index of a Sel node from dimension n
342  */
343 static long get_Sel_array_index_long(ir_node *n, int dim) {
344   ir_node *index = get_Sel_index(n, dim);
345   assert(get_irn_op(index) == op_Const);
346   return get_tarval_long(get_Const_tarval(index));
347 }
348
349 /**
350  * Returns the accessed component graph path for an
351  * node computing an address.
352  *
353  * @param ptr    the node computing the address
354  * @param depth  current depth in steps upward from the root
355  *               of the address
356  */
357 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
358   compound_graph_path *res = NULL;
359   entity              *root, *field;
360   int                 path_len, pos;
361
362   if (get_irn_op(ptr) == op_SymConst) {
363     /* a SymConst. If the depth is 0, this is an access to a global
364      * entity and we don't need a component path, else we know
365      * at least it's length.
366      */
367     assert(get_SymConst_kind(ptr) == symconst_addr_ent);
368     root = get_SymConst_entity(ptr);
369     res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
370   }
371   else {
372     assert(get_irn_op(ptr) == op_Sel);
373     /* it's a Sel, go up until we find the root */
374     res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
375
376     /* fill up the step in the path at the current position */
377     field    = get_Sel_entity(ptr);
378     path_len = get_compound_graph_path_length(res);
379     pos      = path_len - depth - 1;
380     set_compound_graph_path_node(res, pos, field);
381
382     if (is_Array_type(get_entity_owner(field))) {
383       assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
384       set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
385     }
386   }
387   return res;
388 }
389
390 /** Returns an access path or NULL.  The access path is only
391  *  valid, if the graph is in phase_high and _no_ address computation is used.
392  */
393 static compound_graph_path *get_accessed_path(ir_node *ptr) {
394   return rec_get_accessed_path(ptr, 0);
395 }
396
397 /**
398  * optimize a Load
399  */
400 static unsigned optimize_load(ir_node *load)
401 {
402   ldst_info_t *info = get_irn_link(load);
403   ir_mode *load_mode = get_Load_mode(load);
404   ir_node *pred, *mem, *ptr, *new_node;
405   entity *ent;
406   unsigned res = 0;
407
408   /* do NOT touch volatile loads for now */
409   if (get_Load_volatility(load) == volatility_is_volatile)
410     return 0;
411
412   /* the address of the load to be optimized */
413   ptr = get_Load_ptr(load);
414
415   /*
416    * Check if we can remove the exception from a Load:
417    * This can be done, if the address is from an Sel(Alloc) and
418    * the Sel type is a subtype of the allocated type.
419    *
420    * This optimizes some often used OO constructs,
421    * like x = new O; x->t;
422    */
423   if (info->projs[pn_Load_X_except]) {
424     if (get_irn_op(ptr) == op_Sel) {
425       ir_node *mem = get_Sel_mem(ptr);
426
427       if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
428         /* ok, check the types */
429         entity *ent  = get_Sel_entity(ptr);
430         type *s_type = get_entity_type(ent);
431         type *a_type = get_Alloc_type(mem);
432
433         if (is_subclass_of(s_type, a_type)) {
434           /* ok, condition met: there can't be an exception because
435            * Alloc guarantees that enough memory was allocated */
436
437           exchange(info->projs[pn_Load_X_except], new_Bad());
438           info->projs[pn_Load_X_except] = NULL;
439           res |= CF_CHANGED;
440         }
441       }
442     }
443     else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
444              ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
445       /* simple case: a direct load after an Alloc. Firm Alloc throw
446        * an exception in case of out-of-memory. So, there is no way for an
447        * exception in this load.
448        * This code is constructed by the "exception lowering" in the Jack compiler.
449        */
450        exchange(info->projs[pn_Load_X_except], new_Bad());
451        info->projs[pn_Load_X_except] = NULL;
452        res |= CF_CHANGED;
453     }
454   }
455
456   /* the mem of the Load. Must still be returned after optimization */
457   mem  = get_Load_mem(load);
458
459   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
460     /* a Load which value is neither used nor exception checked, remove it */
461     exchange(info->projs[pn_Load_M], mem);
462
463     return res | DF_CHANGED;
464   }
465
466   /* Load from a constant polymorphic field, where we can resolve
467      polymorphy. */
468   new_node = transform_node_Load(load);
469   if (new_node != load) {
470     if (info->projs[pn_Load_M]) {
471       exchange(info->projs[pn_Load_M], mem);
472       info->projs[pn_Load_M] = NULL;
473     }
474     if (info->projs[pn_Load_X_except]) {
475       exchange(info->projs[pn_Load_X_except], new_Bad());
476       info->projs[pn_Load_X_except] = NULL;
477     }
478     if (info->projs[pn_Load_res])
479       exchange(info->projs[pn_Load_res], new_node);
480     return res | DF_CHANGED;
481   }
482
483   /* check if we can determine the entity that will be loaded */
484   ent = find_constant_entity(ptr);
485   if (ent) {
486     if ((allocation_static == get_entity_allocation(ent)) &&
487         (visibility_external_allocated != get_entity_visibility(ent))) {
488       /* a static allocation that is not external: there should be NO exception
489        * when loading. */
490
491       /* no exception, clear the info field as it might be checked later again */
492       if (info->projs[pn_Load_X_except]) {
493         exchange(info->projs[pn_Load_X_except], new_Bad());
494         info->projs[pn_Load_X_except] = NULL;
495         res |= CF_CHANGED;
496       }
497
498       if (variability_constant == get_entity_variability(ent)
499                 && is_atomic_entity(ent)) {
500         /* Might not be atomic after
501            lowering of Sels.  In this
502            case we could also load, but
503            it's more complicated. */
504         /* more simpler case: we load the content of a constant value:
505          * replace it by the constant itself
506          */
507
508         /* no memory */
509         if (info->projs[pn_Load_M]) {
510           exchange(info->projs[pn_Load_M], mem);
511           res |= DF_CHANGED;
512         }
513
514         /* no result :-) */
515         if (info->projs[pn_Load_res]) {
516           if (is_atomic_entity(ent)) {
517             ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
518
519             DBG_OPT_RC(load, c);
520             exchange(info->projs[pn_Load_res], c);
521             return DF_CHANGED | res;
522           }
523         }
524       }
525       else if (variability_constant == get_entity_variability(ent)) {
526         compound_graph_path *path = get_accessed_path(ptr);
527
528         if (path) {
529           ir_node *c;
530
531           assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
532           /*
533           {
534             int j;
535             for (j = 0; j < get_compound_graph_path_length(path); ++j) {
536               entity *node = get_compound_graph_path_node(path, j);
537               fprintf(stdout, ".%s", get_entity_name(node));
538               if (is_Array_type(get_entity_owner(node)))
539                       fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
540             }
541             printf("\n");
542           }
543           */
544
545           c = get_compound_ent_value_by_path(ent, path);
546           free_compound_graph_path(path);
547
548           /* printf("  cons: "); DDMN(c); */
549
550           if (info->projs[pn_Load_M]) {
551             exchange(info->projs[pn_Load_M], mem);
552             res |= DF_CHANGED;
553           }
554           if (info->projs[pn_Load_res]) {
555             exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
556             return res | DF_CHANGED;
557           }
558         }
559         else {
560           /*  We can not determine a correct access path.  E.g., in jack, we load
561                     a byte from an object to generate an exception.   Happens in test program
562                     Reflectiontest.
563           printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
564            get_entity_name(get_irg_entity(current_ir_graph)));
565           printf("  load: "); DDMN(load);
566           printf("  ptr:  "); DDMN(ptr);
567           */
568         }
569       }
570     }
571   }
572
573   /* Check, if the address of this load is used more than once.
574    * If not, this load cannot be removed in any case. */
575   if (get_irn_out_n(ptr) <= 1)
576     return res;
577
578   /*
579    * follow the memory chain as long as there are only Loads
580    * and try to replace current Load or Store by a previous one.
581    * Note that in unreachable loops it might happen that we reach
582    * load again, as well as we can fall into a cycle.
583    * We break such cycles using a special visited flag.
584    */
585   INC_MASTER();
586   for (pred = skip_Proj(mem); load != pred; pred = skip_Proj(get_Load_mem(pred))) {
587     ldst_info_t *pred_info = get_irn_link(pred);
588
589     /*
590      * BEWARE: one might think that checking the modes is useless, because
591      * if the pointers are identical, they refer to the same object.
592      * This is only true in strong typed languages, not in C were the following
593      * is possible a = *(type1 *)p; b = *(type2 *)p ...
594      */
595
596     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
597         get_irn_mode(get_Store_value(pred)) == load_mode) {
598       /*
599        * a Load immediately after a Store -- a read after write.
600        * We may remove the Load, if both Load & Store does not have an exception handler
601        * OR they are in the same block. In the latter case the Load cannot
602        * throw an exception when the previous Store was quiet.
603        *
604        * Why we need to check for Store Exception? If the Store cannot
605        * be executed (ROM) the exception handler might simply jump into
606        * the load block :-(
607        * We could make it a little bit better if we would know that the exception
608        * handler of the Store jumps directly to the end...
609        */
610       if ((!pred_info->projs[pn_Store_X_except] && !info->projs[pn_Load_X_except]) ||
611           get_nodes_block(load) == get_nodes_block(pred)) {
612         ir_node *value = get_Store_value(pred);
613
614         DBG_OPT_RAW(load, value);
615         if (info->projs[pn_Load_M])
616           exchange(info->projs[pn_Load_M], mem);
617
618         /* no exception */
619         if (info->projs[pn_Load_X_except]) {
620           exchange( info->projs[pn_Load_X_except], new_Bad());
621           res |= CF_CHANGED;
622         }
623
624         if (info->projs[pn_Load_res])
625           exchange(info->projs[pn_Load_res], value);
626
627         return res | DF_CHANGED;
628       }
629     }
630     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
631              get_Load_mode(pred) == load_mode) {
632       /*
633        * a Load after a Load -- a read after read.
634        * We may remove the second Load, if it does not have an exception handler
635        * OR they are in the same block. In the later case the Load cannot
636        * throw an exception when the previous Load was quiet.
637        *
638        * Here, there is no need to check if the previous Load has an exception
639        * hander because they would have exact the same exception...
640        */
641       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
642         DBG_OPT_RAR(load, pred);
643
644         if (pred_info->projs[pn_Load_res]) {
645           /* we need a data proj from the previous load for this optimization */
646           if (info->projs[pn_Load_res])
647             exchange(info->projs[pn_Load_res], pred_info->projs[pn_Load_res]);
648
649           if (info->projs[pn_Load_M])
650             exchange(info->projs[pn_Load_M], mem);
651         }
652         else {
653           if (info->projs[pn_Load_res]) {
654             set_Proj_pred(info->projs[pn_Load_res], pred);
655             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
656             pred_info->projs[pn_Load_res] = info->projs[pn_Load_res];
657           }
658           if (info->projs[pn_Load_M]) {
659             /* Actually, this if should not be necessary.  Construct the Loads
660                properly!!! */
661             exchange(info->projs[pn_Load_M], mem);
662           }
663         }
664
665         /* no exception */
666         if (info->projs[pn_Load_X_except]) {
667           exchange(info->projs[pn_Load_X_except], new_Bad());
668           res |= CF_CHANGED;
669         }
670
671         return res |= DF_CHANGED;
672       }
673     }
674
675     /* follow only Load chains */
676     if (get_irn_op(pred) != op_Load)
677       break;
678
679     /* check for cycles */
680     if (NODE_VISITED(pred_info))
681       break;
682     MARK_NODE(pred_info);
683   }
684   return res;
685 }
686
687 /**
688  * optimize a Store
689  */
690 static unsigned optimize_store(ir_node *store)
691 {
692   ldst_info_t *info = get_irn_link(store);
693   ir_node *pred, *mem, *ptr, *value, *block;
694   ir_mode *mode;
695   unsigned res = 0;
696
697   if (get_Store_volatility(store) == volatility_is_volatile)
698     return 0;
699
700   /*
701    * BEWARE: one might think that checking the modes is useless, because
702    * if the pointers are identical, they refer to the same object.
703    * This is only true in strong typed languages, not is C were the following
704    * is possible *(type1 *)p = a; *(type2 *)p = b ...
705    */
706
707   ptr   = get_Store_ptr(store);
708
709   /* Check, if the address of this load is used more than once.
710    * If not, this load cannot be removed in any case. */
711   if (get_irn_out_n(ptr) <= 1)
712     return 0;
713
714   block = get_nodes_block(store);
715   mem   = get_Store_mem(store);
716   value = get_Store_value(store);
717   mode  = get_irn_mode(value);
718
719   /* follow the memory chain as long as there are only Loads */
720   INC_MASTER();
721   for (pred = skip_Proj(mem); pred != store; pred = skip_Proj(get_Load_mem(pred))) {
722     ldst_info_t *pred_info = get_irn_link(pred);
723
724     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
725         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
726       /*
727        * a Store after a Store in the same block -- a write after write.
728        * We may remove the first Store, if it does not have an exception handler.
729        *
730        * TODO: What, if both have the same exception handler ???
731        */
732       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
733         DBG_OPT_WAW(pred, store);
734         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
735         return DF_CHANGED;
736       }
737     }
738     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
739              value == pred_info->projs[pn_Load_res]) {
740       /*
741        * a Store of a value after a Load -- a write after read.
742        * We may remove the second Store, if it does not have an exception handler.
743        */
744       if (! info->projs[pn_Store_X_except]) {
745         DBG_OPT_WAR(store, pred);
746         exchange( info->projs[pn_Store_M], mem );
747         return DF_CHANGED;
748       }
749     }
750
751     /* follow only Load chains */
752     if (get_irn_op(pred) != op_Load)
753       break;
754
755     /* check for cycles */
756     if (NODE_VISITED(pred_info))
757       break;
758     MARK_NODE(pred_info);
759   }
760   return res;
761 }
762
763 /**
764  * walker, optimizes Phi after Stores to identical places:
765  * Does the following optimization:
766  * @verbatim
767  *
768  *   val1   val2   val3          val1  val2  val3
769  *    |      |      |               \    |    /
770  *   Str    Str    Str               \   |   /
771  *      \    |    /                   PhiData
772  *       \   |   /                       |
773  *        \  |  /                       Str
774  *          PhiM
775  *
776  * @endverbatim
777  * This reduces the number of stores and allows for predicated execution.
778  * Moves Stores back to the end of a function which may be bad.
779  *
780  * This is only possible if the predecessor blocks have only one successor.
781  */
782 static unsigned optimize_phi(ir_node *phi, void *env)
783 {
784   walk_env_t *wenv = env;
785   int i, n;
786   ir_node *store, *old_store, *ptr, *block, *phiM, *phiD, *exc, *projM;
787   ir_mode *mode;
788   ir_node **inM, **inD;
789   int *idx;
790   dbg_info *db = NULL;
791   ldst_info_t *info;
792   block_info_t *bl_info;
793   unsigned res = 0;
794
795   /* Must be a memory Phi */
796   if (get_irn_mode(phi) != mode_M)
797     return 0;
798
799   n = get_Phi_n_preds(phi);
800   if (n <= 0)
801     return 0;
802
803   store = skip_Proj(get_Phi_pred(phi, 0));
804   old_store = store;
805   if (get_irn_op(store) != op_Store)
806     return 0;
807
808   /* abort on dead blocks */
809   if (is_Block_dead(get_nodes_block(store)))
810     return 0;
811
812   /* check if the block has only one successor */
813   bl_info = get_irn_link(get_nodes_block(store));
814   if (bl_info->flags)
815     return 0;
816
817   /* this is the address of the store */
818   ptr  = get_Store_ptr(store);
819   mode = get_irn_mode(get_Store_value(store));
820   info = get_irn_link(store);
821   exc  = info->exc_block;
822
823   for (i = 1; i < n; ++i) {
824     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
825
826     if (get_irn_op(pred) != op_Store)
827       return 0;
828
829     if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
830       return 0;
831
832     info = get_irn_link(pred);
833
834     /* check, if all stores have the same exception flow */
835     if (exc != info->exc_block)
836       return 0;
837
838     /* abort on dead blocks */
839     if (is_Block_dead(get_nodes_block(store)))
840       return 0;
841
842     /* check if the block has only one successor */
843     bl_info = get_irn_link(get_nodes_block(store));
844     if (bl_info->flags)
845       return 0;
846   }
847
848   /*
849    * ok, when we are here, we found all predecessors of a Phi that
850    * are Stores to the same address and size. That means whatever
851    * we do before we enter the block of the Phi, we do a Store.
852    * So, we can move the Store to the current block:
853    *
854    *   val1    val2    val3          val1  val2  val3
855    *    |       |       |               \    |    /
856    * | Str | | Str | | Str |             \   |   /
857    *      \     |     /                   PhiData
858    *       \    |    /                       |
859    *        \   |   /                       Str
860    *           PhiM
861    *
862    * Is only allowed if the predecessor blocks have only one successor.
863    */
864
865   /* first step: collect all inputs */
866   NEW_ARR_A(ir_node *, inM, n);
867   NEW_ARR_A(ir_node *, inD, n);
868   NEW_ARR_A(int, idx, n);
869
870   for (i = 0; i < n; ++i) {
871     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
872     info = get_irn_link(pred);
873
874     inM[i] = get_Store_mem(pred);
875     inD[i] = get_Store_value(pred);
876     idx[i] = info->exc_idx;
877   }
878   block = get_nodes_block(phi);
879
880   /* second step: create a new memory Phi */
881   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
882
883   /* third step: create a new data Phi */
884   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
885
886   /* fourth step: create the Store */
887   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
888 #ifdef DO_CACHEOPT
889   co_set_irn_name(store, co_get_irn_ident(old_store));
890 #endif
891
892   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
893
894   info = get_ldst_info(store, wenv);
895   info->projs[pn_Store_M] = projM;
896
897   /* fifths step: repair exception flow */
898   if (exc) {
899     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
900
901     info->projs[pn_Store_X_except] = projX;
902     info->exc_block                = exc;
903     info->exc_idx                  = idx[0];
904
905     for (i = 0; i < n; ++i) {
906       set_Block_cfgpred(exc, idx[i], projX);
907     }
908
909     if (n > 1) {
910       /* the exception block should be optimized as some inputs are identical now */
911     }
912
913     res |= CF_CHANGED;
914   }
915
916   /* sixth step: replace old Phi */
917   exchange(phi, projM);
918
919   return res | DF_CHANGED;
920 }
921
922 /**
923  * walker, do the optiimizations
924  */
925 static void do_load_store_optimize(ir_node *n, void *env)
926 {
927   walk_env_t *wenv = env;
928
929   switch (get_irn_opcode(n)) {
930
931   case iro_Load:
932     wenv->changes |= optimize_load(n);
933     break;
934
935   case iro_Store:
936     wenv->changes |= optimize_store(n);
937     break;
938
939   case iro_Phi:
940     wenv->changes |= optimize_phi(n, env);
941
942   default:
943     ;
944   }
945 }
946
947 /*
948  * do the load store optimization
949  */
950 void optimize_load_store(ir_graph *irg)
951 {
952   walk_env_t env;
953
954   assert(get_irg_phase_state(irg) != phase_building);
955   assert(get_irg_pinned(irg) != op_pin_state_floats &&
956     "LoadStore optimization needs pinned graph");
957
958   if (! get_opt_redundant_loadstore())
959     return;
960
961   obstack_init(&env.obst);
962   env.changes = 0;
963
964   /* init the links, then collect Loads/Stores/Proj's in lists */
965   master_visited = 0;
966   irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
967
968   /* now we have collected enough information, optimize */
969   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
970
971   obstack_free(&env.obst, NULL);
972
973   /* Handle graph state */
974   if (env.changes) {
975     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
976       set_irg_outs_inconsistent(current_ir_graph);
977   }
978
979   if (env.changes & CF_CHANGED) {
980     /* is this really needed: Yes, control flow changed, block might get Bad. */
981     if (get_irg_dom_state(current_ir_graph) == dom_consistent)
982       set_irg_dom_inconsistent(current_ir_graph);
983   }
984 }