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