fixed svn properties
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Load/Store optimizations.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <string.h>
31
32 #include "iroptimize.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "irmode_t.h"
36 #include "iropt_t.h"
37 #include "ircons_t.h"
38 #include "irgmod.h"
39 #include "irgwalk.h"
40 #include "irvrfy.h"
41 #include "tv_t.h"
42 #include "dbginfo_t.h"
43 #include "iropt_dbg.h"
44 #include "irflag_t.h"
45 #include "array.h"
46 #include "irhooks.h"
47 #include "iredges.h"
48 #include "irtools.h"
49 #include "opt_polymorphy.h"
50 #include "irmemory.h"
51 #include "xmalloc.h"
52 #include "irphase_t.h"
53 #include "irgopt.h"
54 #include "debug.h"
55
56 /** The debug handle. */
57 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
58
59 #ifdef DO_CACHEOPT
60 #include "cacheopt/cachesim.h"
61 #endif
62
63 #undef IMAX
64 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
65
66 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
67
68 enum changes_t {
69         DF_CHANGED = 1,       /**< data flow changed */
70         CF_CHANGED = 2,       /**< control flow changed */
71 };
72
73 /**
74  * walker environment
75  */
76 typedef struct _walk_env_t {
77         struct obstack obst;          /**< list of all stores */
78         unsigned changes;             /**< a bitmask of graph changes */
79 } walk_env_t;
80
81 /**
82  * flags for Load/Store
83  */
84 enum ldst_flags_t {
85         LDST_VISITED = 1              /**< if set, this Load/Store is already visited */
86 };
87
88 /** A Load/Store info. */
89 typedef struct _ldst_info_t {
90         ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
91         ir_node  *exc_block;          /**< the exception block if available */
92         int      exc_idx;             /**< predecessor index in the exception block */
93         unsigned flags;               /**< flags */
94         unsigned visited;             /**< visited counter for breaking loops */
95 } ldst_info_t;
96
97 /**
98  * flags for control flow.
99  */
100 enum block_flags_t {
101         BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
102         BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
103 };
104
105 /**
106  * a Block info.
107  */
108 typedef struct _block_info_t {
109         unsigned flags;               /**< flags for the block */
110 } block_info_t;
111
112 /** the master visited flag for loop detection. */
113 static unsigned master_visited = 0;
114
115 #define INC_MASTER()       ++master_visited
116 #define MARK_NODE(info)    (info)->visited = master_visited
117 #define NODE_VISITED(info) (info)->visited >= master_visited
118
119 /**
120  * get the Load/Store info of a node
121  */
122 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst) {
123         ldst_info_t *info = get_irn_link(node);
124
125         if (! info) {
126                 info = obstack_alloc(obst, sizeof(*info));
127                 memset(info, 0, sizeof(*info));
128                 set_irn_link(node, info);
129         }
130         return info;
131 }  /* get_ldst_info */
132
133 /**
134  * get the Block info of a node
135  */
136 static block_info_t *get_block_info(ir_node *node, struct obstack *obst) {
137         block_info_t *info = get_irn_link(node);
138
139         if (! info) {
140                 info = obstack_alloc(obst, sizeof(*info));
141                 memset(info, 0, sizeof(*info));
142                 set_irn_link(node, info);
143         }
144         return info;
145 }  /* get_block_info */
146
147 /**
148  * update the projection info for a Load/Store
149  */
150 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
151 {
152         long nr = get_Proj_proj(proj);
153
154         assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
155
156         if (info->projs[nr]) {
157                 /* there is already one, do CSE */
158                 exchange(proj, info->projs[nr]);
159                 return DF_CHANGED;
160         }
161         else {
162                 info->projs[nr] = proj;
163                 return 0;
164         }
165 }  /* update_projs */
166
167 /**
168  * update the exception block info for a Load/Store node.
169  *
170  * @param info   the load/store info struct
171  * @param block  the exception handler block for this load/store
172  * @param pos    the control flow input of the block
173  */
174 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
175 {
176         assert(info->exc_block == NULL && "more than one exception block found");
177
178         info->exc_block = block;
179         info->exc_idx   = pos;
180         return 0;
181 }  /* update_exc */
182
183 /** Return the number of uses of an address node */
184 #define get_irn_n_uses(adr)     get_irn_n_edges(adr)
185
186 /**
187  * walker, collects all Load/Store/Proj nodes
188  *
189  * walks from Start -> End
190  */
191 static void collect_nodes(ir_node *node, void *env)
192 {
193         ir_op       *op = get_irn_op(node);
194         ir_node     *pred, *blk, *pred_blk;
195         ldst_info_t *ldst_info;
196         walk_env_t  *wenv = env;
197
198         if (op == op_Proj) {
199                 ir_node *adr;
200                 ir_op *op;
201
202                 pred = get_Proj_pred(node);
203                 op   = get_irn_op(pred);
204
205                 if (op == op_Load) {
206                         ldst_info = get_ldst_info(pred, &wenv->obst);
207
208                         wenv->changes |= update_projs(ldst_info, node);
209
210                         if ((ldst_info->flags & LDST_VISITED) == 0) {
211                                 adr = get_Load_ptr(pred);
212                                 ldst_info->flags |= LDST_VISITED;
213                         }
214
215                         /*
216                          * Place the Proj's to the same block as the
217                          * predecessor Load. This is always ok and prevents
218                          * "non-SSA" form after optimizations if the Proj
219                          * is in a wrong block.
220                          */
221                         blk      = get_nodes_block(node);
222                         pred_blk = get_nodes_block(pred);
223                         if (blk != pred_blk) {
224                                 wenv->changes |= DF_CHANGED;
225                                 set_nodes_block(node, pred_blk);
226                         }
227                 } else if (op == op_Store) {
228                         ldst_info = get_ldst_info(pred, &wenv->obst);
229
230                         wenv->changes |= update_projs(ldst_info, node);
231
232                         if ((ldst_info->flags & LDST_VISITED) == 0) {
233                                 adr = get_Store_ptr(pred);
234                                 ldst_info->flags |= LDST_VISITED;
235                         }
236
237                         /*
238                         * Place the Proj's to the same block as the
239                         * predecessor Store. This is always ok and prevents
240                         * "non-SSA" form after optimizations if the Proj
241                         * is in a wrong block.
242                         */
243                         blk      = get_nodes_block(node);
244                         pred_blk = get_nodes_block(pred);
245                         if (blk != pred_blk) {
246                                 wenv->changes |= DF_CHANGED;
247                                 set_nodes_block(node, pred_blk);
248                         }
249                 }
250         } else if (op == op_Block) {
251                 int i;
252
253                 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
254                         ir_node      *pred_block, *proj;
255                         block_info_t *bl_info;
256                         int          is_exc = 0;
257
258                         pred = proj = get_Block_cfgpred(node, i);
259
260                         if (is_Proj(proj)) {
261                                 pred   = get_Proj_pred(proj);
262                                 is_exc = get_Proj_proj(proj) == pn_Generic_X_except;
263                         }
264
265                         /* ignore Bad predecessors, they will be removed later */
266                         if (is_Bad(pred))
267                                 continue;
268
269                         pred_block = get_nodes_block(pred);
270                         bl_info    = get_block_info(pred_block, &wenv->obst);
271
272                         if (is_fragile_op(pred) && is_exc)
273                                 bl_info->flags |= BLOCK_HAS_EXC;
274                         else if (is_irn_forking(pred))
275                                 bl_info->flags |= BLOCK_HAS_COND;
276
277                         if (is_exc && (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store)) {
278                                 ldst_info = get_ldst_info(pred, &wenv->obst);
279
280                                 wenv->changes |= update_exc(ldst_info, node, i);
281                         }
282                 }
283         }
284 }  /* collect_nodes */
285
286 /**
287  * Returns an entity if the address ptr points to a constant one.
288  *
289  * @param ptr  the address
290  *
291  * @return an entity or NULL
292  */
293 static ir_entity *find_constant_entity(ir_node *ptr)
294 {
295         for (;;) {
296                 ir_op *op = get_irn_op(ptr);
297
298                 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
299                         ir_entity *ent = get_SymConst_entity(ptr);
300                         if (variability_constant == get_entity_variability(ent))
301                                 return ent;
302                         return NULL;
303                 } else if (op == op_Sel) {
304                         ir_entity *ent = get_Sel_entity(ptr);
305                         ir_type   *tp  = get_entity_owner(ent);
306
307                         /* Do not fiddle with polymorphism. */
308                         if (is_Class_type(get_entity_owner(ent)) &&
309                                 ((get_entity_n_overwrites(ent)    != 0) ||
310                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
311                                 return NULL;
312
313                         if (is_Array_type(tp)) {
314                                 /* check bounds */
315                                 int i, n;
316
317                                 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
318                                         ir_node *bound;
319                                         tarval *tlower, *tupper;
320                                         ir_node *index = get_Sel_index(ptr, i);
321                                         tarval *tv     = computed_value(index);
322
323                                         /* check if the index is constant */
324                                         if (tv == tarval_bad)
325                                                 return NULL;
326
327                                         bound  = get_array_lower_bound(tp, i);
328                                         tlower = computed_value(bound);
329                                         bound  = get_array_upper_bound(tp, i);
330                                         tupper = computed_value(bound);
331
332                                         if (tlower == tarval_bad || tupper == tarval_bad)
333                                                 return NULL;
334
335                                         if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
336                                                 return NULL;
337                                         if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
338                                                 return NULL;
339
340                                         /* ok, bounds check finished */
341                                 }
342                         }
343
344                         if (variability_constant == get_entity_variability(ent))
345                                 return ent;
346
347                         /* try next */
348                         ptr = get_Sel_ptr(ptr);
349                 } else
350                         return NULL;
351         }
352 }  /* find_constant_entity */
353
354 /**
355  * Return the Selection index of a Sel node from dimension n
356  */
357 static long get_Sel_array_index_long(ir_node *n, int dim) {
358         ir_node *index = get_Sel_index(n, dim);
359         assert(is_Const(index));
360         return get_tarval_long(get_Const_tarval(index));
361 }  /* get_Sel_array_index_long */
362
363 /**
364  * Returns the accessed component graph path for an
365  * node computing an address.
366  *
367  * @param ptr    the node computing the address
368  * @param depth  current depth in steps upward from the root
369  *               of the address
370  */
371 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
372         compound_graph_path *res = NULL;
373         ir_entity           *root, *field;
374         int                 path_len, pos;
375
376         if (get_irn_op(ptr) == op_SymConst) {
377                 /* a SymConst. If the depth is 0, this is an access to a global
378                  * entity and we don't need a component path, else we know
379                  * at least it's length.
380                  */
381                 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
382                 root = get_SymConst_entity(ptr);
383                 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
384         } else {
385                 assert(get_irn_op(ptr) == op_Sel);
386                 /* it's a Sel, go up until we find the root */
387                 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
388
389                 /* fill up the step in the path at the current position */
390                 field    = get_Sel_entity(ptr);
391                 path_len = get_compound_graph_path_length(res);
392                 pos      = path_len - depth - 1;
393                 set_compound_graph_path_node(res, pos, field);
394
395                 if (is_Array_type(get_entity_owner(field))) {
396                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
397                         set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
398                 }
399         }
400         return res;
401 }  /* rec_get_accessed_path */
402
403 /** Returns an access path or NULL.  The access path is only
404  *  valid, if the graph is in phase_high and _no_ address computation is used.
405  */
406 static compound_graph_path *get_accessed_path(ir_node *ptr) {
407         return rec_get_accessed_path(ptr, 0);
408 }  /* get_accessed_path */
409
410 /* forward */
411 static void reduce_adr_usage(ir_node *ptr);
412
413 /**
414  * Update a Load that may lost it's usage.
415  */
416 static void handle_load_update(ir_node *load) {
417         ldst_info_t *info = get_irn_link(load);
418
419         /* do NOT touch volatile loads for now */
420         if (get_Load_volatility(load) == volatility_is_volatile)
421                 return;
422
423         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
424                 ir_node *ptr = get_Load_ptr(load);
425                 ir_node *mem = get_Load_mem(load);
426
427                 /* a Load which value is neither used nor exception checked, remove it */
428                 exchange(info->projs[pn_Load_M], mem);
429                 if (info->projs[pn_Load_X_regular])
430                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
431                 exchange(load, new_Bad());
432                 reduce_adr_usage(ptr);
433         }
434 }  /* handle_load_update */
435
436 /**
437  * A Use of an address node is vanished. Check if this was a Proj
438  * node and update the counters.
439  */
440 static void reduce_adr_usage(ir_node *ptr) {
441         if (is_Proj(ptr)) {
442                 if (get_irn_n_edges(ptr) <= 0) {
443                         /* this Proj is dead now */
444                         ir_node *pred = get_Proj_pred(ptr);
445
446                         if (is_Load(pred)) {
447                                 ldst_info_t *info = get_irn_link(pred);
448                                 info->projs[get_Proj_proj(ptr)] = NULL;
449
450                                 /* this node lost it's result proj, handle that */
451                                 handle_load_update(pred);
452                         }
453                 }
454         }
455 }  /* reduce_adr_usage */
456
457 /**
458  * Check, if an already existing value of mode old_mode can be converted
459  * into the needed one new_mode without loss.
460  */
461 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
462         if (old_mode == new_mode)
463                 return 1;
464
465         /* if both modes are two-complement ones, we can always convert the
466            Stored value into the needed one. */
467         if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
468                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
469                   get_mode_arithmetic(new_mode) == irma_twos_complement)
470                 return 1;
471         return 0;
472 }  /* can_use_stored_value */
473
474 /**
475  * Follow the memory chain as long as there are only Loads
476  * and alias free Stores and try to replace current Load or Store
477  * by a previous ones.
478  * Note that in unreachable loops it might happen that we reach
479  * load again, as well as we can fall into a cycle.
480  * We break such cycles using a special visited flag.
481  *
482  * INC_MASTER() must be called before dive into
483  */
484 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
485         unsigned res = 0;
486         ldst_info_t *info = get_irn_link(load);
487         ir_node *pred;
488         ir_node *ptr       = get_Load_ptr(load);
489         ir_node *mem       = get_Load_mem(load);
490         ir_mode *load_mode = get_Load_mode(load);
491
492         for (pred = curr; load != pred; ) {
493                 ldst_info_t *pred_info = get_irn_link(pred);
494
495                 /*
496                  * BEWARE: one might think that checking the modes is useless, because
497                  * if the pointers are identical, they refer to the same object.
498                  * This is only true in strong typed languages, not in C were the following
499                  * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
500                  */
501                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
502                     can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
503                         /*
504                          * a Load immediately after a Store -- a read after write.
505                          * We may remove the Load, if both Load & Store does not have an exception handler
506                          * OR they are in the same MacroBlock. In the latter case the Load cannot
507                          * throw an exception when the previous Store was quiet.
508                          *
509                          * Why we need to check for Store Exception? If the Store cannot
510                          * be executed (ROM) the exception handler might simply jump into
511                          * the load MacroBlock :-(
512                          * We could make it a little bit better if we would know that the exception
513                          * handler of the Store jumps directly to the end...
514                          */
515                         if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
516                             get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
517                                 ir_node *value = get_Store_value(pred);
518
519                                 DBG_OPT_RAW(load, value);
520
521                                 /* add an convert if needed */
522                                 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
523                                         value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
524                                 }
525
526                                 if (info->projs[pn_Load_M])
527                                         exchange(info->projs[pn_Load_M], mem);
528
529                                 /* no exception */
530                                 if (info->projs[pn_Load_X_except]) {
531                                         exchange( info->projs[pn_Load_X_except], new_Bad());
532                                         res |= CF_CHANGED;
533                                 }
534                                 if (info->projs[pn_Load_X_regular]) {
535                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
536                                         res |= CF_CHANGED;
537                                 }
538
539                                 if (info->projs[pn_Load_res])
540                                         exchange(info->projs[pn_Load_res], value);
541
542                                 exchange(load, new_Bad());
543                                 reduce_adr_usage(ptr);
544                                 return res | DF_CHANGED;
545                         }
546                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
547                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
548                         /*
549                          * a Load after a Load -- a read after read.
550                          * We may remove the second Load, if it does not have an exception handler
551                          * OR they are in the same MacroBlock. In the later case the Load cannot
552                          * throw an exception when the previous Load was quiet.
553                          *
554                          * Here, there is no need to check if the previous Load has an exception
555                          * hander because they would have exact the same exception...
556                          */
557                         if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
558                                 ir_node *value;
559
560                                 DBG_OPT_RAR(load, pred);
561
562                                 /* the result is used */
563                                 if (info->projs[pn_Load_res]) {
564                                         if (pred_info->projs[pn_Load_res] == NULL) {
565                                                 /* create a new Proj again */
566                                                 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
567                                         }
568                                         value = pred_info->projs[pn_Load_res];
569
570                                         /* add an convert if needed */
571                                         if (get_Load_mode(pred) != load_mode) {
572                                                 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
573                                         }
574
575                                         exchange(info->projs[pn_Load_res], value);
576                                 }
577
578                                 if (info->projs[pn_Load_M])
579                                         exchange(info->projs[pn_Load_M], mem);
580
581                                 /* no exception */
582                                 if (info->projs[pn_Load_X_except]) {
583                                         exchange(info->projs[pn_Load_X_except], new_Bad());
584                                         res |= CF_CHANGED;
585                                 }
586                                 if (info->projs[pn_Load_X_regular]) {
587                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
588                                         res |= CF_CHANGED;
589                                 }
590
591                                 exchange(load, new_Bad());
592                                 reduce_adr_usage(ptr);
593                                 return res |= DF_CHANGED;
594                         }
595                 }
596
597                 if (is_Store(pred)) {
598                         /* check if we can pass through this store */
599                         ir_alias_relation rel = get_alias_relation(
600                                 current_ir_graph,
601                                 get_Store_ptr(pred),
602                                 get_irn_mode(get_Store_value(pred)),
603                                 ptr, load_mode);
604                         /* if the might be an alias, we cannot pass this Store */
605                         if (rel != no_alias)
606                                 break;
607                         pred = skip_Proj(get_Store_mem(pred));
608                 } else if (get_irn_op(pred) == op_Load) {
609                         pred = skip_Proj(get_Load_mem(pred));
610                 } else {
611                         /* follow only Load chains */
612                         break;
613                 }
614
615                 /* check for cycles */
616                 if (NODE_VISITED(pred_info))
617                         break;
618                 MARK_NODE(pred_info);
619         }
620
621         if (is_Sync(pred)) {
622                 int i;
623
624                 /* handle all Sync predecessors */
625                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
626                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
627                         if (res)
628                                 break;
629                 }
630         }
631
632         return res;
633 }  /* follow_Mem_chain */
634
635 /**
636  * optimize a Load
637  *
638  * @param load  the Load node
639  */
640 static unsigned optimize_load(ir_node *load)
641 {
642         ldst_info_t *info = get_irn_link(load);
643         ir_node *mem, *ptr, *new_node;
644         ir_entity *ent;
645         unsigned res = 0;
646
647         /* do NOT touch volatile loads for now */
648         if (get_Load_volatility(load) == volatility_is_volatile)
649                 return 0;
650
651         /* the address of the load to be optimized */
652         ptr = get_Load_ptr(load);
653
654         /*
655          * Check if we can remove the exception from a Load:
656          * This can be done, if the address is from an Sel(Alloc) and
657          * the Sel type is a subtype of the allocated type.
658          *
659          * This optimizes some often used OO constructs,
660          * like x = new O; x->t;
661          */
662         if (info->projs[pn_Load_X_except]) {
663                 if (is_Sel(ptr)) {
664                         ir_node *mem = get_Sel_mem(ptr);
665
666                         /* FIXME: works with the current FE, but better use the base */
667                         if (is_Alloc(skip_Proj(mem))) {
668                                 /* ok, check the types */
669                                 ir_entity *ent    = get_Sel_entity(ptr);
670                                 ir_type   *s_type = get_entity_type(ent);
671                                 ir_type   *a_type = get_Alloc_type(mem);
672
673                                 if (is_SubClass_of(s_type, a_type)) {
674                                         /* ok, condition met: there can't be an exception because
675                                         * Alloc guarantees that enough memory was allocated */
676
677                                         exchange(info->projs[pn_Load_X_except], new_Bad());
678                                         info->projs[pn_Load_X_except] = NULL;
679                                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
680                                         info->projs[pn_Load_X_regular] = NULL;
681                                         res |= CF_CHANGED;
682                                 }
683                         }
684                 } else if (is_Alloc(skip_Proj(skip_Cast(ptr)))) {
685                                 /* simple case: a direct load after an Alloc. Firm Alloc throw
686                                  * an exception in case of out-of-memory. So, there is no way for an
687                                  * exception in this load.
688                                  * This code is constructed by the "exception lowering" in the Jack compiler.
689                                  */
690                                 exchange(info->projs[pn_Load_X_except], new_Bad());
691                                 info->projs[pn_Load_X_except] = NULL;
692                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
693                                 info->projs[pn_Load_X_regular] = NULL;
694                                 res |= CF_CHANGED;
695                 }
696         }
697
698         /* The mem of the Load. Must still be returned after optimization. */
699         mem  = get_Load_mem(load);
700
701         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
702                 /* a Load which value is neither used nor exception checked, remove it */
703                 exchange(info->projs[pn_Load_M], mem);
704
705                 if (info->projs[pn_Load_X_regular]) {
706                         /* should not happen, but if it does, remove it */
707                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
708                         res |= CF_CHANGED;
709                 }
710                 exchange(load, new_Bad());
711                 reduce_adr_usage(ptr);
712                 return res | DF_CHANGED;
713         }
714
715         /* Load from a constant polymorphic field, where we can resolve
716            polymorphism. */
717         new_node = transform_node_Load(load);
718         if (new_node != load) {
719                 if (info->projs[pn_Load_M]) {
720                         exchange(info->projs[pn_Load_M], mem);
721                         info->projs[pn_Load_M] = NULL;
722                 }
723                 if (info->projs[pn_Load_X_except]) {
724                         exchange(info->projs[pn_Load_X_except], new_Bad());
725                         info->projs[pn_Load_X_except] = NULL;
726                         res |= CF_CHANGED;
727                 }
728                 if (info->projs[pn_Load_X_regular]) {
729                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
730                         info->projs[pn_Load_X_regular] = NULL;
731                         res |= CF_CHANGED;
732                 }
733                 if (info->projs[pn_Load_res])
734                         exchange(info->projs[pn_Load_res], new_node);
735
736                 exchange(load, new_Bad());
737                 reduce_adr_usage(ptr);
738                 return res | DF_CHANGED;
739         }
740
741         /* check if we can determine the entity that will be loaded */
742         ent = find_constant_entity(ptr);
743         if (ent) {
744                 if ((allocation_static == get_entity_allocation(ent)) &&
745                         (visibility_external_allocated != get_entity_visibility(ent))) {
746                         /* a static allocation that is not external: there should be NO exception
747                          * when loading. */
748
749                         /* no exception, clear the info field as it might be checked later again */
750                         if (info->projs[pn_Load_X_except]) {
751                                 exchange(info->projs[pn_Load_X_except], new_Bad());
752                                 info->projs[pn_Load_X_except] = NULL;
753                                 res |= CF_CHANGED;
754                         }
755                         if (info->projs[pn_Load_X_regular]) {
756                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
757                                 info->projs[pn_Load_X_regular] = NULL;
758                                 res |= CF_CHANGED;
759                         }
760
761                         if (variability_constant == get_entity_variability(ent)) {
762                                 if (is_atomic_entity(ent)) {
763                                         /* Might not be atomic after
764                                            lowering of Sels.  In this
765                                            case we could also load, but
766                                            it's more complicated. */
767                                         /* more simpler case: we load the content of a constant value:
768                                          * replace it by the constant itself
769                                          */
770
771                                         /* no memory */
772                                         if (info->projs[pn_Load_M]) {
773                                                 exchange(info->projs[pn_Load_M], mem);
774                                                 res |= DF_CHANGED;
775                                         }
776                                         /* no result :-) */
777                                         if (info->projs[pn_Load_res]) {
778                                                 if (is_atomic_entity(ent)) {
779                                                         ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
780
781                                                         DBG_OPT_RC(load, c);
782                                                         exchange(info->projs[pn_Load_res], c);
783                                                         res |= DF_CHANGED;
784                                                 }
785                                         }
786                                         exchange(load, new_Bad());
787                                         reduce_adr_usage(ptr);
788                                         return res;
789                                 } else {
790                                         compound_graph_path *path = get_accessed_path(ptr);
791
792                                         if (path) {
793                                                 ir_node *c;
794
795                                                 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
796                                                 /*
797                                                 {
798                                                         int j;
799                                                         for (j = 0; j < get_compound_graph_path_length(path); ++j) {
800                                                                 ir_entity *node = get_compound_graph_path_node(path, j);
801                                                                 fprintf(stdout, ".%s", get_entity_name(node));
802                                                                 if (is_Array_type(get_entity_owner(node)))
803                                                                         fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
804                                                         }
805                                                         printf("\n");
806                                                 }
807                                                 */
808
809                                                 c = get_compound_ent_value_by_path(ent, path);
810                                                 free_compound_graph_path(path);
811
812                                                 /* printf("  cons: "); DDMN(c); */
813
814                                                 if (info->projs[pn_Load_M]) {
815                                                         exchange(info->projs[pn_Load_M], mem);
816                                                         res |= DF_CHANGED;
817                                                 }
818                                                 if (info->projs[pn_Load_res]) {
819                                                         exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
820                                                         res |= DF_CHANGED;
821                                                 }
822                                                 exchange(load, new_Bad());
823                                                 reduce_adr_usage(ptr);
824                                                 return res;
825                                         } else {
826                                                 /*  We can not determine a correct access path.  E.g., in jack, we load
827                                                 a byte from an object to generate an exception.   Happens in test program
828                                                 Reflectiontest.
829                                                 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
830                                                 get_entity_name(get_irg_entity(current_ir_graph)));
831                                                 printf("  load: "); DDMN(load);
832                                                 printf("  ptr:  "); DDMN(ptr);
833                                                 */
834                                         }
835                                 }
836                         }
837                 }
838         }
839
840         /* Check, if the address of this load is used more than once.
841          * If not, this load cannot be removed in any case. */
842         if (get_irn_n_uses(ptr) <= 1)
843                 return res;
844
845         /*
846          * follow the memory chain as long as there are only Loads
847          * and try to replace current Load or Store by a previous one.
848          * Note that in unreachable loops it might happen that we reach
849          * load again, as well as we can fall into a cycle.
850          * We break such cycles using a special visited flag.
851          */
852         INC_MASTER();
853         res = follow_Mem_chain(load, skip_Proj(mem));
854         return res;
855 }  /* optimize_load */
856
857 /**
858  * Check whether a value of mode new_mode would completely overwrite a value
859  * of mode old_mode in memory.
860  */
861 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
862 {
863         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
864 }  /* is_completely_overwritten */
865
866 /**
867  * follow the memory chain as long as there are only Loads and alias free Stores.
868  *
869  * INC_MASTER() must be called before dive into
870  */
871 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
872         unsigned res = 0;
873         ldst_info_t *info = get_irn_link(store);
874         ir_node *pred;
875         ir_node *ptr = get_Store_ptr(store);
876         ir_node *mem = get_Store_mem(store);
877         ir_node *value = get_Store_value(store);
878         ir_mode *mode  = get_irn_mode(value);
879         ir_node *block = get_nodes_block(store);
880         ir_node *mblk  = get_Block_MacroBlock(block);
881
882         for (pred = curr; pred != store;) {
883                 ldst_info_t *pred_info = get_irn_link(pred);
884
885                 /*
886                  * BEWARE: one might think that checking the modes is useless, because
887                  * if the pointers are identical, they refer to the same object.
888                  * This is only true in strong typed languages, not is C were the following
889                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
890                  * However, if the mode that is written have a bigger  or equal size the the old
891                  * one, the old value is completely overwritten and can be killed ...
892                  */
893                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
894                     get_nodes_MacroBlock(pred) == mblk &&
895                     is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
896                         /*
897                          * a Store after a Store in the same block -- a write after write.
898                          * We may remove the first Store, if it does not have an exception handler.
899                          *
900                          * TODO: What, if both have the same exception handler ???
901                          */
902                         if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
903                                 DBG_OPT_WAW(pred, store);
904                                 exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
905                                 exchange(pred, new_Bad());
906                                 reduce_adr_usage(ptr);
907                                 return DF_CHANGED;
908                         }
909                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
910                            value == pred_info->projs[pn_Load_res]) {
911                         /*
912                          * a Store of a value after a Load -- a write after read.
913                          * We may remove the second Store, if it does not have an exception handler.
914                          */
915                         if (! info->projs[pn_Store_X_except]) {
916                                 DBG_OPT_WAR(store, pred);
917                                 exchange(info->projs[pn_Store_M], mem);
918                                 exchange(store, new_Bad());
919                                 reduce_adr_usage(ptr);
920                                 return DF_CHANGED;
921                         }
922                 }
923
924                 if (is_Store(pred)) {
925                         /* check if we can pass thru this store */
926                         ir_alias_relation rel = get_alias_relation(
927                                 current_ir_graph,
928                                 get_Store_ptr(pred),
929                                 get_irn_mode(get_Store_value(pred)),
930                                 ptr, mode);
931                         /* if the might be an alias, we cannot pass this Store */
932                         if (rel != no_alias)
933                                 break;
934                         pred = skip_Proj(get_Store_mem(pred));
935                 } else if (get_irn_op(pred) == op_Load) {
936                         pred = skip_Proj(get_Load_mem(pred));
937                 } else {
938                         /* follow only Load chains */
939                         break;
940                 }
941
942                 /* check for cycles */
943                 if (NODE_VISITED(pred_info))
944                         break;
945                 MARK_NODE(pred_info);
946         }
947
948         if (is_Sync(pred)) {
949                 int i;
950
951                 /* handle all Sync predecessors */
952                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
953                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
954                         if (res)
955                                 break;
956                 }
957         }
958         return res;
959 }  /* follow_Mem_chain_for_Store */
960
961 /**
962  * optimize a Store
963  *
964  * @param store  the Store node
965  */
966 static unsigned optimize_store(ir_node *store) {
967         ir_node *ptr, *mem;
968
969         if (get_Store_volatility(store) == volatility_is_volatile)
970                 return 0;
971
972         ptr = get_Store_ptr(store);
973
974         /* Check, if the address of this Store is used more than once.
975          * If not, this Store cannot be removed in any case. */
976         if (get_irn_n_uses(ptr) <= 1)
977                 return 0;
978
979         mem = get_Store_mem(store);
980
981         /* follow the memory chain as long as there are only Loads */
982         INC_MASTER();
983         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
984 }  /* optimize_store */
985
986 /**
987  * walker, optimizes Phi after Stores to identical places:
988  * Does the following optimization:
989  * @verbatim
990  *
991  *   val1   val2   val3          val1  val2  val3
992  *    |      |      |               \    |    /
993  *  Store  Store  Store              \   |   /
994  *      \    |    /                   PhiData
995  *       \   |   /                       |
996  *        \  |  /                      Store
997  *          PhiM
998  *
999  * @endverbatim
1000  * This reduces the number of stores and allows for predicated execution.
1001  * Moves Stores back to the end of a function which may be bad.
1002  *
1003  * This is only possible if the predecessor blocks have only one successor.
1004  */
1005 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1006 {
1007         int i, n;
1008         ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1009         ir_mode *mode;
1010         ir_node **inM, **inD, **projMs;
1011         int *idx;
1012         dbg_info *db = NULL;
1013         ldst_info_t *info;
1014         block_info_t *bl_info;
1015         unsigned res = 0;
1016
1017         /* Must be a memory Phi */
1018         if (get_irn_mode(phi) != mode_M)
1019                 return 0;
1020
1021         n = get_Phi_n_preds(phi);
1022         if (n <= 0)
1023                 return 0;
1024
1025         /* must be only one user */
1026         projM = get_Phi_pred(phi, 0);
1027         if (get_irn_n_edges(projM) != 1)
1028                 return 0;
1029
1030         store = skip_Proj(projM);
1031         old_store = store;
1032         if (get_irn_op(store) != op_Store)
1033                 return 0;
1034
1035         block = get_nodes_block(store);
1036
1037         /* abort on dead blocks */
1038         if (is_Block_dead(block))
1039                 return 0;
1040
1041         /* check if the block is post dominated by Phi-block
1042            and has no exception exit */
1043         bl_info = get_irn_link(block);
1044         if (bl_info->flags & BLOCK_HAS_EXC)
1045                 return 0;
1046
1047         phi_block = get_nodes_block(phi);
1048         if (! block_strictly_postdominates(phi_block, block))
1049                 return 0;
1050
1051         /* this is the address of the store */
1052         ptr  = get_Store_ptr(store);
1053         mode = get_irn_mode(get_Store_value(store));
1054         info = get_irn_link(store);
1055         exc  = info->exc_block;
1056
1057         for (i = 1; i < n; ++i) {
1058                 ir_node *pred = get_Phi_pred(phi, i);
1059
1060                 if (get_irn_n_edges(pred) != 1)
1061                         return 0;
1062
1063                 pred = skip_Proj(pred);
1064                 if (!is_Store(pred))
1065                         return 0;
1066
1067                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1068                         return 0;
1069
1070                 info = get_irn_link(pred);
1071
1072                 /* check, if all stores have the same exception flow */
1073                 if (exc != info->exc_block)
1074                         return 0;
1075
1076                 /* abort on dead blocks */
1077                 block = get_nodes_block(pred);
1078                 if (is_Block_dead(block))
1079                         return 0;
1080
1081                 /* check if the block is post dominated by Phi-block
1082                    and has no exception exit. Note that block must be different from
1083                    Phi-block, else we would move a Store from end End of a block to its
1084                    Start... */
1085                 bl_info = get_irn_link(block);
1086                 if (bl_info->flags & BLOCK_HAS_EXC)
1087                         return 0;
1088                 if (block == phi_block || ! block_postdominates(phi_block, block))
1089                         return 0;
1090         }
1091
1092         /*
1093          * ok, when we are here, we found all predecessors of a Phi that
1094          * are Stores to the same address and size. That means whatever
1095          * we do before we enter the block of the Phi, we do a Store.
1096          * So, we can move the Store to the current block:
1097          *
1098          *   val1    val2    val3          val1  val2  val3
1099          *    |       |       |               \    |    /
1100          * | Str | | Str | | Str |             \   |   /
1101          *      \     |     /                   PhiData
1102          *       \    |    /                       |
1103          *        \   |   /                       Str
1104          *           PhiM
1105          *
1106          * Is only allowed if the predecessor blocks have only one successor.
1107          */
1108
1109         NEW_ARR_A(ir_node *, projMs, n);
1110         NEW_ARR_A(ir_node *, inM, n);
1111         NEW_ARR_A(ir_node *, inD, n);
1112         NEW_ARR_A(int, idx, n);
1113
1114         /* Prepare: Collect all Store nodes.  We must do this
1115            first because we otherwise may loose a store when exchanging its
1116            memory Proj.
1117          */
1118         for (i = n - 1; i >= 0; --i) {
1119                 ir_node *store;
1120
1121                 projMs[i] = get_Phi_pred(phi, i);
1122                 assert(is_Proj(projMs[i]));
1123
1124                 store = get_Proj_pred(projMs[i]);
1125                 info  = get_irn_link(store);
1126
1127                 inM[i] = get_Store_mem(store);
1128                 inD[i] = get_Store_value(store);
1129                 idx[i] = info->exc_idx;
1130         }
1131         block = get_nodes_block(phi);
1132
1133         /* second step: create a new memory Phi */
1134         phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1135
1136         /* third step: create a new data Phi */
1137         phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1138
1139         /* rewire memory and kill the node */
1140         for (i = n - 1; i >= 0; --i) {
1141                 ir_node *proj  = projMs[i];
1142
1143                 if(is_Proj(proj)) {
1144                         ir_node *store = get_Proj_pred(proj);
1145                         exchange(proj, inM[i]);
1146                         kill_node(store);
1147                 }
1148         }
1149
1150         /* fourth step: create the Store */
1151         store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1152 #ifdef DO_CACHEOPT
1153         co_set_irn_name(store, co_get_irn_ident(old_store));
1154 #endif
1155
1156         projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1157
1158         info = get_ldst_info(store, &wenv->obst);
1159         info->projs[pn_Store_M] = projM;
1160
1161         /* fifths step: repair exception flow */
1162         if (exc) {
1163                 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1164
1165                 info->projs[pn_Store_X_except] = projX;
1166                 info->exc_block                = exc;
1167                 info->exc_idx                  = idx[0];
1168
1169                 for (i = 0; i < n; ++i) {
1170                         set_Block_cfgpred(exc, idx[i], projX);
1171                 }
1172
1173                 if (n > 1) {
1174                         /* the exception block should be optimized as some inputs are identical now */
1175                 }
1176
1177                 res |= CF_CHANGED;
1178         }
1179
1180         /* sixth step: replace old Phi */
1181         exchange(phi, projM);
1182
1183         return res | DF_CHANGED;
1184 }  /* optimize_phi */
1185
1186 /**
1187  * walker, do the optimizations
1188  */
1189 static void do_load_store_optimize(ir_node *n, void *env) {
1190         walk_env_t *wenv = env;
1191
1192         switch (get_irn_opcode(n)) {
1193
1194         case iro_Load:
1195                 wenv->changes |= optimize_load(n);
1196                 break;
1197
1198         case iro_Store:
1199                 wenv->changes |= optimize_store(n);
1200                 break;
1201
1202         case iro_Phi:
1203                 wenv->changes |= optimize_phi(n, wenv);
1204
1205         default:
1206                 ;
1207         }
1208 }  /* do_load_store_optimize */
1209
1210 /** A scc. */
1211 typedef struct scc {
1212         ir_node *head;          /**< the head of the list */
1213 } scc;
1214
1215 /** A node entry. */
1216 typedef struct node_entry {
1217         unsigned DFSnum;    /**< the DFS number of this node */
1218         unsigned low;       /**< the low number of this node */
1219         ir_node  *header;   /**< the header of this node */
1220         int      in_stack;  /**< flag, set if the node is on the stack */
1221         ir_node  *next;     /**< link to the next node the the same scc */
1222         scc      *pscc;     /**< the scc of this node */
1223         unsigned POnum;     /**< the post order number for blocks */
1224 } node_entry;
1225
1226 /** A loop entry. */
1227 typedef struct loop_env {
1228         ir_phase ph;           /**< the phase object */
1229         ir_node  **stack;      /**< the node stack */
1230         int      tos;          /**< tos index */
1231         unsigned nextDFSnum;   /**< the current DFS number */
1232         unsigned POnum;        /**< current post order number */
1233
1234         unsigned changes;      /**< a bitmask of graph changes */
1235 } loop_env;
1236
1237 /**
1238 * Gets the node_entry of a node
1239 */
1240 static node_entry *get_irn_ne(ir_node *irn, loop_env *env) {
1241         ir_phase   *ph = &env->ph;
1242         node_entry *e  = phase_get_irn_data(&env->ph, irn);
1243
1244         if (! e) {
1245                 e = phase_alloc(ph, sizeof(*e));
1246                 memset(e, 0, sizeof(*e));
1247                 phase_set_irn_data(ph, irn, e);
1248         }
1249         return e;
1250 }  /* get_irn_ne */
1251
1252 /**
1253  * Push a node onto the stack.
1254  *
1255  * @param env   the loop environment
1256  * @param n     the node to push
1257  */
1258 static void push(loop_env *env, ir_node *n) {
1259         node_entry *e;
1260
1261         if (env->tos == ARR_LEN(env->stack)) {
1262                 int nlen = ARR_LEN(env->stack) * 2;
1263                 ARR_RESIZE(ir_node *, env->stack, nlen);
1264         }
1265         env->stack[env->tos++] = n;
1266         e = get_irn_ne(n, env);
1267         e->in_stack = 1;
1268 }  /* push */
1269
1270 /**
1271  * pop a node from the stack
1272  *
1273  * @param env   the loop environment
1274  *
1275  * @return  The topmost node
1276  */
1277 static ir_node *pop(loop_env *env) {
1278         ir_node *n = env->stack[--env->tos];
1279         node_entry *e = get_irn_ne(n, env);
1280
1281         e->in_stack = 0;
1282         return n;
1283 }  /* pop */
1284
1285 /**
1286  * Check if irn is a region constant.
1287  * The block or irn must strictly dominate the header block.
1288  *
1289  * @param irn           the node to check
1290  * @param header_block  the header block of the induction variable
1291  */
1292 static int is_rc(ir_node *irn, ir_node *header_block) {
1293         ir_node *block = get_nodes_block(irn);
1294
1295         return (block != header_block) && block_dominates(block, header_block);
1296 }  /* is_rc */
1297
1298 typedef struct phi_entry phi_entry;
1299 struct phi_entry {
1300         ir_node   *phi;    /**< A phi with a region const memory. */
1301         int       pos;     /**< The position of the region const memory */
1302         ir_node   *load;   /**< the newly created load for this phi */
1303         phi_entry *next;
1304 };
1305
1306 /**
1307  * Move loops out of loops if possible
1308  */
1309 static void move_loads_in_loops(scc *pscc, loop_env *env) {
1310         ir_node   *phi, *load, *next, *other, *next_other;
1311         ir_entity *ent;
1312         int       j;
1313         phi_entry *phi_list = NULL;
1314
1315         /* collect all outer memories */
1316         for (phi = pscc->head; phi != NULL; phi = next) {
1317                 node_entry *ne = get_irn_ne(phi, env);
1318                 next = ne->next;
1319
1320                 /* check all memory Phi's */
1321                 if (! is_Phi(phi))
1322                         continue;
1323
1324                 assert(get_irn_mode(phi) == mode_M && "DFS geturn non-memory Phi");
1325
1326                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1327                         ir_node    *pred = get_irn_n(phi, j);
1328                         node_entry *pe   = get_irn_ne(pred, env);
1329
1330                         if (pe->pscc != ne->pscc) {
1331                                 /* not in the same SCC, is region const */
1332                                 phi_entry *pe = phase_alloc(&env->ph, sizeof(*pe));
1333
1334                                 pe->phi  = phi;
1335                                 pe->pos  = j;
1336                                 pe->next = phi_list;
1337                                 phi_list = pe;
1338                         }
1339                 }
1340         }
1341         /* no Phis no fun */
1342         assert(phi_list != NULL && "DFS found a loop without Phi");
1343
1344         for (load = pscc->head; load; load = next) {
1345                 ir_mode *load_mode;
1346                 node_entry *ne = get_irn_ne(load, env);
1347                 next = ne->next;
1348
1349                 if (is_Load(load)) {
1350                         ldst_info_t *info = get_irn_link(load);
1351                         ir_node     *ptr = get_Load_ptr(load);
1352
1353                         /* for now, we cannot handle Loads with exceptions */
1354                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1355                                 continue;
1356
1357                         /* for now, we can only handle Load(SymConst) */
1358                         if (! is_SymConst(ptr) || get_SymConst_kind(ptr) != symconst_addr_ent)
1359                                 continue;
1360                         ent = get_SymConst_entity(ptr);
1361                         load_mode = get_Load_mode(load);
1362                         for (other = pscc->head; other != NULL; other = next_other) {
1363                                 node_entry *ne = get_irn_ne(other, env);
1364                                 next_other = ne->next;
1365
1366                                 if (is_Store(other)) {
1367                                         ir_alias_relation rel = get_alias_relation(
1368                                                 current_ir_graph,
1369                                                 get_Store_ptr(other),
1370                                                 get_irn_mode(get_Store_value(other)),
1371                                                 ptr, load_mode);
1372                                         /* if the might be an alias, we cannot pass this Store */
1373                                         if (rel != no_alias)
1374                                                 break;
1375                                 }
1376                         }
1377                         if (other == NULL) {
1378                                 ldst_info_t *ninfo;
1379                                 phi_entry   *pe;
1380                                 dbg_info    *db;
1381
1382                                 /* for now, we cannot handle more than one input */
1383                                 if (phi_list->next != NULL)
1384                                         return;
1385
1386                                 /* yep, no aliasing Store found, Load can be moved */
1387                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1388
1389                                 db   = get_irn_dbg_info(load);
1390                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1391                                         int     pos   = pe->pos;
1392                                         ir_node *phi  = pe->phi;
1393                                         ir_node *blk  = get_nodes_block(phi);
1394                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1395                                         ir_node *irn, *mem;
1396
1397                                         pe->load = irn = new_rd_Load(db, current_ir_graph, pred, get_Phi_pred(phi, pos), ptr, load_mode);
1398                                         ninfo = get_ldst_info(irn, phase_obst(&env->ph));
1399
1400                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(current_ir_graph, pred, irn, mode_M, pn_Load_M);
1401                                         set_Phi_pred(phi, pos, mem);
1402
1403                                         ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1404
1405                                         DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1406                                 }
1407
1408                                 /* now kill the old Load */
1409                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1410                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1411
1412                                 env->changes |= DF_CHANGED;
1413                         }
1414                 }
1415         }
1416 }  /* move_loads_in_loops */
1417
1418 /**
1419  * Process a loop SCC.
1420  *
1421  * @param pscc  the SCC
1422  * @param env   the loop environment
1423  */
1424 static void process_loop(scc *pscc, loop_env *env) {
1425         ir_node *irn, *next, *header = NULL;
1426         node_entry *b, *h = NULL;
1427         int j, only_phi, num_outside, process = 0;
1428         ir_node *out_rc;
1429
1430         /* find the header block for this scc */
1431         for (irn = pscc->head; irn; irn = next) {
1432                 node_entry *e = get_irn_ne(irn, env);
1433                 ir_node *block = get_nodes_block(irn);
1434
1435                 next = e->next;
1436                 b = get_irn_ne(block, env);
1437
1438                 if (header) {
1439                         if (h->POnum < b->POnum) {
1440                                 header = block;
1441                                 h      = b;
1442                         }
1443                 }
1444                 else {
1445                         header = block;
1446                         h      = b;
1447                 }
1448         }
1449
1450         /* check if this scc contains only Phi, Loads or Stores nodes */
1451         only_phi    = 1;
1452         num_outside = 0;
1453         out_rc      = NULL;
1454         for (irn = pscc->head; irn; irn = next) {
1455                 node_entry *e = get_irn_ne(irn, env);
1456
1457                 next = e->next;
1458                 switch (get_irn_opcode(irn)) {
1459                 case iro_Call:
1460                 case iro_CopyB:
1461                         /* cannot handle Calls or CopyB yet */
1462                         goto fail;
1463                 case iro_Load:
1464                         process = 1;
1465                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1466                                 /* cannot handle loops with volatile Loads */
1467                                 goto fail;
1468                         }
1469                         only_phi = 0;
1470                         break;
1471                 case iro_Store:
1472                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1473                                 /* cannot handle loops with volatile Stores */
1474                                 goto fail;
1475                         }
1476                         only_phi = 0;
1477                         break;
1478                 default:
1479                         only_phi = 0;
1480                         break;
1481                 case iro_Phi:
1482                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1483                                 ir_node *pred  = get_irn_n(irn, j);
1484                                 node_entry *pe = get_irn_ne(pred, env);
1485
1486                                 if (pe->pscc != e->pscc) {
1487                                         /* not in the same SCC, must be a region const */
1488                                         if (! is_rc(pred, header)) {
1489                                                 /* not a memory loop */
1490                                                 goto fail;
1491                                         }
1492                                         if (! out_rc) {
1493                                                 out_rc = pred;
1494                                                 ++num_outside;
1495                                         } else if (out_rc != pred) {
1496                                                 ++num_outside;
1497                                         }
1498                                 }
1499                         }
1500                         break;
1501                 }
1502         }
1503         if (! process)
1504                 goto fail;
1505
1506         /* found a memory loop */
1507         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1508         if (only_phi && num_outside == 1) {
1509                 /* a phi cycle with only one real predecessor can be collapsed */
1510                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1511
1512                 for (irn = pscc->head; irn; irn = next) {
1513                         node_entry *e = get_irn_ne(irn, env);
1514                         next = e->next;
1515                         e->header = NULL;
1516                         exchange(irn, out_rc);
1517                 }
1518                 env->changes |= DF_CHANGED;
1519                 return;
1520         }
1521
1522         /* set the header for every node in this scc */
1523         for (irn = pscc->head; irn; irn = next) {
1524                 node_entry *e = get_irn_ne(irn, env);
1525                 e->header = header;
1526                 next = e->next;
1527                 DB((dbg, LEVEL_2, " %+F,", irn));
1528         }
1529         DB((dbg, LEVEL_2, "\n"));
1530
1531         move_loads_in_loops(pscc, env);
1532
1533 fail:
1534         ;
1535 }  /* process_loop */
1536
1537 /**
1538  * Process a SCC.
1539  *
1540  * @param pscc  the SCC
1541  * @param env   the loop environment
1542  */
1543 static void process_scc(scc *pscc, loop_env *env) {
1544         ir_node *head = pscc->head;
1545         node_entry *e = get_irn_ne(head, env);
1546
1547 #ifdef DEBUG_libfirm
1548         {
1549                 ir_node *irn, *next;
1550
1551                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1552                 for (irn = pscc->head; irn; irn = next) {
1553                         node_entry *e = get_irn_ne(irn, env);
1554
1555                         next = e->next;
1556
1557                         DB((dbg, LEVEL_4, " %+F,", irn));
1558                 }
1559                 DB((dbg, LEVEL_4, "\n"));
1560         }
1561 #endif
1562
1563         if (e->next != NULL) {
1564                 /* this SCC has more than one member */
1565                 process_loop(pscc, env);
1566         }
1567 }  /* process_scc */
1568
1569 /**
1570  * Do Tarjan's SCC algorithm and drive load/store optimization.
1571  *
1572  * @param irn  start at this node
1573  * @param env  the loop environment
1574  */
1575 static void dfs(ir_node *irn, loop_env *env)
1576 {
1577         int i, n;
1578         node_entry *node = get_irn_ne(irn, env);
1579
1580         mark_irn_visited(irn);
1581
1582         node->DFSnum = env->nextDFSnum++;
1583         node->low    = node->DFSnum;
1584         push(env, irn);
1585
1586         /* handle preds */
1587         if (is_Phi(irn) || is_Sync(irn)) {
1588                 n = get_irn_arity(irn);
1589                 for (i = 0; i < n; ++i) {
1590                         ir_node *pred = get_irn_n(irn, i);
1591                         node_entry *o = get_irn_ne(pred, env);
1592
1593                         if (irn_not_visited(pred)) {
1594                                 dfs(pred, env);
1595                                 node->low = MIN(node->low, o->low);
1596                         }
1597                         if (o->DFSnum < node->DFSnum && o->in_stack)
1598                                 node->low = MIN(o->DFSnum, node->low);
1599                 }
1600         } else if (is_fragile_op(irn)) {
1601                 ir_node *pred = get_fragile_op_mem(irn);
1602                 node_entry *o = get_irn_ne(pred, env);
1603
1604                 if (irn_not_visited(pred)) {
1605                         dfs(pred, env);
1606                         node->low = MIN(node->low, o->low);
1607                 }
1608                 if (o->DFSnum < node->DFSnum && o->in_stack)
1609                         node->low = MIN(o->DFSnum, node->low);
1610         } else if (is_Proj(irn)) {
1611                 ir_node *pred = get_Proj_pred(irn);
1612                 node_entry *o = get_irn_ne(pred, env);
1613
1614                 if (irn_not_visited(pred)) {
1615                         dfs(pred, env);
1616                         node->low = MIN(node->low, o->low);
1617                 }
1618                 if (o->DFSnum < node->DFSnum && o->in_stack)
1619                         node->low = MIN(o->DFSnum, node->low);
1620         }
1621         else {
1622                  /* IGNORE predecessors */
1623         }
1624
1625         if (node->low == node->DFSnum) {
1626                 scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1627                 ir_node *x;
1628
1629                 pscc->head = NULL;
1630                 do {
1631                         node_entry *e;
1632
1633                         x = pop(env);
1634                         e = get_irn_ne(x, env);
1635                         e->pscc    = pscc;
1636                         e->next    = pscc->head;
1637                         pscc->head = x;
1638                 } while (x != irn);
1639
1640                 process_scc(pscc, env);
1641         }
1642 }  /* dfs */
1643
1644 /**
1645  * Do the DFS on the memory edges a graph.
1646  *
1647  * @param irg  the graph to process
1648  * @param env  the loop environment
1649  */
1650 static void do_dfs(ir_graph *irg, loop_env *env) {
1651         ir_graph *rem = current_ir_graph;
1652         ir_node  *endblk, *end;
1653         int      i;
1654
1655         current_ir_graph = irg;
1656         inc_irg_visited(irg);
1657
1658         /* visit all memory nodes */
1659         endblk = get_irg_end_block(irg);
1660         for (i = get_Block_n_cfgpreds(endblk) - 1; i >= 0; --i) {
1661                 ir_node *pred = get_Block_cfgpred(endblk, i);
1662
1663                 if (is_Return(pred))
1664                         dfs(get_Return_mem(pred), env);
1665                 else if (is_Raise(pred))
1666                         dfs(get_Raise_mem(pred), env);
1667                 else if (is_fragile_op(pred))
1668                         dfs(get_fragile_op_mem(pred), env);
1669                 else {
1670                         assert(0 && "Unknown EndBlock predecessor");
1671                 }
1672         }
1673
1674         /* visit the keep-alives */
1675         end = get_irg_end(irg);
1676         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
1677                 ir_node *ka = get_End_keepalive(end, i);
1678
1679                 if (is_Phi(ka) && irn_not_visited(ka))
1680                         dfs(ka, env);
1681         }
1682         current_ir_graph = rem;
1683 }  /* do_dfs */
1684
1685 /**
1686  * Initialize new phase data. We do this always explicit, so return NULL here
1687  */
1688 static void *init_loop_data(ir_phase *ph, ir_node *irn, void *data) {
1689         (void)ph;
1690         (void)irn;
1691         (void)data;
1692         return NULL;
1693 }  /* init_loop_data */
1694
1695 /**
1696  * Optimize Loads/Stores in loops.
1697  *
1698  * @param irg  the graph
1699  */
1700 static int optimize_loops(ir_graph *irg) {
1701         loop_env env;
1702
1703         env.stack         = NEW_ARR_F(ir_node *, 128);
1704         env.tos           = 0;
1705         env.nextDFSnum    = 0;
1706         env.POnum         = 0;
1707         env.changes       = 0;
1708         phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
1709
1710         /* calculate the SCC's and drive loop optimization. */
1711         do_dfs(irg, &env);
1712
1713         DEL_ARR_F(env.stack);
1714         phase_free(&env.ph);
1715
1716         return env.changes;
1717 }  /* optimize_loops */
1718
1719 /*
1720  * do the load store optimization
1721  */
1722 void optimize_load_store(ir_graph *irg) {
1723         walk_env_t env;
1724
1725         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
1726
1727         assert(get_irg_phase_state(irg) != phase_building);
1728         assert(get_irg_pinned(irg) != op_pin_state_floats &&
1729                 "LoadStore optimization needs pinned graph");
1730
1731         if (! get_opt_redundant_loadstore())
1732                 return;
1733
1734         /* we need landing pads */
1735         remove_critical_cf_edges(irg);
1736
1737         edges_assure(irg);
1738
1739         /* for Phi optimization post-dominators are needed ... */
1740         assure_postdoms(irg);
1741
1742         if (get_opt_alias_analysis()) {
1743                 assure_irg_address_taken_computed(irg);
1744                 assure_irp_globals_address_taken_computed();
1745         }
1746
1747         obstack_init(&env.obst);
1748         env.changes = 0;
1749
1750         /* init the links, then collect Loads/Stores/Proj's in lists */
1751         master_visited = 0;
1752         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1753
1754         /* now we have collected enough information, optimize */
1755         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1756
1757         env.changes |= optimize_loops(irg);
1758
1759         obstack_free(&env.obst, NULL);
1760
1761         /* Handle graph state */
1762         if (env.changes) {
1763                 set_irg_outs_inconsistent(irg);
1764         }
1765
1766         if (env.changes & CF_CHANGED) {
1767                 /* is this really needed: Yes, control flow changed, block might
1768                 have Bad() predecessors. */
1769                 set_irg_doms_inconsistent(irg);
1770         }
1771 }  /* optimize_load_store */