010df3a7c0d0e6e7ef7a5b587be9965478df2442
[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) { /* check, if it's an exception 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_mode *load_mode = get_Load_mode(load);
578   ir_node *mem, *ptr, *new_node;
579   entity *ent;
580   unsigned res = 0;
581
582   /* do NOT touch volatile loads for now */
583   if (get_Load_volatility(load) == volatility_is_volatile)
584     return 0;
585
586   /* the address of the load to be optimized */
587   ptr = get_Load_ptr(load);
588
589   /*
590    * Check if we can remove the exception from a Load:
591    * This can be done, if the address is from an Sel(Alloc) and
592    * the Sel type is a subtype of the allocated type.
593    *
594    * This optimizes some often used OO constructs,
595    * like x = new O; x->t;
596    */
597   if (info->projs[pn_Load_X_except]) {
598     if (is_Sel(ptr)) {
599       ir_node *mem = get_Sel_mem(ptr);
600
601       if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
602         /* ok, check the types */
603         entity  *ent    = get_Sel_entity(ptr);
604         ir_type *s_type = get_entity_type(ent);
605         ir_type *a_type = get_Alloc_type(mem);
606
607         if (is_SubClass_of(s_type, a_type)) {
608           /* ok, condition met: there can't be an exception because
609            * Alloc guarantees that enough memory was allocated */
610
611           exchange(info->projs[pn_Load_X_except], new_Bad());
612           info->projs[pn_Load_X_except] = NULL;
613           res |= CF_CHANGED;
614         }
615       }
616     }
617     else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
618              ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
619       /* simple case: a direct load after an Alloc. Firm Alloc throw
620        * an exception in case of out-of-memory. So, there is no way for an
621        * exception in this load.
622        * This code is constructed by the "exception lowering" in the Jack compiler.
623        */
624        exchange(info->projs[pn_Load_X_except], new_Bad());
625        info->projs[pn_Load_X_except] = NULL;
626        res |= CF_CHANGED;
627     }
628   }
629
630   /* the mem of the Load. Must still be returned after optimization */
631   mem  = get_Load_mem(load);
632
633   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
634     /* a Load which value is neither used nor exception checked, remove it */
635     exchange(info->projs[pn_Load_M], mem);
636
637     exchange(load, new_Bad());
638     reduce_adr_usage(ptr);
639     return res | DF_CHANGED;
640   }
641
642   /* Load from a constant polymorphic field, where we can resolve
643      polymorphism. */
644   new_node = transform_node_Load(load);
645   if (new_node != load) {
646     if (info->projs[pn_Load_M]) {
647       exchange(info->projs[pn_Load_M], mem);
648       info->projs[pn_Load_M] = NULL;
649     }
650     if (info->projs[pn_Load_X_except]) {
651       exchange(info->projs[pn_Load_X_except], new_Bad());
652       info->projs[pn_Load_X_except] = NULL;
653     }
654     if (info->projs[pn_Load_res])
655       exchange(info->projs[pn_Load_res], new_node);
656
657     exchange(load, new_Bad());
658     reduce_adr_usage(ptr);
659     return res | DF_CHANGED;
660   }
661
662   /* check if we can determine the entity that will be loaded */
663   ent = find_constant_entity(ptr);
664   if (ent) {
665     if ((allocation_static == get_entity_allocation(ent)) &&
666         (visibility_external_allocated != get_entity_visibility(ent))) {
667       /* a static allocation that is not external: there should be NO exception
668        * when loading. */
669
670       /* no exception, clear the info field as it might be checked later again */
671       if (info->projs[pn_Load_X_except]) {
672         exchange(info->projs[pn_Load_X_except], new_Bad());
673         info->projs[pn_Load_X_except] = NULL;
674         res |= CF_CHANGED;
675       }
676
677       if (variability_constant == get_entity_variability(ent)
678                 && is_atomic_entity(ent)) {
679         /* Might not be atomic after
680            lowering of Sels.  In this
681            case we could also load, but
682            it's more complicated. */
683         /* more simpler case: we load the content of a constant value:
684          * replace it by the constant itself
685          */
686
687         /* no memory */
688         if (info->projs[pn_Load_M]) {
689           exchange(info->projs[pn_Load_M], mem);
690           res |= DF_CHANGED;
691         }
692         /* no result :-) */
693         if (info->projs[pn_Load_res]) {
694           if (is_atomic_entity(ent)) {
695             ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
696
697             DBG_OPT_RC(load, c);
698             exchange(info->projs[pn_Load_res], c);
699             res |= DF_CHANGED;
700           }
701         }
702         exchange(load, new_Bad());
703         reduce_adr_usage(ptr);
704         return res;
705       }
706       else if (variability_constant == get_entity_variability(ent)) {
707         compound_graph_path *path = get_accessed_path(ptr);
708
709         if (path) {
710           ir_node *c;
711
712           assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
713           /*
714           {
715             int j;
716             for (j = 0; j < get_compound_graph_path_length(path); ++j) {
717               entity *node = get_compound_graph_path_node(path, j);
718               fprintf(stdout, ".%s", get_entity_name(node));
719               if (is_Array_type(get_entity_owner(node)))
720                       fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
721             }
722             printf("\n");
723           }
724           */
725
726           c = get_compound_ent_value_by_path(ent, path);
727           free_compound_graph_path(path);
728
729           /* printf("  cons: "); DDMN(c); */
730
731           if (info->projs[pn_Load_M]) {
732             exchange(info->projs[pn_Load_M], mem);
733             res |= DF_CHANGED;
734           }
735           if (info->projs[pn_Load_res]) {
736             exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
737             res |= DF_CHANGED;
738           }
739           exchange(load, new_Bad());
740           reduce_adr_usage(ptr);
741           return res;
742         }
743         else {
744           /*  We can not determine a correct access path.  E.g., in jack, we load
745                     a byte from an object to generate an exception.   Happens in test program
746                     Reflectiontest.
747           printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
748            get_entity_name(get_irg_entity(current_ir_graph)));
749           printf("  load: "); DDMN(load);
750           printf("  ptr:  "); DDMN(ptr);
751           */
752         }
753       }
754     }
755   }
756
757   /* Check, if the address of this load is used more than once.
758    * If not, this load cannot be removed in any case. */
759   if (get_irn_n_uses(ptr) <= 1)
760     return res;
761
762   /*
763    * follow the memory chain as long as there are only Loads
764    * and try to replace current Load or Store by a previous one.
765    * Note that in unreachable loops it might happen that we reach
766    * load again, as well as we can fall into a cycle.
767    * We break such cycles using a special visited flag.
768    */
769   INC_MASTER();
770   res = follow_Load_chain(load, skip_Proj(mem));
771   return res;
772 }
773
774 /**
775  * follow the memory chain as long as there are only Loads.
776  *
777  * INC_MASTER() must be called before dive into
778  */
779 static unsigned follow_Load_chain_for_Store(ir_node *store, ir_node *curr) {
780   unsigned res = 0;
781   ldst_info_t *info = get_irn_link(store);
782   ir_node *pred;
783   ir_node *ptr = get_Store_ptr(store);
784   ir_node *mem = get_Store_mem(store);
785   ir_node *value = get_Store_value(store);
786   ir_mode *mode  = get_irn_mode(value);
787   ir_node *block = get_nodes_block(store);
788
789   for (pred = curr; pred != store; pred = skip_Proj(get_Load_mem(pred))) {
790     ldst_info_t *pred_info = get_irn_link(pred);
791
792     /*
793      * BEWARE: one might think that checking the modes is useless, because
794      * if the pointers are identical, they refer to the same object.
795      * This is only true in strong typed languages, not is C were the following
796      * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
797      */
798     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
799         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
800       /*
801        * a Store after a Store in the same block -- a write after write.
802        * We may remove the first Store, if it does not have an exception handler.
803        *
804        * TODO: What, if both have the same exception handler ???
805        */
806       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
807         DBG_OPT_WAW(pred, store);
808         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
809         exchange(pred, new_Bad());
810         reduce_adr_usage(ptr);
811         return DF_CHANGED;
812       }
813     }
814     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
815              value == pred_info->projs[pn_Load_res]) {
816       /*
817        * a Store of a value after a Load -- a write after read.
818        * We may remove the second Store, if it does not have an exception handler.
819        */
820       if (! info->projs[pn_Store_X_except]) {
821         DBG_OPT_WAR(store, pred);
822         exchange( info->projs[pn_Store_M], mem );
823         exchange(store, new_Bad());
824         reduce_adr_usage(ptr);
825         return DF_CHANGED;
826       }
827     }
828
829     /* follow only Load chains */
830     if (get_irn_op(pred) != op_Load)
831       break;
832
833     /* check for cycles */
834     if (NODE_VISITED(pred_info))
835       break;
836     MARK_NODE(pred_info);
837   }
838
839   if (get_irn_op(pred) == op_Sync) {
840     int i;
841
842     /* handle all Sync predecessors */
843     for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
844       res |= follow_Load_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
845       if (res)
846         break;
847     }
848   }
849   return res;
850 }
851
852 /**
853  * optimize a Store
854  */
855 static unsigned optimize_store(ir_node *store)
856 {
857   ldst_info_t *info = get_irn_link(store);
858   ir_node *ptr, *mem;
859
860   if (get_Store_volatility(store) == volatility_is_volatile)
861     return 0;
862
863   ptr = get_Store_ptr(store);
864
865   /* Check, if the address of this load is used more than once.
866    * If not, this load cannot be removed in any case. */
867   if (get_irn_n_uses(ptr) <= 1)
868     return 0;
869
870   mem = get_Store_mem(store);
871
872   /* follow the memory chain as long as there are only Loads */
873   INC_MASTER();
874   return follow_Load_chain_for_Store(store, skip_Proj(mem));
875 }
876
877 /**
878  * walker, optimizes Phi after Stores to identical places:
879  * Does the following optimization:
880  * @verbatim
881  *
882  *   val1   val2   val3          val1  val2  val3
883  *    |      |      |               \    |    /
884  *   Str    Str    Str               \   |   /
885  *      \    |    /                   PhiData
886  *       \   |   /                       |
887  *        \  |  /                       Str
888  *          PhiM
889  *
890  * @endverbatim
891  * This reduces the number of stores and allows for predicated execution.
892  * Moves Stores back to the end of a function which may be bad.
893  *
894  * This is only possible if the predecessor blocks have only one successor.
895  */
896 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
897 {
898   int i, n;
899   ir_node *store, *old_store, *ptr, *block, *phiM, *phiD, *exc, *projM;
900   ir_mode *mode;
901   ir_node **inM, **inD, **stores;
902   int *idx;
903   dbg_info *db = NULL;
904   ldst_info_t *info;
905   block_info_t *bl_info;
906   unsigned res = 0;
907
908   /* Must be a memory Phi */
909   if (get_irn_mode(phi) != mode_M)
910     return 0;
911
912   n = get_Phi_n_preds(phi);
913   if (n <= 0)
914     return 0;
915
916   store = skip_Proj(get_Phi_pred(phi, 0));
917   old_store = store;
918   if (get_irn_op(store) != op_Store)
919     return 0;
920
921   /* abort on dead blocks */
922   if (is_Block_dead(get_nodes_block(store)))
923     return 0;
924
925   /* check if the block has only one successor */
926   bl_info = get_irn_link(get_nodes_block(store));
927   if (bl_info->flags)
928     return 0;
929
930   /* this is the address of the store */
931   ptr  = get_Store_ptr(store);
932   mode = get_irn_mode(get_Store_value(store));
933   info = get_irn_link(store);
934   exc  = info->exc_block;
935
936   for (i = 1; i < n; ++i) {
937     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
938
939     if (get_irn_op(pred) != op_Store)
940       return 0;
941
942     if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
943       return 0;
944
945     info = get_irn_link(pred);
946
947     /* check, if all stores have the same exception flow */
948     if (exc != info->exc_block)
949       return 0;
950
951     /* abort on dead blocks */
952     if (is_Block_dead(get_nodes_block(store)))
953       return 0;
954
955     /* check if the block has only one successor */
956     bl_info = get_irn_link(get_nodes_block(store));
957     if (bl_info->flags)
958       return 0;
959   }
960
961   /*
962    * ok, when we are here, we found all predecessors of a Phi that
963    * are Stores to the same address and size. That means whatever
964    * we do before we enter the block of the Phi, we do a Store.
965    * So, we can move the Store to the current block:
966    *
967    *   val1    val2    val3          val1  val2  val3
968    *    |       |       |               \    |    /
969    * | Str | | Str | | Str |             \   |   /
970    *      \     |     /                   PhiData
971    *       \    |    /                       |
972    *        \   |   /                       Str
973    *           PhiM
974    *
975    * Is only allowed if the predecessor blocks have only one successor.
976    */
977
978   /* first step: collect all inputs */
979   NEW_ARR_A(ir_node *, stores, n);
980   NEW_ARR_A(ir_node *, inM, n);
981   NEW_ARR_A(ir_node *, inD, n);
982   NEW_ARR_A(int, idx, n);
983
984   /* prepare: skip the memory proj: we need this in the case some stores
985      are cascaded */
986   for (i = 0; i < n; ++i) {
987     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
988     info = get_irn_link(pred);
989
990     stores[i] = pred;
991
992     exchange(info->projs[pn_Store_M], get_Store_mem(pred));
993   }
994
995   for (i = 0; i < n; ++i) {
996     ir_node *pred = stores[i];
997     info = get_irn_link(pred);
998
999     inM[i] = get_Store_mem(pred);
1000     inD[i] = get_Store_value(pred);
1001     idx[i] = info->exc_idx;
1002
1003     /* Should we here replace the Proj after the Store by
1004      * the Store's memory? Would be save but should not be needed,
1005      * because we checked that all pred blocks have only one
1006      * control flow successor.
1007      */
1008   }
1009   block = get_nodes_block(phi);
1010
1011   /* second step: create a new memory Phi */
1012   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1013
1014   /* third step: create a new data Phi */
1015   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1016
1017   /* fourth step: create the Store */
1018   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1019 #ifdef DO_CACHEOPT
1020   co_set_irn_name(store, co_get_irn_ident(old_store));
1021 #endif
1022
1023   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1024
1025   info = get_ldst_info(store, wenv);
1026   info->projs[pn_Store_M] = projM;
1027
1028   /* fifths step: repair exception flow */
1029   if (exc) {
1030     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1031
1032     info->projs[pn_Store_X_except] = projX;
1033     info->exc_block                = exc;
1034     info->exc_idx                  = idx[0];
1035
1036     for (i = 0; i < n; ++i) {
1037       set_Block_cfgpred(exc, idx[i], projX);
1038     }
1039
1040     if (n > 1) {
1041       /* the exception block should be optimized as some inputs are identical now */
1042     }
1043
1044     res |= CF_CHANGED;
1045   }
1046
1047   /* sixth step: replace old Phi */
1048   exchange(phi, projM);
1049
1050   return res | DF_CHANGED;
1051 }
1052
1053 /**
1054  * walker, do the optimizations
1055  */
1056 static void do_load_store_optimize(ir_node *n, void *env)
1057 {
1058   walk_env_t *wenv = env;
1059
1060   switch (get_irn_opcode(n)) {
1061
1062   case iro_Load:
1063     wenv->changes |= optimize_load(n);
1064     break;
1065
1066   case iro_Store:
1067     wenv->changes |= optimize_store(n);
1068     break;
1069
1070   case iro_Phi:
1071     wenv->changes |= optimize_phi(n, wenv);
1072
1073   default:
1074     ;
1075   }
1076 }
1077
1078 /*
1079  * do the load store optimization
1080  */
1081 void optimize_load_store(ir_graph *irg)
1082 {
1083   walk_env_t env;
1084   int        was_activ;
1085
1086   assert(get_irg_phase_state(irg) != phase_building);
1087   assert(get_irg_pinned(irg) != op_pin_state_floats &&
1088     "LoadStore optimization needs pinned graph");
1089
1090   if (! get_opt_redundant_loadstore())
1091     return;
1092
1093   was_activ = edges_activated(irg);
1094   if (was_activ) {
1095     /* we need "fresh" edges */
1096     edges_deactivate(irg);
1097   }
1098   edges_activate(irg);
1099
1100   obstack_init(&env.obst);
1101   env.changes = 0;
1102
1103   /* init the links, then collect Loads/Stores/Proj's in lists */
1104   master_visited = 0;
1105   irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1106
1107   /* now we have collected enough information, optimize */
1108   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1109
1110   obstack_free(&env.obst, NULL);
1111
1112   /* Handle graph state */
1113   if (env.changes) {
1114     if (get_irg_outs_state(irg) == outs_consistent)
1115       set_irg_outs_inconsistent(irg);
1116   }
1117
1118   if (env.changes & CF_CHANGED) {
1119     /* is this really needed: Yes, control flow changed, block might
1120        have Bad() predecessors. */
1121     set_irg_doms_inconsistent(irg);
1122   }
1123
1124   if (! was_activ)
1125     edges_deactivate(irg);
1126 }