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