00fa55049f0a6759a24dcbb7fc59083499fa7e15
[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(get_irn_op(index) == op_Const);
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                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
430                 exchange(load, new_Bad());
431                 reduce_adr_usage(ptr);
432         }
433 }  /* handle_load_update */
434
435 /**
436  * A Use of an address node is vanished. Check if this was a Proj
437  * node and update the counters.
438  */
439 static void reduce_adr_usage(ir_node *ptr) {
440         if (is_Proj(ptr)) {
441                 if (get_irn_n_edges(ptr) <= 0) {
442                         /* this Proj is dead now */
443                         ir_node *pred = get_Proj_pred(ptr);
444
445                         if (is_Load(pred)) {
446                                 ldst_info_t *info = get_irn_link(pred);
447                                 info->projs[get_Proj_proj(ptr)] = NULL;
448
449                                 /* this node lost it's result proj, handle that */
450                                 handle_load_update(pred);
451                         }
452                 }
453         }
454 }  /* reduce_adr_usage */
455
456 /**
457  * Check, if an already existing value of mode old_mode can be converted
458  * into the needed one new_mode without loss.
459  */
460 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
461         if (old_mode == new_mode)
462                 return 1;
463
464         /* if both modes are two-complement ones, we can always convert the
465            Stored value into the needed one. */
466         if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
467                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
468                   get_mode_arithmetic(new_mode) == irma_twos_complement)
469                 return 1;
470         return 0;
471 }  /* can_use_stored_value */
472
473 /**
474  * Follow the memory chain as long as there are only Loads
475  * and alias free Stores and try to replace current Load or Store
476  * by a previous ones.
477  * Note that in unreachable loops it might happen that we reach
478  * load again, as well as we can fall into a cycle.
479  * We break such cycles using a special visited flag.
480  *
481  * INC_MASTER() must be called before dive into
482  */
483 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
484         unsigned res = 0;
485         ldst_info_t *info = get_irn_link(load);
486         ir_node *pred;
487         ir_node *ptr       = get_Load_ptr(load);
488         ir_node *mem       = get_Load_mem(load);
489         ir_mode *load_mode = get_Load_mode(load);
490
491         for (pred = curr; load != pred; ) {
492                 ldst_info_t *pred_info = get_irn_link(pred);
493
494                 /*
495                  * BEWARE: one might think that checking the modes is useless, because
496                  * if the pointers are identical, they refer to the same object.
497                  * This is only true in strong typed languages, not in C were the following
498                  * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
499                  */
500                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
501                     can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
502                         /*
503                          * a Load immediately after a Store -- a read after write.
504                          * We may remove the Load, if both Load & Store does not have an exception handler
505                          * OR they are in the same MacroBlock. In the latter case the Load cannot
506                          * throw an exception when the previous Store was quiet.
507                          *
508                          * Why we need to check for Store Exception? If the Store cannot
509                          * be executed (ROM) the exception handler might simply jump into
510                          * the load MacroBlock :-(
511                          * We could make it a little bit better if we would know that the exception
512                          * handler of the Store jumps directly to the end...
513                          */
514                         if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
515                             get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
516                                 ir_node *value = get_Store_value(pred);
517
518                                 DBG_OPT_RAW(load, value);
519
520                                 /* add an convert if needed */
521                                 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
522                                         value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
523                                 }
524
525                                 if (info->projs[pn_Load_M])
526                                         exchange(info->projs[pn_Load_M], mem);
527
528                                 /* no exception */
529                                 if (info->projs[pn_Load_X_except]) {
530                                         exchange( info->projs[pn_Load_X_except], new_Bad());
531                                         res |= CF_CHANGED;
532                                 }
533                                 if (info->projs[pn_Load_X_regular]) {
534                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
535                                         res |= CF_CHANGED;
536                                 }
537
538                                 if (info->projs[pn_Load_res])
539                                         exchange(info->projs[pn_Load_res], value);
540
541                                 exchange(load, new_Bad());
542                                 reduce_adr_usage(ptr);
543                                 return res | DF_CHANGED;
544                         }
545                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
546                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
547                         /*
548                          * a Load after a Load -- a read after read.
549                          * We may remove the second Load, if it does not have an exception handler
550                          * OR they are in the same MacroBlock. In the later case the Load cannot
551                          * throw an exception when the previous Load was quiet.
552                          *
553                          * Here, there is no need to check if the previous Load has an exception
554                          * hander because they would have exact the same exception...
555                          */
556                         if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
557                                 ir_node *value;
558
559                                 DBG_OPT_RAR(load, pred);
560
561                                 /* the result is used */
562                                 if (info->projs[pn_Load_res]) {
563                                         if (pred_info->projs[pn_Load_res] == NULL) {
564                                                 /* create a new Proj again */
565                                                 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
566                                         }
567                                         value = pred_info->projs[pn_Load_res];
568
569                                         /* add an convert if needed */
570                                         if (get_Load_mode(pred) != load_mode) {
571                                                 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
572                                         }
573
574                                         exchange(info->projs[pn_Load_res], value);
575                                 }
576
577                                 if (info->projs[pn_Load_M])
578                                         exchange(info->projs[pn_Load_M], mem);
579
580                                 /* no exception */
581                                 if (info->projs[pn_Load_X_except]) {
582                                         exchange(info->projs[pn_Load_X_except], new_Bad());
583                                         res |= CF_CHANGED;
584                                 }
585                                 if (info->projs[pn_Load_X_regular]) {
586                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
587                                         res |= CF_CHANGED;
588                                 }
589
590                                 exchange(load, new_Bad());
591                                 reduce_adr_usage(ptr);
592                                 return res |= DF_CHANGED;
593                         }
594                 }
595
596                 if (is_Store(pred)) {
597                         /* check if we can pass through this store */
598                         ir_alias_relation rel = get_alias_relation(
599                                 current_ir_graph,
600                                 get_Store_ptr(pred),
601                                 get_irn_mode(get_Store_value(pred)),
602                                 ptr, load_mode);
603                         /* if the might be an alias, we cannot pass this Store */
604                         if (rel != no_alias)
605                                 break;
606                         pred = skip_Proj(get_Store_mem(pred));
607                 } else if (get_irn_op(pred) == op_Load) {
608                         pred = skip_Proj(get_Load_mem(pred));
609                 } else {
610                         /* follow only Load chains */
611                         break;
612                 }
613
614                 /* check for cycles */
615                 if (NODE_VISITED(pred_info))
616                         break;
617                 MARK_NODE(pred_info);
618         }
619
620         if (is_Sync(pred)) {
621                 int i;
622
623                 /* handle all Sync predecessors */
624                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
625                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
626                         if (res)
627                                 break;
628                 }
629         }
630
631         return res;
632 }  /* follow_Mem_chain */
633
634 /**
635  * optimize a Load
636  *
637  * @param load  the Load node
638  */
639 static unsigned optimize_load(ir_node *load)
640 {
641         ldst_info_t *info = get_irn_link(load);
642         ir_node *mem, *ptr, *new_node;
643         ir_entity *ent;
644         unsigned res = 0;
645
646         /* do NOT touch volatile loads for now */
647         if (get_Load_volatility(load) == volatility_is_volatile)
648                 return 0;
649
650         /* the address of the load to be optimized */
651         ptr = get_Load_ptr(load);
652
653         /*
654          * Check if we can remove the exception from a Load:
655          * This can be done, if the address is from an Sel(Alloc) and
656          * the Sel type is a subtype of the allocated type.
657          *
658          * This optimizes some often used OO constructs,
659          * like x = new O; x->t;
660          */
661         if (info->projs[pn_Load_X_except]) {
662                 if (is_Sel(ptr)) {
663                         ir_node *mem = get_Sel_mem(ptr);
664
665                         /* FIXME: works with the current FE, but better use the base */
666                         if (is_Alloc(skip_Proj(mem))) {
667                                 /* ok, check the types */
668                                 ir_entity *ent    = get_Sel_entity(ptr);
669                                 ir_type   *s_type = get_entity_type(ent);
670                                 ir_type   *a_type = get_Alloc_type(mem);
671
672                                 if (is_SubClass_of(s_type, a_type)) {
673                                         /* ok, condition met: there can't be an exception because
674                                         * Alloc guarantees that enough memory was allocated */
675
676                                         exchange(info->projs[pn_Load_X_except], new_Bad());
677                                         info->projs[pn_Load_X_except] = NULL;
678                                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
679                                         info->projs[pn_Load_X_regular] = NULL;
680                                         res |= CF_CHANGED;
681                                 }
682                         }
683                 } else if (is_Alloc(skip_Proj(skip_Cast(ptr)))) {
684                                 /* simple case: a direct load after an Alloc. Firm Alloc throw
685                                  * an exception in case of out-of-memory. So, there is no way for an
686                                  * exception in this load.
687                                  * This code is constructed by the "exception lowering" in the Jack compiler.
688                                  */
689                                 exchange(info->projs[pn_Load_X_except], new_Bad());
690                                 info->projs[pn_Load_X_except] = NULL;
691                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
692                                 info->projs[pn_Load_X_regular] = NULL;
693                                 res |= CF_CHANGED;
694                 }
695         }
696
697         /* The mem of the Load. Must still be returned after optimization. */
698         mem  = get_Load_mem(load);
699
700         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
701                 /* a Load which value is neither used nor exception checked, remove it */
702                 exchange(info->projs[pn_Load_M], mem);
703
704                 if (info->projs[pn_Load_X_regular]) {
705                         /* should not happen, but if it does, remove it */
706                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
707                         res |= CF_CHANGED;
708                 }
709                 exchange(load, new_Bad());
710                 reduce_adr_usage(ptr);
711                 return res | DF_CHANGED;
712         }
713
714         /* Load from a constant polymorphic field, where we can resolve
715            polymorphism. */
716         new_node = transform_node_Load(load);
717         if (new_node != load) {
718                 if (info->projs[pn_Load_M]) {
719                         exchange(info->projs[pn_Load_M], mem);
720                         info->projs[pn_Load_M] = NULL;
721                 }
722                 if (info->projs[pn_Load_X_except]) {
723                         exchange(info->projs[pn_Load_X_except], new_Bad());
724                         info->projs[pn_Load_X_except] = NULL;
725                         res |= CF_CHANGED;
726                 }
727                 if (info->projs[pn_Load_X_regular]) {
728                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
729                         info->projs[pn_Load_X_regular] = NULL;
730                         res |= CF_CHANGED;
731                 }
732                 if (info->projs[pn_Load_res])
733                         exchange(info->projs[pn_Load_res], new_node);
734
735                 exchange(load, new_Bad());
736                 reduce_adr_usage(ptr);
737                 return res | DF_CHANGED;
738         }
739
740         /* check if we can determine the entity that will be loaded */
741         ent = find_constant_entity(ptr);
742         if (ent) {
743                 if ((allocation_static == get_entity_allocation(ent)) &&
744                         (visibility_external_allocated != get_entity_visibility(ent))) {
745                         /* a static allocation that is not external: there should be NO exception
746                          * when loading. */
747
748                         /* no exception, clear the info field as it might be checked later again */
749                         if (info->projs[pn_Load_X_except]) {
750                                 exchange(info->projs[pn_Load_X_except], new_Bad());
751                                 info->projs[pn_Load_X_except] = NULL;
752                                 res |= CF_CHANGED;
753                         }
754                         if (info->projs[pn_Load_X_regular]) {
755                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
756                                 info->projs[pn_Load_X_regular] = NULL;
757                                 res |= CF_CHANGED;
758                         }
759
760                         if (variability_constant == get_entity_variability(ent)
761                                 && is_atomic_entity(ent)) {
762                                 /* Might not be atomic after
763                                    lowering of Sels.  In this
764                                    case we could also load, but
765                                    it's more complicated. */
766                                 /* more simpler case: we load the content of a constant value:
767                                  * replace it by the constant itself
768                                  */
769
770                                 /* no memory */
771                                 if (info->projs[pn_Load_M]) {
772                                         exchange(info->projs[pn_Load_M], mem);
773                                         res |= DF_CHANGED;
774                                 }
775                                 /* no result :-) */
776                                 if (info->projs[pn_Load_res]) {
777                                         if (is_atomic_entity(ent)) {
778                                                 ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
779
780                                                 DBG_OPT_RC(load, c);
781                                                 exchange(info->projs[pn_Load_res], c);
782                                                 res |= DF_CHANGED;
783                                         }
784                                 }
785                                 exchange(load, new_Bad());
786                                 reduce_adr_usage(ptr);
787                                 return res;
788                         } else if (variability_constant == get_entity_variability(ent)) {
789                                 compound_graph_path *path = get_accessed_path(ptr);
790
791                                 if (path) {
792                                         ir_node *c;
793
794                                         assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
795                                         /*
796                                         {
797                                                 int j;
798                                                 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
799                                                         ir_entity *node = get_compound_graph_path_node(path, j);
800                                                         fprintf(stdout, ".%s", get_entity_name(node));
801                                                         if (is_Array_type(get_entity_owner(node)))
802                                                                 fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
803                                                 }
804                                                 printf("\n");
805                                         }
806                                         */
807
808                                         c = get_compound_ent_value_by_path(ent, path);
809                                         free_compound_graph_path(path);
810
811                                         /* printf("  cons: "); DDMN(c); */
812
813                                         if (info->projs[pn_Load_M]) {
814                                                 exchange(info->projs[pn_Load_M], mem);
815                                                 res |= DF_CHANGED;
816                                         }
817                                         if (info->projs[pn_Load_res]) {
818                                                 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
819                                                 res |= DF_CHANGED;
820                                         }
821                                         exchange(load, new_Bad());
822                                         reduce_adr_usage(ptr);
823                                         return res;
824                                 } else {
825                                         /*  We can not determine a correct access path.  E.g., in jack, we load
826                                         a byte from an object to generate an exception.   Happens in test program
827                                         Reflectiontest.
828                                         printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
829                                         get_entity_name(get_irg_entity(current_ir_graph)));
830                                         printf("  load: "); DDMN(load);
831                                         printf("  ptr:  "); DDMN(ptr);
832                                         */
833                                 }
834                         }
835                 }
836         }
837
838         /* Check, if the address of this load is used more than once.
839          * If not, this load cannot be removed in any case. */
840         if (get_irn_n_uses(ptr) <= 1)
841                 return res;
842
843         /*
844          * follow the memory chain as long as there are only Loads
845          * and try to replace current Load or Store by a previous one.
846          * Note that in unreachable loops it might happen that we reach
847          * load again, as well as we can fall into a cycle.
848          * We break such cycles using a special visited flag.
849          */
850         INC_MASTER();
851         res = follow_Mem_chain(load, skip_Proj(mem));
852         return res;
853 }  /* optimize_load */
854
855 /**
856  * Check whether a value of mode new_mode would completely overwrite a value
857  * of mode old_mode in memory.
858  */
859 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
860 {
861         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
862 }  /* is_completely_overwritten */
863
864 /**
865  * follow the memory chain as long as there are only Loads and alias free Stores.
866  *
867  * INC_MASTER() must be called before dive into
868  */
869 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
870         unsigned res = 0;
871         ldst_info_t *info = get_irn_link(store);
872         ir_node *pred;
873         ir_node *ptr = get_Store_ptr(store);
874         ir_node *mem = get_Store_mem(store);
875         ir_node *value = get_Store_value(store);
876         ir_mode *mode  = get_irn_mode(value);
877         ir_node *block = get_nodes_block(store);
878         ir_node *mblk  = get_Block_MacroBlock(block);
879
880         for (pred = curr; pred != store;) {
881                 ldst_info_t *pred_info = get_irn_link(pred);
882
883                 /*
884                  * BEWARE: one might think that checking the modes is useless, because
885                  * if the pointers are identical, they refer to the same object.
886                  * This is only true in strong typed languages, not is C were the following
887                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
888                  * However, if the mode that is written have a bigger  or equal size the the old
889                  * one, the old value is completely overwritten and can be killed ...
890                  */
891                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
892                     get_nodes_MacroBlock(pred) == mblk &&
893                     is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
894                         /*
895                          * a Store after a Store in the same block -- a write after write.
896                          * We may remove the first Store, if it does not have an exception handler.
897                          *
898                          * TODO: What, if both have the same exception handler ???
899                          */
900                         if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
901                                 DBG_OPT_WAW(pred, store);
902                                 exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
903                                 exchange(pred, new_Bad());
904                                 reduce_adr_usage(ptr);
905                                 return DF_CHANGED;
906                         }
907                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
908                            value == pred_info->projs[pn_Load_res]) {
909                         /*
910                          * a Store of a value after a Load -- a write after read.
911                          * We may remove the second Store, if it does not have an exception handler.
912                          */
913                         if (! info->projs[pn_Store_X_except]) {
914                                 DBG_OPT_WAR(store, pred);
915                                 exchange(info->projs[pn_Store_M], mem);
916                                 exchange(store, new_Bad());
917                                 reduce_adr_usage(ptr);
918                                 return DF_CHANGED;
919                         }
920                 }
921
922                 if (is_Store(pred)) {
923                         /* check if we can pass thru this store */
924                         ir_alias_relation rel = get_alias_relation(
925                                 current_ir_graph,
926                                 get_Store_ptr(pred),
927                                 get_irn_mode(get_Store_value(pred)),
928                                 ptr, mode);
929                         /* if the might be an alias, we cannot pass this Store */
930                         if (rel != no_alias)
931                                 break;
932                         pred = skip_Proj(get_Store_mem(pred));
933                 } else if (get_irn_op(pred) == op_Load) {
934                         pred = skip_Proj(get_Load_mem(pred));
935                 } else {
936                         /* follow only Load chains */
937                         break;
938                 }
939
940                 /* check for cycles */
941                 if (NODE_VISITED(pred_info))
942                         break;
943                 MARK_NODE(pred_info);
944         }
945
946         if (is_Sync(pred)) {
947                 int i;
948
949                 /* handle all Sync predecessors */
950                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
951                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
952                         if (res)
953                                 break;
954                 }
955         }
956         return res;
957 }  /* follow_Mem_chain_for_Store */
958
959 /**
960  * optimize a Store
961  *
962  * @param store  the Store node
963  */
964 static unsigned optimize_store(ir_node *store) {
965         ir_node *ptr, *mem;
966
967         if (get_Store_volatility(store) == volatility_is_volatile)
968                 return 0;
969
970         ptr = get_Store_ptr(store);
971
972         /* Check, if the address of this Store is used more than once.
973          * If not, this Store cannot be removed in any case. */
974         if (get_irn_n_uses(ptr) <= 1)
975                 return 0;
976
977         mem = get_Store_mem(store);
978
979         /* follow the memory chain as long as there are only Loads */
980         INC_MASTER();
981         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
982 }  /* optimize_store */
983
984 /**
985  * walker, optimizes Phi after Stores to identical places:
986  * Does the following optimization:
987  * @verbatim
988  *
989  *   val1   val2   val3          val1  val2  val3
990  *    |      |      |               \    |    /
991  *  Store  Store  Store              \   |   /
992  *      \    |    /                   PhiData
993  *       \   |   /                       |
994  *        \  |  /                      Store
995  *          PhiM
996  *
997  * @endverbatim
998  * This reduces the number of stores and allows for predicated execution.
999  * Moves Stores back to the end of a function which may be bad.
1000  *
1001  * This is only possible if the predecessor blocks have only one successor.
1002  */
1003 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1004 {
1005         int i, n;
1006         ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1007         ir_mode *mode;
1008         ir_node **inM, **inD, **projMs;
1009         int *idx;
1010         dbg_info *db = NULL;
1011         ldst_info_t *info;
1012         block_info_t *bl_info;
1013         unsigned res = 0;
1014
1015         /* Must be a memory Phi */
1016         if (get_irn_mode(phi) != mode_M)
1017                 return 0;
1018
1019         n = get_Phi_n_preds(phi);
1020         if (n <= 0)
1021                 return 0;
1022
1023         /* must be only one user */
1024         projM = get_Phi_pred(phi, 0);
1025         if (get_irn_n_edges(projM) != 1)
1026                 return 0;
1027
1028         store = skip_Proj(projM);
1029         old_store = store;
1030         if (get_irn_op(store) != op_Store)
1031                 return 0;
1032
1033         block = get_nodes_block(store);
1034
1035         /* abort on dead blocks */
1036         if (is_Block_dead(block))
1037                 return 0;
1038
1039         /* check if the block is post dominated by Phi-block
1040            and has no exception exit */
1041         bl_info = get_irn_link(block);
1042         if (bl_info->flags & BLOCK_HAS_EXC)
1043                 return 0;
1044
1045         phi_block = get_nodes_block(phi);
1046         if (! block_strictly_postdominates(phi_block, block))
1047                 return 0;
1048
1049         /* this is the address of the store */
1050         ptr  = get_Store_ptr(store);
1051         mode = get_irn_mode(get_Store_value(store));
1052         info = get_irn_link(store);
1053         exc  = info->exc_block;
1054
1055         for (i = 1; i < n; ++i) {
1056                 ir_node *pred = get_Phi_pred(phi, i);
1057
1058                 if (get_irn_n_edges(pred) != 1)
1059                         return 0;
1060
1061                 pred = skip_Proj(pred);
1062                 if (!is_Store(pred))
1063                         return 0;
1064
1065                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1066                         return 0;
1067
1068                 info = get_irn_link(pred);
1069
1070                 /* check, if all stores have the same exception flow */
1071                 if (exc != info->exc_block)
1072                         return 0;
1073
1074                 /* abort on dead blocks */
1075                 block = get_nodes_block(pred);
1076                 if (is_Block_dead(block))
1077                         return 0;
1078
1079                 /* check if the block is post dominated by Phi-block
1080                    and has no exception exit. Note that block must be different from
1081                    Phi-block, else we would move a Store from end End of a block to its
1082                    Start... */
1083                 bl_info = get_irn_link(block);
1084                 if (bl_info->flags & BLOCK_HAS_EXC)
1085                         return 0;
1086                 if (block == phi_block || ! block_postdominates(phi_block, block))
1087                         return 0;
1088         }
1089
1090         /*
1091          * ok, when we are here, we found all predecessors of a Phi that
1092          * are Stores to the same address and size. That means whatever
1093          * we do before we enter the block of the Phi, we do a Store.
1094          * So, we can move the Store to the current block:
1095          *
1096          *   val1    val2    val3          val1  val2  val3
1097          *    |       |       |               \    |    /
1098          * | Str | | Str | | Str |             \   |   /
1099          *      \     |     /                   PhiData
1100          *       \    |    /                       |
1101          *        \   |   /                       Str
1102          *           PhiM
1103          *
1104          * Is only allowed if the predecessor blocks have only one successor.
1105          */
1106
1107         NEW_ARR_A(ir_node *, projMs, n);
1108         NEW_ARR_A(ir_node *, inM, n);
1109         NEW_ARR_A(ir_node *, inD, n);
1110         NEW_ARR_A(int, idx, n);
1111
1112         /* Prepare: Collect all Store nodes.  We must do this
1113            first because we otherwise may loose a store when exchanging its
1114            memory Proj.
1115          */
1116         for (i = n - 1; i >= 0; --i) {
1117                 ir_node *store;
1118
1119                 projMs[i] = get_Phi_pred(phi, i);
1120                 assert(is_Proj(projMs[i]));
1121
1122                 store = get_Proj_pred(projMs[i]);
1123                 info  = get_irn_link(store);
1124
1125                 inM[i] = get_Store_mem(store);
1126                 inD[i] = get_Store_value(store);
1127                 idx[i] = info->exc_idx;
1128         }
1129         block = get_nodes_block(phi);
1130
1131         /* second step: create a new memory Phi */
1132         phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1133
1134         /* third step: create a new data Phi */
1135         phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1136
1137         /* rewire memory and kill the node */
1138         for (i = n - 1; i >= 0; --i) {
1139                 ir_node *proj  = projMs[i];
1140
1141                 if(is_Proj(proj)) {
1142                         ir_node *store = get_Proj_pred(proj);
1143                         exchange(proj, inM[i]);
1144                         kill_node(store);
1145                 }
1146         }
1147
1148         /* fourth step: create the Store */
1149         store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1150 #ifdef DO_CACHEOPT
1151         co_set_irn_name(store, co_get_irn_ident(old_store));
1152 #endif
1153
1154         projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1155
1156         info = get_ldst_info(store, &wenv->obst);
1157         info->projs[pn_Store_M] = projM;
1158
1159         /* fifths step: repair exception flow */
1160         if (exc) {
1161                 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1162
1163                 info->projs[pn_Store_X_except] = projX;
1164                 info->exc_block                = exc;
1165                 info->exc_idx                  = idx[0];
1166
1167                 for (i = 0; i < n; ++i) {
1168                         set_Block_cfgpred(exc, idx[i], projX);
1169                 }
1170
1171                 if (n > 1) {
1172                         /* the exception block should be optimized as some inputs are identical now */
1173                 }
1174
1175                 res |= CF_CHANGED;
1176         }
1177
1178         /* sixth step: replace old Phi */
1179         exchange(phi, projM);
1180
1181         return res | DF_CHANGED;
1182 }  /* optimize_phi */
1183
1184 /**
1185  * walker, do the optimizations
1186  */
1187 static void do_load_store_optimize(ir_node *n, void *env) {
1188         walk_env_t *wenv = env;
1189
1190         switch (get_irn_opcode(n)) {
1191
1192         case iro_Load:
1193                 wenv->changes |= optimize_load(n);
1194                 break;
1195
1196         case iro_Store:
1197                 wenv->changes |= optimize_store(n);
1198                 break;
1199
1200         case iro_Phi:
1201                 wenv->changes |= optimize_phi(n, wenv);
1202
1203         default:
1204                 ;
1205         }
1206 }  /* do_load_store_optimize */
1207
1208 /** A scc. */
1209 typedef struct scc {
1210         ir_node *head;          /**< the head of the list */
1211 } scc;
1212
1213 /** A node entry. */
1214 typedef struct node_entry {
1215         unsigned DFSnum;    /**< the DFS number of this node */
1216         unsigned low;       /**< the low number of this node */
1217         ir_node  *header;   /**< the header of this node */
1218         int      in_stack;  /**< flag, set if the node is on the stack */
1219         ir_node  *next;     /**< link to the next node the the same scc */
1220         scc      *pscc;     /**< the scc of this node */
1221         unsigned POnum;     /**< the post order number for blocks */
1222 } node_entry;
1223
1224 /** A loop entry. */
1225 typedef struct loop_env {
1226         ir_phase ph;           /**< the phase object */
1227         ir_node  **stack;      /**< the node stack */
1228         int      tos;          /**< tos index */
1229         unsigned nextDFSnum;   /**< the current DFS number */
1230         unsigned POnum;        /**< current post order number */
1231
1232         unsigned changes;      /**< a bitmask of graph changes */
1233 } loop_env;
1234
1235 /**
1236 * Gets the node_entry of a node
1237 */
1238 static node_entry *get_irn_ne(ir_node *irn, loop_env *env) {
1239         ir_phase   *ph = &env->ph;
1240         node_entry *e  = phase_get_irn_data(&env->ph, irn);
1241
1242         if (! e) {
1243                 e = phase_alloc(ph, sizeof(*e));
1244                 memset(e, 0, sizeof(*e));
1245                 phase_set_irn_data(ph, irn, e);
1246         }
1247         return e;
1248 }  /* get_irn_ne */
1249
1250 /**
1251  * Push a node onto the stack.
1252  *
1253  * @param env   the loop environment
1254  * @param n     the node to push
1255  */
1256 static void push(loop_env *env, ir_node *n) {
1257         node_entry *e;
1258
1259         if (env->tos == ARR_LEN(env->stack)) {
1260                 int nlen = ARR_LEN(env->stack) * 2;
1261                 ARR_RESIZE(ir_node *, env->stack, nlen);
1262         }
1263         env->stack[env->tos++] = n;
1264         e = get_irn_ne(n, env);
1265         e->in_stack = 1;
1266 }  /* push */
1267
1268 /**
1269  * pop a node from the stack
1270  *
1271  * @param env   the loop environment
1272  *
1273  * @return  The topmost node
1274  */
1275 static ir_node *pop(loop_env *env) {
1276         ir_node *n = env->stack[--env->tos];
1277         node_entry *e = get_irn_ne(n, env);
1278
1279         e->in_stack = 0;
1280         return n;
1281 }  /* pop */
1282
1283 /**
1284  * Check if irn is a region constant.
1285  * The block or irn must strictly dominate the header block.
1286  *
1287  * @param irn           the node to check
1288  * @param header_block  the header block of the induction variable
1289  */
1290 static int is_rc(ir_node *irn, ir_node *header_block) {
1291         ir_node *block = get_nodes_block(irn);
1292
1293         return (block != header_block) && block_dominates(block, header_block);
1294 }  /* is_rc */
1295
1296 typedef struct phi_entry phi_entry;
1297 struct phi_entry {
1298         ir_node   *phi;    /**< A phi with a region const memory. */
1299         int       pos;     /**< The position of the region const memory */
1300         ir_node   *load;   /**< the newly created load for this phi */
1301         phi_entry *next;
1302 };
1303
1304 /**
1305  * Move loops out of loops if possible
1306  */
1307 static void move_loads_in_loops(scc *pscc, loop_env *env) {
1308         ir_node   *phi, *load, *next, *other, *next_other;
1309         ir_entity *ent;
1310         int       j;
1311         phi_entry *phi_list = NULL;
1312
1313         /* collect all outer memories */
1314         for (phi = pscc->head; phi != NULL; phi = next) {
1315                 node_entry *ne = get_irn_ne(phi, env);
1316                 next = ne->next;
1317
1318                 /* check all memory Phi's */
1319                 if (! is_Phi(phi) || get_irn_mode(phi) != mode_M)
1320                         continue;
1321
1322                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1323                         ir_node    *pred = get_irn_n(phi, j);
1324                         node_entry *pe   = get_irn_ne(pred, env);
1325
1326                         if (pe->pscc != ne->pscc) {
1327                                 /* not in the same SCC, is region const */
1328                                 phi_entry *pe = phase_alloc(&env->ph, sizeof(*pe));
1329
1330                                 pe->phi  = phi;
1331                                 pe->pos  = j;
1332                                 pe->next = phi_list;
1333                                 phi_list = pe;
1334                         }
1335                 }
1336         }
1337         /* no Phis no fun */
1338         if (phi_list == NULL)
1339                 return;
1340
1341         for (load = pscc->head; load; load = next) {
1342                 ir_mode *load_mode;
1343                 node_entry *ne = get_irn_ne(load, env);
1344                 next = ne->next;
1345
1346                 if (is_Load(load)) {
1347                         ldst_info_t *info = get_irn_link(load);
1348                         ir_node     *ptr = get_Load_ptr(load);
1349
1350                         /* for now, we cannot handle Loads with exceptions */
1351                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1352                                 continue;
1353
1354                         /* for now, we can only handle Load(SymConst) */
1355                         if (! is_SymConst(ptr) || get_SymConst_kind(ptr) != symconst_addr_ent)
1356                                 continue;
1357                         ent = get_SymConst_entity(ptr);
1358
1359                         load_mode = get_Load_mode(load);
1360                         if (get_entity_address_taken(ent) == ir_address_not_taken) {
1361                                 /* Shortcut: If the addres is never taken, this address if complete alias free*/
1362                                 goto can_move;
1363                         }
1364
1365                         for (other = pscc->head; other != NULL; other = next_other) {
1366                                 node_entry *ne = get_irn_ne(other, env);
1367                                 next_other = ne->next;
1368
1369                                 if (is_Store(other)) {
1370                                         ir_alias_relation rel = get_alias_relation(
1371                                                 current_ir_graph,
1372                                                 get_Store_ptr(other),
1373                                                 get_irn_mode(get_Store_value(other)),
1374                                                 ptr, load_mode);
1375                                         /* if the might be an alias, we cannot pass this Store */
1376                                         if (rel != no_alias)
1377                                                 break;
1378                                 }
1379                         }
1380                         if (other == NULL) {
1381                                 ldst_info_t *ninfo;
1382                                 phi_entry   *pe;
1383                                 dbg_info    *db;
1384 can_move:
1385                                 /* for now, we cannot handle more than one input */
1386                                 if (phi_list->next != NULL)
1387                                         return;
1388
1389                                 /* yep, no aliasing Store found, Load can be moved */
1390                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1391
1392                                 db   = get_irn_dbg_info(load);
1393                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1394                                         int     pos   = pe->pos;
1395                                         ir_node *phi  = pe->phi;
1396                                         ir_node *blk  = get_nodes_block(phi);
1397                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1398                                         ir_node *irn, *mem;
1399
1400                                         pe->load = irn = new_rd_Load(db, current_ir_graph, pred, get_Phi_pred(phi, pos), ptr, load_mode);
1401                                         ninfo = get_ldst_info(pred, phase_obst(&env->ph));
1402
1403                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(current_ir_graph, pred, irn, mode_M, pn_Load_M);
1404                                         set_Phi_pred(phi, pos, mem);
1405
1406                                         ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1407
1408                                         DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1409                                 }
1410
1411                                 /* now kill the old Load */
1412                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1413                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1414
1415                                 env->changes |= DF_CHANGED;
1416                         }
1417                 }
1418         }
1419 }  /* move_loads_in_loops */
1420
1421 /**
1422  * Process a loop SCC.
1423  *
1424  * @param pscc  the SCC
1425  * @param env   the loop environment
1426  */
1427 static void process_loop(scc *pscc, loop_env *env) {
1428         ir_node *irn, *next, *header = NULL;
1429         node_entry *b, *h = NULL;
1430         int j, only_phi, num_outside, process = 0;
1431         ir_node *out_rc;
1432
1433         /* find the header block for this scc */
1434         for (irn = pscc->head; irn; irn = next) {
1435                 node_entry *e = get_irn_ne(irn, env);
1436                 ir_node *block = get_nodes_block(irn);
1437
1438                 next = e->next;
1439                 b = get_irn_ne(block, env);
1440
1441                 if (header) {
1442                         if (h->POnum < b->POnum) {
1443                                 header = block;
1444                                 h      = b;
1445                         }
1446                 }
1447                 else {
1448                         header = block;
1449                         h      = b;
1450                 }
1451         }
1452
1453         /* check if this scc contains only Phi, Loads or Stores nodes */
1454         only_phi    = 1;
1455         num_outside = 0;
1456         out_rc      = NULL;
1457         for (irn = pscc->head; irn; irn = next) {
1458                 node_entry *e = get_irn_ne(irn, env);
1459
1460                 next = e->next;
1461                 switch (get_irn_opcode(irn)) {
1462                 case iro_Call:
1463                 case iro_CopyB:
1464                         /* cannot handle Calls or CopyB yet */
1465                         goto fail;
1466                 case iro_Load:
1467                         process = 1;
1468                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1469                                 /* cannot handle loops with volatile Loads */
1470                                 goto fail;
1471                         }
1472                         only_phi = 0;
1473                         break;
1474                 case iro_Store:
1475                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1476                                 /* cannot handle loops with volatile Stores */
1477                                 goto fail;
1478                         }
1479                         only_phi = 0;
1480                         break;
1481                 default:
1482                         only_phi = 0;
1483                         break;
1484                 case iro_Phi:
1485                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1486                                 ir_node *pred  = get_irn_n(irn, j);
1487                                 node_entry *pe = get_irn_ne(pred, env);
1488
1489                                 if (pe->pscc != e->pscc) {
1490                                         /* not in the same SCC, must be a region const */
1491                                         if (! is_rc(pred, header)) {
1492                                                 /* not a memory loop */
1493                                                 goto fail;
1494                                         }
1495                                         if (! out_rc) {
1496                                                 out_rc = pred;
1497                                                 ++num_outside;
1498                                         } else if (out_rc != pred) {
1499                                                 ++num_outside;
1500                                         }
1501                                 }
1502                         }
1503                         break;
1504                 }
1505         }
1506         if (! process)
1507                 goto fail;
1508
1509         /* found a memory loop */
1510         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1511         if (only_phi && num_outside == 1) {
1512                 /* a phi cycle with only one real predecessor can be collapsed */
1513                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1514
1515                 for (irn = pscc->head; irn; irn = next) {
1516                         node_entry *e = get_irn_ne(irn, env);
1517                         next = e->next;
1518                         e->header = NULL;
1519                         exchange(irn, out_rc);
1520                 }
1521                 env->changes |= DF_CHANGED;
1522                 return;
1523         }
1524
1525         /* set the header for every node in this scc */
1526         for (irn = pscc->head; irn; irn = next) {
1527                 node_entry *e = get_irn_ne(irn, env);
1528                 e->header = header;
1529                 next = e->next;
1530                 DB((dbg, LEVEL_2, " %+F,", irn));
1531         }
1532         DB((dbg, LEVEL_2, "\n"));
1533
1534         move_loads_in_loops(pscc, env);
1535
1536 fail:
1537         ;
1538 }  /* process_loop */
1539
1540 /**
1541  * Process a SCC.
1542  *
1543  * @param pscc  the SCC
1544  * @param env   the loop environment
1545  */
1546 static void process_scc(scc *pscc, loop_env *env) {
1547         ir_node *head = pscc->head;
1548         node_entry *e = get_irn_ne(head, env);
1549
1550 #ifdef DEBUG_libfirm
1551         {
1552                 ir_node *irn, *next;
1553
1554                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1555                 for (irn = pscc->head; irn; irn = next) {
1556                         node_entry *e = get_irn_ne(irn, env);
1557
1558                         next = e->next;
1559
1560                         DB((dbg, LEVEL_4, " %+F,", irn));
1561                 }
1562                 DB((dbg, LEVEL_4, "\n"));
1563         }
1564 #endif
1565
1566         if (e->next != NULL) {
1567                 /* this SCC has more than one member */
1568                 process_loop(pscc, env);
1569         }
1570 }  /* process_scc */
1571 /**
1572  * Do Tarjan's SCC algorithm and drive load/store optimization.
1573  *
1574  * @param irn  start at this node
1575  * @param env  the loop environment
1576  */
1577 static void dfs(ir_node *irn, loop_env *env)
1578 {
1579         int i, n;
1580         node_entry *node = get_irn_ne(irn, env);
1581
1582         mark_irn_visited(irn);
1583
1584         /* do not put blocks into the scc */
1585         if (is_Block(irn)) {
1586                 n = get_irn_arity(irn);
1587                 for (i = 0; i < n; ++i) {
1588                         ir_node *pred = get_irn_n(irn, i);
1589
1590                         if (irn_not_visited(pred))
1591                                 dfs(pred, env);
1592                 }
1593         }
1594         else {
1595                 ir_node *block = get_nodes_block(irn);
1596
1597                 node->DFSnum = env->nextDFSnum++;
1598                 node->low    = node->DFSnum;
1599                 push(env, irn);
1600
1601                 /* handle the block */
1602                 if (irn_not_visited(block))
1603                         dfs(block, env);
1604
1605                 n = get_irn_arity(irn);
1606                 for (i = 0; i < n; ++i) {
1607                         ir_node *pred = get_irn_n(irn, i);
1608                         node_entry *o = get_irn_ne(pred, env);
1609
1610                         if (irn_not_visited(pred)) {
1611                                 dfs(pred, env);
1612                                 node->low = MIN(node->low, o->low);
1613                         }
1614                         if (o->DFSnum < node->DFSnum && o->in_stack)
1615                                 node->low = MIN(o->DFSnum, node->low);
1616                 }
1617                 if (node->low == node->DFSnum) {
1618                         scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1619                         ir_node *x;
1620
1621                         pscc->head = NULL;
1622                         do {
1623                                 node_entry *e;
1624
1625                                 x = pop(env);
1626                                 e = get_irn_ne(x, env);
1627                                 e->pscc    = pscc;
1628                                 e->next    = pscc->head;
1629                                 pscc->head = x;
1630                         } while (x != irn);
1631
1632                         process_scc(pscc, env);
1633                 }
1634         }
1635 }  /* dfs */
1636
1637 /**
1638  * Do the DFS by starting at the End node of a graph.
1639  *
1640  * @param irg  the graph to process
1641  * @param env  the loop environment
1642  */
1643 static void do_dfs(ir_graph *irg, loop_env *env) {
1644         ir_graph *rem = current_ir_graph;
1645         ir_node *end = get_irg_end(irg);
1646         int i, n;
1647
1648         current_ir_graph = irg;
1649         inc_irg_visited(irg);
1650
1651         /* visit all visible nodes */
1652         dfs(end, env);
1653
1654         /* visit the keep-alives */
1655         n = get_End_n_keepalives(end);
1656         for (i = 0; i < n; ++i) {
1657                 ir_node *ka = get_End_keepalive(end, i);
1658
1659                 if (irn_not_visited(ka))
1660                         dfs(ka, env);
1661         }
1662         current_ir_graph = rem;
1663 }  /* do_dfs */
1664
1665 /**
1666  * Initialize new phase data. We do this always explicit, so return NULL here
1667  */
1668 static void *init_loop_data(ir_phase *ph, ir_node *irn, void *data) {
1669         (void)ph;
1670         (void)irn;
1671         (void)data;
1672         return NULL;
1673 }  /* init_loop_data */
1674
1675 /**
1676  * Optimize Loads/Stores in loops.
1677  *
1678  * @param irg  the graph
1679  */
1680 static int optimize_loops(ir_graph *irg) {
1681         loop_env env;
1682
1683         env.stack         = NEW_ARR_F(ir_node *, 128);
1684         env.tos           = 0;
1685         env.nextDFSnum    = 0;
1686         env.POnum         = 0;
1687         env.changes       = 0;
1688         phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
1689
1690         /* calculate the SCC's and drive loop optimization. */
1691         do_dfs(irg, &env);
1692
1693         DEL_ARR_F(env.stack);
1694         phase_free(&env.ph);
1695
1696         return env.changes;
1697 }  /* optimize_loops */
1698
1699 /*
1700  * do the load store optimization
1701  */
1702 void optimize_load_store(ir_graph *irg) {
1703         walk_env_t env;
1704
1705         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
1706         firm_dbg_set_mask(dbg, SET_LEVEL_1);
1707
1708         assert(get_irg_phase_state(irg) != phase_building);
1709         assert(get_irg_pinned(irg) != op_pin_state_floats &&
1710                 "LoadStore optimization needs pinned graph");
1711
1712         if (! get_opt_redundant_loadstore())
1713                 return;
1714
1715         /* we need landing pads */
1716         remove_critical_cf_edges(irg);
1717
1718         edges_assure(irg);
1719
1720         /* loop optimizations need dominators ... */
1721         assure_doms(irg);
1722
1723         /* for Phi optimization post-dominators are needed ... */
1724         assure_postdoms(irg);
1725
1726         if (get_opt_alias_analysis()) {
1727                 assure_irg_address_taken_computed(irg);
1728                 assure_irp_globals_address_taken_computed();
1729         }
1730
1731         obstack_init(&env.obst);
1732         env.changes = 0;
1733
1734         /* init the links, then collect Loads/Stores/Proj's in lists */
1735         master_visited = 0;
1736         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1737
1738         /* now we have collected enough information, optimize */
1739         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1740
1741         env.changes |= optimize_loops(irg);
1742
1743         obstack_free(&env.obst, NULL);
1744
1745         /* Handle graph state */
1746         if (env.changes) {
1747                 set_irg_outs_inconsistent(irg);
1748         }
1749
1750         if (env.changes & CF_CHANGED) {
1751                 /* is this really needed: Yes, control flow changed, block might
1752                 have Bad() predecessors. */
1753                 set_irg_doms_inconsistent(irg);
1754         }
1755 }  /* optimize_load_store */