ldstopt: Remove duplicate comments.
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Copyright (C) 1995-2011 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  */
25 #include "config.h"
26
27 #include <string.h>
28
29 #include "iroptimize.h"
30 #include "irnode_t.h"
31 #include "irgraph_t.h"
32 #include "irmode_t.h"
33 #include "iropt_t.h"
34 #include "ircons_t.h"
35 #include "irgmod.h"
36 #include "irgwalk.h"
37 #include "irtools.h"
38 #include "tv_t.h"
39 #include "dbginfo_t.h"
40 #include "iropt_dbg.h"
41 #include "irflag_t.h"
42 #include "array_t.h"
43 #include "irhooks.h"
44 #include "iredges.h"
45 #include "irpass.h"
46 #include "irmemory.h"
47 #include "irnodehashmap.h"
48 #include "irgopt.h"
49 #include "set.h"
50 #include "be.h"
51 #include "debug.h"
52
53 /** The debug handle. */
54 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
55
56 #undef IMAX
57 #define IMAX(a,b)   ((a) > (b) ? (a) : (b))
58
59 #define MAX_PROJ    IMAX(IMAX((long)pn_Load_max, (long)pn_Store_max), (long)pn_Call_max)
60
61 enum changes_t {
62         DF_CHANGED = 1,       /**< data flow changed */
63         CF_CHANGED = 2,       /**< control flow changed */
64 };
65
66 /**
67  * walker environment
68  */
69 typedef struct walk_env_t {
70         struct obstack obst;          /**< list of all stores */
71         unsigned changes;             /**< a bitmask of graph changes */
72 } walk_env_t;
73
74 /** A Load/Store info. */
75 typedef struct ldst_info_t {
76         ir_node  *projs[MAX_PROJ+1];  /**< list of Proj's of this node */
77         ir_node  *exc_block;          /**< the exception block if available */
78         int      exc_idx;             /**< predecessor index in the exception block */
79         unsigned visited;             /**< visited counter for breaking loops */
80 } ldst_info_t;
81
82 /**
83  * flags for control flow.
84  */
85 enum block_flags_t {
86         BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
87         BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
88 };
89
90 /**
91  * a Block info.
92  */
93 typedef struct block_info_t {
94         unsigned flags;               /**< flags for the block */
95 } block_info_t;
96
97 /** the master visited flag for loop detection. */
98 static unsigned master_visited = 0;
99
100 #define INC_MASTER()       ++master_visited
101 #define MARK_NODE(info)    (info)->visited = master_visited
102 #define NODE_VISITED(info) (info)->visited >= master_visited
103
104 /**
105  * get the Load/Store info of a node
106  */
107 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst)
108 {
109         ldst_info_t *info = (ldst_info_t*)get_irn_link(node);
110
111         if (! info) {
112                 info = OALLOCZ(obst, ldst_info_t);
113                 set_irn_link(node, info);
114         }
115         return info;
116 }  /* get_ldst_info */
117
118 /**
119  * get the Block info of a node
120  */
121 static block_info_t *get_block_info(ir_node *node, struct obstack *obst)
122 {
123         block_info_t *info = (block_info_t*)get_irn_link(node);
124
125         if (! info) {
126                 info = OALLOCZ(obst, block_info_t);
127                 set_irn_link(node, info);
128         }
129         return info;
130 }  /* get_block_info */
131
132 /**
133  * update the projection info for a Load/Store
134  */
135 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
136 {
137         long nr = get_Proj_proj(proj);
138
139         assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
140
141         if (info->projs[nr]) {
142                 /* there is already one, do CSE */
143                 exchange(proj, info->projs[nr]);
144                 return DF_CHANGED;
145         }
146         else {
147                 info->projs[nr] = proj;
148                 return 0;
149         }
150 }  /* update_projs */
151
152 /**
153  * update the exception block info for a Load/Store node.
154  *
155  * @param info   the load/store info struct
156  * @param block  the exception handler block for this load/store
157  * @param pos    the control flow input of the block
158  */
159 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
160 {
161         assert(info->exc_block == NULL && "more than one exception block found");
162
163         info->exc_block = block;
164         info->exc_idx   = pos;
165         return 0;
166 }  /* update_exc */
167
168 /**
169  * walker, collects all Load/Store/Proj nodes
170  *
171  * walks from Start -> End
172  */
173 static void collect_nodes(ir_node *node, void *env)
174 {
175         walk_env_t  *wenv   = (walk_env_t *)env;
176         unsigned     opcode = get_irn_opcode(node);
177         ir_node     *pred, *blk, *pred_blk;
178         ldst_info_t *ldst_info;
179
180         if (opcode == iro_Proj) {
181                 pred   = get_Proj_pred(node);
182                 opcode = get_irn_opcode(pred);
183
184                 if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
185                         ldst_info = get_ldst_info(pred, &wenv->obst);
186
187                         wenv->changes |= update_projs(ldst_info, node);
188
189                         /*
190                          * Place the Proj's to the same block as the
191                          * predecessor Load. This is always ok and prevents
192                          * "non-SSA" form after optimizations if the Proj
193                          * is in a wrong block.
194                          */
195                         blk      = get_nodes_block(node);
196                         pred_blk = get_nodes_block(pred);
197                         if (blk != pred_blk) {
198                                 wenv->changes |= DF_CHANGED;
199                                 set_nodes_block(node, pred_blk);
200                         }
201                 }
202         } else if (opcode == iro_Block) {
203                 int i;
204
205                 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
206                         ir_node      *pred_block, *proj;
207                         block_info_t *bl_info;
208                         int          is_exc = 0;
209
210                         pred = proj = get_Block_cfgpred(node, i);
211
212                         if (is_Proj(proj)) {
213                                 pred   = get_Proj_pred(proj);
214                                 is_exc = is_x_except_Proj(proj);
215                         }
216
217                         /* ignore Bad predecessors, they will be removed later */
218                         if (is_Bad(pred))
219                                 continue;
220
221                         pred_block = get_nodes_block(pred);
222                         bl_info    = get_block_info(pred_block, &wenv->obst);
223
224                         if (is_fragile_op(pred) && is_exc)
225                                 bl_info->flags |= BLOCK_HAS_EXC;
226                         else if (is_irn_forking(pred))
227                                 bl_info->flags |= BLOCK_HAS_COND;
228
229                         opcode = get_irn_opcode(pred);
230                         if (is_exc && (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call)) {
231                                 ldst_info = get_ldst_info(pred, &wenv->obst);
232
233                                 wenv->changes |= update_exc(ldst_info, node, i);
234                         }
235                 }
236         }
237 }  /* collect_nodes */
238
239 /**
240  * Returns an entity if the address ptr points to a constant one.
241  *
242  * @param ptr  the address
243  *
244  * @return an entity or NULL
245  */
246 static ir_entity *find_constant_entity(ir_node *ptr)
247 {
248         for (;;) {
249                 if (is_SymConst(ptr) && get_SymConst_kind(ptr) == symconst_addr_ent) {
250                         return get_SymConst_entity(ptr);
251                 } else if (is_Sel(ptr)) {
252                         ir_entity *ent = get_Sel_entity(ptr);
253                         ir_type   *tp  = get_entity_owner(ent);
254
255                         /* Do not fiddle with polymorphism. */
256                         if (is_Class_type(get_entity_owner(ent)) &&
257                                 ((get_entity_n_overwrites(ent)    != 0) ||
258                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
259                                 return NULL;
260
261                         if (is_Array_type(tp)) {
262                                 /* check bounds */
263                                 int i, n;
264
265                                 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
266                                         ir_node   *bound;
267                                         ir_tarval *tlower, *tupper;
268                                         ir_node   *index = get_Sel_index(ptr, i);
269                                         ir_tarval *tv    = computed_value(index);
270
271                                         /* check if the index is constant */
272                                         if (tv == tarval_bad)
273                                                 return NULL;
274
275                                         bound  = get_array_lower_bound(tp, i);
276                                         tlower = computed_value(bound);
277                                         bound  = get_array_upper_bound(tp, i);
278                                         tupper = computed_value(bound);
279
280                                         if (tlower == tarval_bad || tupper == tarval_bad)
281                                                 return NULL;
282
283                                         if (tarval_cmp(tv, tlower) == ir_relation_less)
284                                                 return NULL;
285                                         if (tarval_cmp(tupper, tv) == ir_relation_less)
286                                                 return NULL;
287
288                                         /* ok, bounds check finished */
289                                 }
290                         }
291
292                         if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT)
293                                 return ent;
294
295                         /* try next */
296                         ptr = get_Sel_ptr(ptr);
297                 } else if (is_Add(ptr)) {
298                         ir_node *l = get_Add_left(ptr);
299                         ir_node *r = get_Add_right(ptr);
300
301                         if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
302                                 ptr = l;
303                         else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
304                                 ptr = r;
305                         else
306                                 return NULL;
307
308                         /* for now, we support only one addition, reassoc should fold all others */
309                         if (! is_SymConst(ptr) && !is_Sel(ptr))
310                                 return NULL;
311                 } else if (is_Sub(ptr)) {
312                         ir_node *l = get_Sub_left(ptr);
313                         ir_node *r = get_Sub_right(ptr);
314
315                         if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
316                                 ptr = l;
317                         else
318                                 return NULL;
319                         /* for now, we support only one substraction, reassoc should fold all others */
320                         if (! is_SymConst(ptr) && !is_Sel(ptr))
321                                 return NULL;
322                 } else
323                         return NULL;
324         }
325 }  /* find_constant_entity */
326
327 /**
328  * Return the Selection index of a Sel node from dimension n
329  */
330 static long get_Sel_array_index_long(ir_node *n, int dim)
331 {
332         ir_node *index = get_Sel_index(n, dim);
333         assert(is_Const(index));
334         return get_tarval_long(get_Const_tarval(index));
335 }  /* get_Sel_array_index_long */
336
337 typedef struct path_entry {
338         ir_entity         *ent;
339         struct path_entry *next;
340         size_t            index;
341 } path_entry;
342
343 static ir_node *rec_find_compound_ent_value(ir_node *ptr, path_entry *next)
344 {
345         path_entry       entry, *p;
346         ir_entity        *ent, *field;
347         ir_initializer_t *initializer;
348         ir_tarval        *tv;
349         ir_type          *tp;
350         size_t           n;
351
352         entry.next = next;
353         if (is_SymConst(ptr)) {
354                 /* found the root */
355                 ent         = get_SymConst_entity(ptr);
356                 initializer = get_entity_initializer(ent);
357                 for (p = next; p != NULL;) {
358                         if (initializer->kind != IR_INITIALIZER_COMPOUND)
359                                 return NULL;
360                         n  = get_initializer_compound_n_entries(initializer);
361                         tp = get_entity_type(ent);
362
363                         if (is_Array_type(tp)) {
364                                 ent = get_array_element_entity(tp);
365                                 if (ent != p->ent) {
366                                         /* a missing [0] */
367                                         if (0 >= n)
368                                                 return NULL;
369                                         initializer = get_initializer_compound_value(initializer, 0);
370                                         continue;
371                                 }
372                         }
373                         if (p->index >= n)
374                                 return NULL;
375                         initializer = get_initializer_compound_value(initializer, p->index);
376
377                         ent = p->ent;
378                         p   = p->next;
379                 }
380                 tp = get_entity_type(ent);
381                 while (is_Array_type(tp)) {
382                         ent = get_array_element_entity(tp);
383                         tp = get_entity_type(ent);
384                         /* a missing [0] */
385                         n  = get_initializer_compound_n_entries(initializer);
386                         if (0 >= n)
387                                 return NULL;
388                         initializer = get_initializer_compound_value(initializer, 0);
389                 }
390
391                 switch (initializer->kind) {
392                 case IR_INITIALIZER_CONST:
393                         return get_initializer_const_value(initializer);
394                 case IR_INITIALIZER_TARVAL:
395                 case IR_INITIALIZER_NULL:
396                 default:
397                         return NULL;
398                 }
399         } else if (is_Sel(ptr)) {
400                 entry.ent = field = get_Sel_entity(ptr);
401                 tp = get_entity_owner(field);
402                 if (is_Array_type(tp)) {
403                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
404                         entry.index = get_Sel_array_index_long(ptr, 0) - get_array_lower_bound_int(tp, 0);
405                 } else {
406                         size_t i, n_members = get_compound_n_members(tp);
407                         for (i = 0; i < n_members; ++i) {
408                                 if (get_compound_member(tp, i) == field)
409                                         break;
410                         }
411                         if (i >= n_members) {
412                                 /* not found: should NOT happen */
413                                 return NULL;
414                         }
415                         entry.index = i;
416                 }
417                 return rec_find_compound_ent_value(get_Sel_ptr(ptr), &entry);
418         }  else if (is_Add(ptr)) {
419                 ir_mode  *mode;
420                 unsigned pos;
421
422                 {
423                         ir_node *l = get_Add_left(ptr);
424                         ir_node *r = get_Add_right(ptr);
425                         if (is_Const(r)) {
426                                 ptr = l;
427                                 tv  = get_Const_tarval(r);
428                         } else {
429                                 ptr = r;
430                                 tv  = get_Const_tarval(l);
431                         }
432                 }
433 ptr_arith:
434                 mode = get_tarval_mode(tv);
435
436                 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
437                 if (is_Sel(ptr)) {
438                         field = get_Sel_entity(ptr);
439                 } else {
440                         field = get_SymConst_entity(ptr);
441                 }
442
443                 /* count needed entries */
444                 pos = 0;
445                 for (ent = field;;) {
446                         tp = get_entity_type(ent);
447                         if (! is_Array_type(tp))
448                                 break;
449                         ent = get_array_element_entity(tp);
450                         ++pos;
451                 }
452                 /* should be at least ONE entry */
453                 if (pos == 0)
454                         return NULL;
455
456                 /* allocate the right number of entries */
457                 NEW_ARR_A(path_entry, p, pos);
458
459                 /* fill them up */
460                 pos = 0;
461                 for (ent = field;;) {
462                         unsigned   size;
463                         ir_tarval *sz, *tv_index, *tlower, *tupper;
464                         long       index;
465                         ir_node   *bound;
466
467                         tp = get_entity_type(ent);
468                         if (! is_Array_type(tp))
469                                 break;
470                         ent = get_array_element_entity(tp);
471                         p[pos].ent  = ent;
472                         p[pos].next = &p[pos + 1];
473
474                         size = get_type_size_bytes(get_entity_type(ent));
475                         sz   = new_tarval_from_long(size, mode);
476
477                         tv_index = tarval_div(tv, sz);
478                         tv       = tarval_mod(tv, sz);
479
480                         if (tv_index == tarval_bad || tv == tarval_bad)
481                                 return NULL;
482
483                         assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
484                         bound  = get_array_lower_bound(tp, 0);
485                         tlower = computed_value(bound);
486                         bound  = get_array_upper_bound(tp, 0);
487                         tupper = computed_value(bound);
488
489                         if (tlower == tarval_bad || tupper == tarval_bad)
490                                 return NULL;
491
492                         if (tarval_cmp(tv_index, tlower) == ir_relation_less)
493                                 return NULL;
494                         if (tarval_cmp(tupper, tv_index) == ir_relation_less)
495                                 return NULL;
496
497                         /* ok, bounds check finished */
498                         index = get_tarval_long(tv_index);
499                         p[pos].index = index;
500                         ++pos;
501                 }
502                 if (! tarval_is_null(tv)) {
503                         /* hmm, wrong access */
504                         return NULL;
505                 }
506                 p[pos - 1].next = next;
507                 return rec_find_compound_ent_value(ptr, p);
508         } else if (is_Sub(ptr)) {
509                 ir_node *l = get_Sub_left(ptr);
510                 ir_node *r = get_Sub_right(ptr);
511
512                 ptr = l;
513                 tv  = get_Const_tarval(r);
514                 tv  = tarval_neg(tv);
515                 goto ptr_arith;
516         }
517         return NULL;
518 }
519
520 static ir_node *find_compound_ent_value(ir_node *ptr)
521 {
522         return rec_find_compound_ent_value(ptr, NULL);
523 }
524
525 /* forward */
526 static void reduce_adr_usage(ir_node *ptr);
527
528 /**
529  * Update a Load that may have lost its users.
530  */
531 static void handle_load_update(ir_node *load)
532 {
533         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
534
535         /* do NOT touch volatile loads for now */
536         if (get_Load_volatility(load) == volatility_is_volatile)
537                 return;
538
539         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
540                 ir_node *ptr = get_Load_ptr(load);
541                 ir_node *mem = get_Load_mem(load);
542
543                 /* a Load whose value is neither used nor exception checked, remove it */
544                 exchange(info->projs[pn_Load_M], mem);
545                 if (info->projs[pn_Load_X_regular])
546                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
547                 kill_node(load);
548                 reduce_adr_usage(ptr);
549         }
550 }  /* handle_load_update */
551
552 /**
553  * A use of an address node has vanished. Check if this was a Proj
554  * node and update the counters.
555  */
556 static void reduce_adr_usage(ir_node *ptr)
557 {
558         ir_node *pred;
559         if (!is_Proj(ptr))
560                 return;
561         if (get_irn_n_edges(ptr) > 0)
562                 return;
563
564         /* this Proj is dead now */
565         pred = get_Proj_pred(ptr);
566         if (is_Load(pred)) {
567                 ldst_info_t *info = (ldst_info_t*)get_irn_link(pred);
568                 info->projs[get_Proj_proj(ptr)] = NULL;
569
570                 /* this node lost its result proj, handle that */
571                 handle_load_update(pred);
572         }
573 }  /* reduce_adr_usage */
574
575 /**
576  * Check, if an already existing value of mode old_mode can be converted
577  * into the needed one new_mode without loss.
578  */
579 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode)
580 {
581         unsigned old_size;
582         unsigned new_size;
583         if (old_mode == new_mode)
584                 return true;
585
586         old_size = get_mode_size_bits(old_mode);
587         new_size = get_mode_size_bits(new_mode);
588
589         /* if both modes are two-complement ones, we can always convert the
590            Stored value into the needed one. (on big endian machines we currently
591            only support this for modes of same size) */
592         if (old_size >= new_size &&
593                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
594                   get_mode_arithmetic(new_mode) == irma_twos_complement &&
595                   (!be_get_backend_param()->byte_order_big_endian
596                 || old_size == new_size)) {
597                 return true;
598         }
599         return false;
600 }
601
602 /**
603  * Check whether a Call is at least pure, i.e. does only read memory.
604  */
605 static unsigned is_Call_pure(ir_node *call)
606 {
607         ir_type *call_tp = get_Call_type(call);
608         unsigned prop = get_method_additional_properties(call_tp);
609
610         /* check first the call type */
611         if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
612                 /* try the called entity */
613                 ir_node *ptr = get_Call_ptr(call);
614
615                 if (is_SymConst_addr_ent(ptr)) {
616                         ir_entity *ent = get_SymConst_entity(ptr);
617
618                         prop = get_entity_additional_properties(ent);
619                 }
620         }
621         return (prop & (mtp_property_const|mtp_property_pure)) != 0;
622 }  /* is_Call_pure */
623
624 static ir_node *get_base_and_offset(ir_node *ptr, long *pOffset)
625 {
626         ir_mode *mode  = get_irn_mode(ptr);
627         long    offset = 0;
628
629         /* TODO: long might not be enough, we should probably use some tarval thingy... */
630         for (;;) {
631                 if (is_Add(ptr)) {
632                         ir_node *l = get_Add_left(ptr);
633                         ir_node *r = get_Add_right(ptr);
634
635                         if (get_irn_mode(l) != mode || !is_Const(r))
636                                 break;
637
638                         offset += get_tarval_long(get_Const_tarval(r));
639                         ptr     = l;
640                 } else if (is_Sub(ptr)) {
641                         ir_node *l = get_Sub_left(ptr);
642                         ir_node *r = get_Sub_right(ptr);
643
644                         if (get_irn_mode(l) != mode || !is_Const(r))
645                                 break;
646
647                         offset -= get_tarval_long(get_Const_tarval(r));
648                         ptr     = l;
649                 } else if (is_Sel(ptr)) {
650                         ir_entity *ent = get_Sel_entity(ptr);
651                         ir_type   *tp  = get_entity_owner(ent);
652
653                         if (is_Array_type(tp)) {
654                                 int     size;
655                                 ir_node *index;
656
657                                 /* only one dimensional arrays yet */
658                                 if (get_Sel_n_indexs(ptr) != 1)
659                                         break;
660                                 index = get_Sel_index(ptr, 0);
661                                 if (! is_Const(index))
662                                         break;
663
664                                 tp = get_entity_type(ent);
665                                 if (get_type_state(tp) != layout_fixed)
666                                         break;
667
668                                 size    = get_type_size_bytes(tp);
669                                 offset += size * get_tarval_long(get_Const_tarval(index));
670                         } else {
671                                 if (get_type_state(tp) != layout_fixed)
672                                         break;
673                                 offset += get_entity_offset(ent);
674                         }
675                         ptr = get_Sel_ptr(ptr);
676                 } else
677                         break;
678         }
679
680         *pOffset = offset;
681         return ptr;
682 }
683
684 static int try_load_after_store(ir_node *load,
685                 ir_node *load_base_ptr, long load_offset, ir_node *store)
686 {
687         ldst_info_t *info;
688         ir_node *store_ptr      = get_Store_ptr(store);
689         long     store_offset;
690         ir_node *store_base_ptr = get_base_and_offset(store_ptr, &store_offset);
691         ir_node *store_value;
692         ir_mode *store_mode;
693         ir_node *load_ptr;
694         ir_mode *load_mode;
695         long     load_mode_len;
696         long     store_mode_len;
697         long     delta;
698         int      res;
699
700         if (load_base_ptr != store_base_ptr)
701                 return 0;
702
703         load_mode      = get_Load_mode(load);
704         load_mode_len  = get_mode_size_bytes(load_mode);
705         store_mode     = get_irn_mode(get_Store_value(store));
706         store_mode_len = get_mode_size_bytes(store_mode);
707         delta          = load_offset - store_offset;
708         store_value    = get_Store_value(store);
709
710         if (delta != 0 || store_mode != load_mode) {
711                 /* TODO: implement for big-endian */
712                 if (delta < 0 || delta + load_mode_len > store_mode_len
713                                 || (be_get_backend_param()->byte_order_big_endian
714                                     && load_mode_len != store_mode_len))
715                         return 0;
716
717                 if (get_mode_arithmetic(store_mode) != irma_twos_complement ||
718                         get_mode_arithmetic(load_mode)  != irma_twos_complement)
719                         return 0;
720
721
722                 /* produce a shift to adjust offset delta */
723                 if (delta > 0) {
724                         ir_node *cnst;
725                         ir_graph *irg = get_irn_irg(load);
726
727                         cnst        = new_r_Const_long(irg, mode_Iu, delta * 8);
728                         store_value = new_r_Shr(get_nodes_block(load),
729                                                                         store_value, cnst, store_mode);
730                 }
731
732                 /* add an convert if needed */
733                 if (store_mode != load_mode) {
734                         store_value = new_r_Conv(get_nodes_block(load), store_value, load_mode);
735                 }
736         }
737
738         DBG_OPT_RAW(load, store_value);
739
740         info = (ldst_info_t*)get_irn_link(load);
741         if (info->projs[pn_Load_M])
742                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
743
744         res = 0;
745         /* no exception */
746         if (info->projs[pn_Load_X_except]) {
747                 ir_graph *irg = get_irn_irg(load);
748                 exchange( info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
749                 res |= CF_CHANGED;
750         }
751         if (info->projs[pn_Load_X_regular]) {
752                 exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
753                 res |= CF_CHANGED;
754         }
755
756         if (info->projs[pn_Load_res])
757                 exchange(info->projs[pn_Load_res], store_value);
758
759         load_ptr = get_Load_ptr(load);
760         kill_node(load);
761         reduce_adr_usage(load_ptr);
762         return res | DF_CHANGED;
763 }
764
765 /**
766  * Follow the memory chain as long as there are only Loads,
767  * alias free Stores, and constant Calls and try to replace the
768  * current Load by a previous ones.
769  * Note that in unreachable loops it might happen that we reach
770  * load again, as well as we can fall into a cycle.
771  * We break such cycles using a special visited flag.
772  *
773  * INC_MASTER() must be called before dive into
774  */
775 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr)
776 {
777         unsigned    res = 0;
778         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
779         ir_node     *pred;
780         ir_node     *ptr       = get_Load_ptr(load);
781         ir_node     *mem       = get_Load_mem(load);
782         ir_mode     *load_mode = get_Load_mode(load);
783
784         for (pred = curr; load != pred; ) {
785                 ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
786
787                 /*
788                  * a Load immediately after a Store -- a read after write.
789                  * We may remove the Load, if both Load & Store does not have an
790                  * exception handler OR they are in the same Block. In the latter
791                  * case the Load cannot throw an exception when the previous Store was
792                  * quiet.
793                  *
794                  * Why we need to check for Store Exception? If the Store cannot
795                  * be executed (ROM) the exception handler might simply jump into
796                  * the load Block :-(
797                  * We could make it a little bit better if we would know that the
798                  * exception handler of the Store jumps directly to the end...
799                  */
800                 if (is_Store(pred) && ((pred_info->projs[pn_Store_X_except] == NULL
801                                 && info->projs[pn_Load_X_except] == NULL)
802                                 || get_nodes_block(load) == get_nodes_block(pred)))
803                 {
804                         long    load_offset;
805                         ir_node *base_ptr = get_base_and_offset(ptr, &load_offset);
806                         int     changes   = try_load_after_store(load, base_ptr, load_offset, pred);
807
808                         if (changes != 0)
809                                 return res | changes;
810                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
811                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
812                         /*
813                          * a Load after a Load -- a read after read.
814                          * We may remove the second Load, if it does not have an exception
815                          * handler OR they are in the same Block. In the later case
816                          * the Load cannot throw an exception when the previous Load was
817                          * quiet.
818                          *
819                          * Here, there is no need to check if the previous Load has an
820                          * exception hander because they would have exact the same
821                          * exception...
822                          *
823                          * TODO: implement load-after-load with different mode for big
824                          *       endian
825                          */
826                         if (info->projs[pn_Load_X_except] == NULL
827                                         || get_nodes_block(load) == get_nodes_block(pred)) {
828                                 ir_node *value;
829
830                                 DBG_OPT_RAR(load, pred);
831
832                                 /* the result is used */
833                                 if (info->projs[pn_Load_res]) {
834                                         if (pred_info->projs[pn_Load_res] == NULL) {
835                                                 /* create a new Proj again */
836                                                 pred_info->projs[pn_Load_res] = new_r_Proj(pred, get_Load_mode(pred), pn_Load_res);
837                                         }
838                                         value = pred_info->projs[pn_Load_res];
839
840                                         /* add an convert if needed */
841                                         if (get_Load_mode(pred) != load_mode) {
842                                                 value = new_r_Conv(get_nodes_block(load), value, load_mode);
843                                         }
844
845                                         exchange(info->projs[pn_Load_res], value);
846                                 }
847
848                                 if (info->projs[pn_Load_M])
849                                         exchange(info->projs[pn_Load_M], mem);
850
851                                 /* no exception */
852                                 if (info->projs[pn_Load_X_except]) {
853                                         ir_graph *irg = get_irn_irg(load);
854                                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
855                                         res |= CF_CHANGED;
856                                 }
857                                 if (info->projs[pn_Load_X_regular]) {
858                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
859                                         res |= CF_CHANGED;
860                                 }
861
862                                 kill_node(load);
863                                 reduce_adr_usage(ptr);
864                                 return res |= DF_CHANGED;
865                         }
866                 }
867
868                 if (is_Store(pred)) {
869                         /* check if we can pass through this store */
870                         ir_alias_relation rel = get_alias_relation(
871                                 get_Store_ptr(pred),
872                                 get_irn_mode(get_Store_value(pred)),
873                                 ptr, load_mode);
874                         /* if the might be an alias, we cannot pass this Store */
875                         if (rel != ir_no_alias)
876                                 break;
877                         pred = skip_Proj(get_Store_mem(pred));
878                 } else if (is_Load(pred)) {
879                         pred = skip_Proj(get_Load_mem(pred));
880                 } else if (is_Call(pred)) {
881                         if (is_Call_pure(pred)) {
882                                 /* The called graph is at least pure, so there are no Store's
883                                    in it. We can handle it like a Load and skip it. */
884                                 pred = skip_Proj(get_Call_mem(pred));
885                         } else {
886                                 /* there might be Store's in the graph, stop here */
887                                 break;
888                         }
889                 } else {
890                         /* follow only Load chains */
891                         break;
892                 }
893
894                 /* check for cycles */
895                 if (NODE_VISITED(pred_info))
896                         break;
897                 MARK_NODE(pred_info);
898         }
899
900         if (is_Sync(pred)) {
901                 int i;
902
903                 /* handle all Sync predecessors */
904                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
905                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
906                         if (res)
907                                 return res;
908                 }
909         }
910
911         return res;
912 }  /* follow_Mem_chain */
913
914 ir_node *can_replace_load_by_const(const ir_node *load, ir_node *c)
915 {
916         ir_mode  *c_mode = get_irn_mode(c);
917         ir_mode  *l_mode = get_Load_mode(load);
918         ir_node  *block  = get_nodes_block(load);
919         dbg_info *dbgi   = get_irn_dbg_info(load);
920         ir_node  *res    = copy_const_value(dbgi, c, block);
921
922         if (c_mode != l_mode) {
923                 /* check, if the mode matches OR can be easily converted info */
924                 if (is_reinterpret_cast(c_mode, l_mode)) {
925                         /* copy the value from the const code irg and cast it */
926                         res = new_rd_Conv(dbgi, block, res, l_mode);
927                 } else {
928                         return NULL;
929                 }
930         }
931         return res;
932 }
933
934 /**
935  * optimize a Load
936  *
937  * @param load  the Load node
938  */
939 static unsigned optimize_load(ir_node *load)
940 {
941         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
942         ir_node     *mem, *ptr, *value;
943         ir_entity   *ent;
944         long        dummy;
945         unsigned    res = 0;
946
947         /* do NOT touch volatile loads for now */
948         if (get_Load_volatility(load) == volatility_is_volatile)
949                 return 0;
950
951         /* the address of the load to be optimized */
952         ptr = get_Load_ptr(load);
953
954         /* The mem of the Load. Must still be returned after optimization. */
955         mem = get_Load_mem(load);
956
957         if (info->projs[pn_Load_res] == NULL
958                         && info->projs[pn_Load_X_except] == NULL) {
959                 /* the value is never used and we don't care about exceptions, remove */
960                 exchange(info->projs[pn_Load_M], mem);
961
962                 if (info->projs[pn_Load_X_regular]) {
963                         /* should not happen, but if it does, remove it */
964                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
965                         res |= CF_CHANGED;
966                 }
967                 kill_node(load);
968                 reduce_adr_usage(ptr);
969                 return res | DF_CHANGED;
970         }
971
972         value = NULL;
973         /* check if we can determine the entity that will be loaded */
974         ent = find_constant_entity(ptr);
975         if (ent != NULL
976                         && get_entity_visibility(ent) != ir_visibility_external) {
977                 /* a static allocation that is not external: there should be NO
978                  * exception when loading even if we cannot replace the load itself.
979                  */
980
981                 /* no exception, clear the info field as it might be checked later again */
982                 if (info->projs[pn_Load_X_except]) {
983                         ir_graph *irg = get_irn_irg(load);
984                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
985                         info->projs[pn_Load_X_except] = NULL;
986                         res |= CF_CHANGED;
987                 }
988                 if (info->projs[pn_Load_X_regular]) {
989                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
990                         info->projs[pn_Load_X_regular] = NULL;
991                         res |= CF_CHANGED;
992                 }
993
994                 if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT) {
995                         if (has_entity_initializer(ent)) {
996                                 /* new style initializer */
997                                 value = find_compound_ent_value(ptr);
998                         }
999                         if (value != NULL) {
1000                                 ir_graph *irg = get_irn_irg(load);
1001                                 value = can_replace_load_by_const(load, value);
1002                                 if (value != NULL && is_Sel(ptr)) {
1003                                         /* frontend has inserted masking operations after bitfield accesses,
1004                                          * so we might have to shift the const. */
1005                                         unsigned char bit_offset = get_entity_offset_bits_remainder(get_Sel_entity(ptr));
1006                                         if (bit_offset != 0) {
1007                                                 if (is_Const(value)) {
1008                                                         ir_tarval *tv_old = get_Const_tarval(value);
1009                                                         ir_tarval *tv_offset = new_tarval_from_long(bit_offset, mode_Bu);
1010                                                         ir_tarval *tv_new = tarval_shl(tv_old, tv_offset);
1011                                                         value = new_r_Const(irg, tv_new);
1012                                                 } else {
1013                                                         value = NULL;
1014                                                 }
1015                                         }
1016                                 }
1017                         }
1018                 }
1019         }
1020         if (value != NULL) {
1021                 /* we completely replace the load by this value */
1022                 if (info->projs[pn_Load_X_except]) {
1023                         ir_graph *irg = get_irn_irg(load);
1024                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
1025                         info->projs[pn_Load_X_except] = NULL;
1026                         res |= CF_CHANGED;
1027                 }
1028                 if (info->projs[pn_Load_X_regular]) {
1029                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
1030                         info->projs[pn_Load_X_regular] = NULL;
1031                         res |= CF_CHANGED;
1032                 }
1033                 if (info->projs[pn_Load_M]) {
1034                         exchange(info->projs[pn_Load_M], mem);
1035                         res |= DF_CHANGED;
1036                 }
1037                 if (info->projs[pn_Load_res]) {
1038                         exchange(info->projs[pn_Load_res], value);
1039                         res |= DF_CHANGED;
1040                 }
1041                 kill_node(load);
1042                 reduce_adr_usage(ptr);
1043                 return res;
1044         }
1045
1046         /* Check, if the address of this load is used more than once.
1047          * If not, more load cannot be removed in any case. */
1048         if (get_irn_n_edges(ptr) <= 1 && get_irn_n_edges(get_base_and_offset(ptr, &dummy)) <= 1)
1049                 return res;
1050
1051         /*
1052          * follow the memory chain as long as there are only Loads
1053          * and try to replace current Load or Store by a previous one.
1054          * Note that in unreachable loops it might happen that we reach
1055          * load again, as well as we can fall into a cycle.
1056          * We break such cycles using a special visited flag.
1057          */
1058         INC_MASTER();
1059         res = follow_Mem_chain(load, skip_Proj(mem));
1060         return res;
1061 }  /* optimize_load */
1062
1063 /**
1064  * Check whether a value of mode new_mode would completely overwrite a value
1065  * of mode old_mode in memory.
1066  */
1067 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
1068 {
1069         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
1070 }  /* is_completely_overwritten */
1071
1072 /**
1073  * Check whether small is a part of large (starting at same address).
1074  */
1075 static int is_partially_same(ir_node *small, ir_node *large)
1076 {
1077         ir_mode *sm = get_irn_mode(small);
1078         ir_mode *lm = get_irn_mode(large);
1079
1080         /* FIXME: Check endianness */
1081         return is_Conv(small) && get_Conv_op(small) == large
1082             && get_mode_size_bytes(sm) < get_mode_size_bytes(lm)
1083             && get_mode_arithmetic(sm) == irma_twos_complement
1084             && get_mode_arithmetic(lm) == irma_twos_complement;
1085 }  /* is_partially_same */
1086
1087 /**
1088  * follow the memory chain as long as there are only Loads and alias free Stores.
1089  *
1090  * INC_MASTER() must be called before dive into
1091  */
1092 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr)
1093 {
1094         unsigned res = 0;
1095         ldst_info_t *info = (ldst_info_t*)get_irn_link(store);
1096         ir_node *pred;
1097         ir_node *ptr = get_Store_ptr(store);
1098         ir_node *mem = get_Store_mem(store);
1099         ir_node *value = get_Store_value(store);
1100         ir_mode *mode  = get_irn_mode(value);
1101         ir_node *block = get_nodes_block(store);
1102
1103         for (pred = curr; pred != store;) {
1104                 ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
1105
1106                 /*
1107                  * BEWARE: one might think that checking the modes is useless, because
1108                  * if the pointers are identical, they refer to the same object.
1109                  * This is only true in strong typed languages, not is C were the following
1110                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
1111                  * However, if the size of the mode that is written is bigger or equal the
1112                  * size of the old one, the old value is completely overwritten and can be
1113                  * killed ...
1114                  */
1115                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
1116             get_nodes_block(pred) == block) {
1117                         /*
1118                          * a Store after a Store in the same Block -- a write after write.
1119                          */
1120
1121                         /*
1122                          * We may remove the first Store, if the old value is completely
1123                          * overwritten or the old value is a part of the new value,
1124                          * and if it does not have an exception handler.
1125                          *
1126                          * TODO: What, if both have the same exception handler ???
1127                          */
1128                         if (get_Store_volatility(pred) != volatility_is_volatile
1129                                 && !pred_info->projs[pn_Store_X_except]) {
1130                                 ir_node *predvalue = get_Store_value(pred);
1131                                 ir_mode *predmode  = get_irn_mode(predvalue);
1132
1133                                 if (is_completely_overwritten(predmode, mode)
1134                                         || is_partially_same(predvalue, value)) {
1135                                         DBG_OPT_WAW(pred, store);
1136                                         exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
1137                                         kill_node(pred);
1138                                         reduce_adr_usage(ptr);
1139                                         return DF_CHANGED;
1140                                 }
1141                         }
1142
1143                         /*
1144                          * We may remove the Store, if the old value already contains
1145                          * the new value, and if it does not have an exception handler.
1146                          *
1147                          * TODO: What, if both have the same exception handler ???
1148                          */
1149                         if (get_Store_volatility(store) != volatility_is_volatile
1150                                 && !info->projs[pn_Store_X_except]) {
1151                                 ir_node *predvalue = get_Store_value(pred);
1152
1153                                 if (is_partially_same(value, predvalue)) {
1154                                         DBG_OPT_WAW(pred, store);
1155                                         exchange(info->projs[pn_Store_M], mem);
1156                                         kill_node(store);
1157                                         reduce_adr_usage(ptr);
1158                                         return DF_CHANGED;
1159                                 }
1160                         }
1161                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
1162                            value == pred_info->projs[pn_Load_res]) {
1163                         /*
1164                          * a Store of a value just loaded from the same address
1165                          * -- a write after read.
1166                          * We may remove the Store, if it does not have an exception
1167                          * handler.
1168                          */
1169                         if (! info->projs[pn_Store_X_except]) {
1170                                 DBG_OPT_WAR(store, pred);
1171                                 exchange(info->projs[pn_Store_M], mem);
1172                                 kill_node(store);
1173                                 reduce_adr_usage(ptr);
1174                                 return DF_CHANGED;
1175                         }
1176                 }
1177
1178                 if (is_Store(pred)) {
1179                         /* check if we can pass through this store */
1180                         ir_alias_relation rel = get_alias_relation(
1181                                 get_Store_ptr(pred),
1182                                 get_irn_mode(get_Store_value(pred)),
1183                                 ptr, mode);
1184                         /* if the might be an alias, we cannot pass this Store */
1185                         if (rel != ir_no_alias)
1186                                 break;
1187                         pred = skip_Proj(get_Store_mem(pred));
1188                 } else if (is_Load(pred)) {
1189                         ir_alias_relation rel = get_alias_relation(
1190                                 get_Load_ptr(pred), get_Load_mode(pred),
1191                                 ptr, mode);
1192                         if (rel != ir_no_alias)
1193                                 break;
1194
1195                         pred = skip_Proj(get_Load_mem(pred));
1196                 } else {
1197                         /* follow only Load chains */
1198                         break;
1199                 }
1200
1201                 /* check for cycles */
1202                 if (NODE_VISITED(pred_info))
1203                         break;
1204                 MARK_NODE(pred_info);
1205         }
1206
1207         if (is_Sync(pred)) {
1208                 int i;
1209
1210                 /* handle all Sync predecessors */
1211                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
1212                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
1213                         if (res)
1214                                 break;
1215                 }
1216         }
1217         return res;
1218 }  /* follow_Mem_chain_for_Store */
1219
1220 /** find entity used as base for an address calculation */
1221 static ir_entity *find_entity(ir_node *ptr)
1222 {
1223         switch (get_irn_opcode(ptr)) {
1224         case iro_SymConst:
1225                 return get_SymConst_entity(ptr);
1226         case iro_Sel: {
1227                 ir_node *pred = get_Sel_ptr(ptr);
1228                 if (get_irg_frame(get_irn_irg(ptr)) == pred)
1229                         return get_Sel_entity(ptr);
1230
1231                 return find_entity(pred);
1232         }
1233         case iro_Sub:
1234         case iro_Add: {
1235                 ir_node *left = get_binop_left(ptr);
1236                 ir_node *right;
1237                 if (mode_is_reference(get_irn_mode(left)))
1238                         return find_entity(left);
1239                 right = get_binop_right(ptr);
1240                 if (mode_is_reference(get_irn_mode(right)))
1241                         return find_entity(right);
1242                 return NULL;
1243         }
1244         default:
1245                 return NULL;
1246         }
1247 }
1248
1249 /**
1250  * optimize a Store
1251  *
1252  * @param store  the Store node
1253  */
1254 static unsigned optimize_store(ir_node *store)
1255 {
1256         ir_node   *ptr;
1257         ir_node   *mem;
1258         ir_entity *entity;
1259
1260         if (get_Store_volatility(store) == volatility_is_volatile)
1261                 return 0;
1262
1263         ptr    = get_Store_ptr(store);
1264         entity = find_entity(ptr);
1265
1266         /* a store to an entity which is never read is unnecessary */
1267         if (entity != NULL && !(get_entity_usage(entity) & ir_usage_read)) {
1268                 ldst_info_t *info = (ldst_info_t*)get_irn_link(store);
1269                 if (info->projs[pn_Store_X_except] == NULL) {
1270                         DB((dbg, LEVEL_1, "  Killing useless %+F to never read entity %+F\n", store, entity));
1271                         exchange(info->projs[pn_Store_M], get_Store_mem(store));
1272                         kill_node(store);
1273                         reduce_adr_usage(ptr);
1274                         return DF_CHANGED;
1275                 }
1276         }
1277
1278         /* Check, if the address of this Store is used more than once.
1279          * If not, this Store cannot be removed in any case. */
1280         if (get_irn_n_edges(ptr) <= 1)
1281                 return 0;
1282
1283         mem = get_Store_mem(store);
1284
1285         /* follow the memory chain as long as there are only Loads */
1286         INC_MASTER();
1287
1288         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
1289 }  /* optimize_store */
1290
1291 /* check if a node has more than one real user. Keepalive edges do not count as
1292  * real users */
1293 static bool has_multiple_users(const ir_node *node)
1294 {
1295         unsigned real_users = 0;
1296         foreach_out_edge(node, edge) {
1297                 ir_node *user = get_edge_src_irn(edge);
1298                 if (is_End(user))
1299                         continue;
1300                 ++real_users;
1301                 if (real_users > 1)
1302                         return true;
1303         }
1304         return false;
1305 }
1306
1307 /**
1308  * walker, optimizes Phi after Stores to identical places:
1309  * Does the following optimization:
1310  * @verbatim
1311  *
1312  *   val1   val2   val3          val1  val2  val3
1313  *    |      |      |               \    |    /
1314  *  Store  Store  Store              \   |   /
1315  *      \    |    /                   PhiData
1316  *       \   |   /                       |
1317  *        \  |  /                      Store
1318  *          PhiM
1319  *
1320  * @endverbatim
1321  * This reduces the number of stores and allows for predicated execution.
1322  * Moves Stores back to the end of a function which may be bad.
1323  *
1324  * This is only possible if the predecessor blocks have only one successor.
1325  */
1326 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1327 {
1328         int i, n;
1329         ir_node *store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1330 #ifdef DO_CACHEOPT
1331         ir_node *old_store;
1332 #endif
1333         ir_mode *mode;
1334         ir_node **inM, **inD, **projMs;
1335         int *idx;
1336         dbg_info *db = NULL;
1337         ldst_info_t *info;
1338         block_info_t *bl_info;
1339         unsigned res = 0;
1340
1341         /* Must be a memory Phi */
1342         if (get_irn_mode(phi) != mode_M)
1343                 return 0;
1344
1345         n = get_Phi_n_preds(phi);
1346         if (n <= 0)
1347                 return 0;
1348
1349         /* must be only one user */
1350         projM = get_Phi_pred(phi, 0);
1351         if (has_multiple_users(projM))
1352                 return 0;
1353
1354         store = skip_Proj(projM);
1355 #ifdef DO_CACHEOPT
1356         old_store = store;
1357 #endif
1358         if (!is_Store(store))
1359                 return 0;
1360
1361         block = get_nodes_block(store);
1362
1363         /* check if the block is post dominated by Phi-block
1364            and has no exception exit */
1365         bl_info = (block_info_t*)get_irn_link(block);
1366         if (bl_info->flags & BLOCK_HAS_EXC)
1367                 return 0;
1368
1369         phi_block = get_nodes_block(phi);
1370         if (! block_strictly_postdominates(phi_block, block))
1371                 return 0;
1372
1373         /* this is the address of the store */
1374         ptr  = get_Store_ptr(store);
1375         mode = get_irn_mode(get_Store_value(store));
1376         info = (ldst_info_t*)get_irn_link(store);
1377         exc  = info->exc_block;
1378
1379         for (i = 1; i < n; ++i) {
1380                 ir_node *pred = get_Phi_pred(phi, i);
1381
1382                 if (has_multiple_users(pred))
1383                         return 0;
1384
1385                 pred = skip_Proj(pred);
1386                 if (!is_Store(pred))
1387                         return 0;
1388
1389                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1390                         return 0;
1391
1392                 info = (ldst_info_t*)get_irn_link(pred);
1393
1394                 /* check, if all stores have the same exception flow */
1395                 if (exc != info->exc_block)
1396                         return 0;
1397
1398                 block = get_nodes_block(pred);
1399
1400                 /* check if the block is post dominated by Phi-block
1401                    and has no exception exit. Note that block must be different from
1402                    Phi-block, else we would move a Store from end End of a block to its
1403                    Start... */
1404                 bl_info = (block_info_t*)get_irn_link(block);
1405                 if (bl_info->flags & BLOCK_HAS_EXC)
1406                         return 0;
1407                 if (block == phi_block || ! block_postdominates(phi_block, block))
1408                         return 0;
1409         }
1410
1411         /*
1412          * ok, when we are here, we found all predecessors of a Phi that
1413          * are Stores to the same address and size. That means whatever
1414          * we do before we enter the block of the Phi, we do a Store.
1415          * So, we can move the Store to the current block:
1416          *
1417          *   val1    val2    val3          val1  val2  val3
1418          *    |       |       |               \    |    /
1419          * | Str | | Str | | Str |             \   |   /
1420          *      \     |     /                   PhiData
1421          *       \    |    /                       |
1422          *        \   |   /                       Str
1423          *           PhiM
1424          *
1425          * Is only allowed if the predecessor blocks have only one successor.
1426          */
1427
1428         NEW_ARR_A(ir_node *, projMs, n);
1429         NEW_ARR_A(ir_node *, inM, n);
1430         NEW_ARR_A(ir_node *, inD, n);
1431         NEW_ARR_A(int, idx, n);
1432
1433         /* Prepare: Collect all Store nodes.  We must do this
1434            first because we otherwise may loose a store when exchanging its
1435            memory Proj.
1436          */
1437         for (i = n - 1; i >= 0; --i) {
1438                 ir_node *store;
1439
1440                 projMs[i] = get_Phi_pred(phi, i);
1441                 assert(is_Proj(projMs[i]));
1442
1443                 store = get_Proj_pred(projMs[i]);
1444                 info  = (ldst_info_t*)get_irn_link(store);
1445
1446                 inM[i] = get_Store_mem(store);
1447                 inD[i] = get_Store_value(store);
1448                 idx[i] = info->exc_idx;
1449         }
1450         block = get_nodes_block(phi);
1451
1452         /* second step: create a new memory Phi */
1453         phiM = new_rd_Phi(get_irn_dbg_info(phi), block, n, inM, mode_M);
1454
1455         /* third step: create a new data Phi */
1456         phiD = new_rd_Phi(get_irn_dbg_info(phi), block, n, inD, mode);
1457
1458         /* rewire memory and kill the node */
1459         for (i = n - 1; i >= 0; --i) {
1460                 ir_node *proj  = projMs[i];
1461
1462                 if (is_Proj(proj)) {
1463                         ir_node *store = get_Proj_pred(proj);
1464                         exchange(proj, inM[i]);
1465                         kill_node(store);
1466                 }
1467         }
1468
1469         /* fourth step: create the Store */
1470         store = new_rd_Store(db, block, phiM, ptr, phiD, cons_none);
1471 #ifdef DO_CACHEOPT
1472         co_set_irn_name(store, co_get_irn_ident(old_store));
1473 #endif
1474
1475         projM = new_rd_Proj(NULL, store, mode_M, pn_Store_M);
1476
1477         info = get_ldst_info(store, &wenv->obst);
1478         info->projs[pn_Store_M] = projM;
1479
1480         /* fifths step: repair exception flow */
1481         if (exc) {
1482                 ir_node *projX = new_rd_Proj(NULL, store, mode_X, pn_Store_X_except);
1483
1484                 info->projs[pn_Store_X_except] = projX;
1485                 info->exc_block                = exc;
1486                 info->exc_idx                  = idx[0];
1487
1488                 for (i = 0; i < n; ++i) {
1489                         set_Block_cfgpred(exc, idx[i], projX);
1490                 }
1491
1492                 if (n > 1) {
1493                         /* the exception block should be optimized as some inputs are identical now */
1494                 }
1495
1496                 res |= CF_CHANGED;
1497         }
1498
1499         /* sixth step: replace old Phi */
1500         exchange(phi, projM);
1501
1502         return res | DF_CHANGED;
1503 }  /* optimize_phi */
1504
1505 static int optimize_conv_load(ir_node *conv)
1506 {
1507         ir_node *op = get_Conv_op(conv);
1508         if (!is_Proj(op))
1509                 return 0;
1510         if (has_multiple_users(op))
1511                 return 0;
1512         /* shrink mode of load if possible. */
1513         ir_node *load = get_Proj_pred(op);
1514         if (!is_Load(load))
1515                 return 0;
1516
1517         /* only do it if we are the only user (otherwise the risk is too
1518          * great that we end up with 2 loads instead of one). */
1519         ir_mode *mode      = get_irn_mode(conv);
1520         ir_mode *load_mode = get_Load_mode(load);
1521         int      bits_diff
1522                 = get_mode_size_bits(load_mode) - get_mode_size_bits(mode);
1523         if (mode_is_float(load_mode) || mode_is_float(mode) || bits_diff < 0)
1524             return 0;
1525
1526         if (be_get_backend_param()->byte_order_big_endian) {
1527                 if (bits_diff % 8 != 0)
1528                         return 0;
1529                 ir_graph *irg   = get_irn_irg(conv);
1530                 ir_node  *ptr   = get_Load_ptr(load);
1531                 ir_mode  *mode  = get_irn_mode(ptr);
1532                 ir_node  *delta = new_r_Const_long(irg, mode, bits_diff/8);
1533                 ir_node  *block = get_nodes_block(load);
1534                 ir_node  *add   = new_r_Add(block, ptr, delta, mode);
1535                 set_Load_ptr(load, add);
1536         }
1537         set_Load_mode(load, mode);
1538         set_irn_mode(op, mode);
1539         exchange(conv, op);
1540         return DF_CHANGED;
1541 }
1542
1543 /**
1544  * walker, do the optimizations
1545  */
1546 static void do_load_store_optimize(ir_node *n, void *env)
1547 {
1548         walk_env_t *wenv = (walk_env_t*)env;
1549
1550         switch (get_irn_opcode(n)) {
1551
1552         case iro_Load:
1553                 wenv->changes |= optimize_load(n);
1554                 break;
1555
1556         case iro_Store:
1557                 wenv->changes |= optimize_store(n);
1558                 break;
1559
1560         case iro_Phi:
1561                 wenv->changes |= optimize_phi(n, wenv);
1562                 break;
1563
1564         case iro_Conv:
1565                 wenv->changes |= optimize_conv_load(n);
1566                 break;
1567
1568         default:
1569                 break;
1570         }
1571 }  /* do_load_store_optimize */
1572
1573 /** A scc. */
1574 typedef struct scc {
1575         ir_node *head;      /**< the head of the list */
1576 } scc;
1577
1578 /** A node entry. */
1579 typedef struct node_entry {
1580         unsigned DFSnum;    /**< the DFS number of this node */
1581         unsigned low;       /**< the low number of this node */
1582         int      in_stack;  /**< flag, set if the node is on the stack */
1583         ir_node  *next;     /**< link to the next node the the same scc */
1584         scc      *pscc;     /**< the scc of this node */
1585         unsigned POnum;     /**< the post order number for blocks */
1586 } node_entry;
1587
1588 /** A loop entry. */
1589 typedef struct loop_env {
1590         ir_nodehashmap_t map;
1591         struct obstack   obst;
1592         ir_node          **stack;      /**< the node stack */
1593         size_t           tos;          /**< tos index */
1594         unsigned         nextDFSnum;   /**< the current DFS number */
1595         unsigned         POnum;        /**< current post order number */
1596
1597         unsigned         changes;      /**< a bitmask of graph changes */
1598 } loop_env;
1599
1600 /**
1601 * Gets the node_entry of a node
1602 */
1603 static node_entry *get_irn_ne(ir_node *irn, loop_env *env)
1604 {
1605         node_entry *e = ir_nodehashmap_get(node_entry, &env->map, irn);
1606
1607         if (e == NULL) {
1608                 e = OALLOC(&env->obst, node_entry);
1609                 memset(e, 0, sizeof(*e));
1610                 ir_nodehashmap_insert(&env->map, irn, e);
1611         }
1612         return e;
1613 }  /* get_irn_ne */
1614
1615 /**
1616  * Push a node onto the stack.
1617  *
1618  * @param env   the loop environment
1619  * @param n     the node to push
1620  */
1621 static void push(loop_env *env, ir_node *n)
1622 {
1623         node_entry *e;
1624
1625         if (env->tos == ARR_LEN(env->stack)) {
1626                 size_t nlen = ARR_LEN(env->stack) * 2;
1627                 ARR_RESIZE(ir_node *, env->stack, nlen);
1628         }
1629         env->stack[env->tos++] = n;
1630         e = get_irn_ne(n, env);
1631         e->in_stack = 1;
1632 }  /* push */
1633
1634 /**
1635  * pop a node from the stack
1636  *
1637  * @param env   the loop environment
1638  *
1639  * @return  The topmost node
1640  */
1641 static ir_node *pop(loop_env *env)
1642 {
1643         ir_node *n = env->stack[--env->tos];
1644         node_entry *e = get_irn_ne(n, env);
1645
1646         e->in_stack = 0;
1647         return n;
1648 }  /* pop */
1649
1650 /**
1651  * Check if irn is a region constant.
1652  * The block or irn must strictly dominate the header block.
1653  *
1654  * @param irn           the node to check
1655  * @param header_block  the header block of the induction variable
1656  */
1657 static int is_rc(ir_node *irn, ir_node *header_block)
1658 {
1659         ir_node *block = get_nodes_block(irn);
1660
1661         return (block != header_block) && block_dominates(block, header_block);
1662 }  /* is_rc */
1663
1664 typedef struct phi_entry phi_entry;
1665 struct phi_entry {
1666         ir_node   *phi;    /**< A phi with a region const memory. */
1667         int       pos;     /**< The position of the region const memory */
1668         ir_node   *load;   /**< the newly created load for this phi */
1669         phi_entry *next;
1670 };
1671
1672 /**
1673  * An entry in the avail set.
1674  */
1675 typedef struct avail_entry_t {
1676         ir_node *ptr;   /**< the address pointer */
1677         ir_mode *mode;  /**< the load mode */
1678         ir_node *load;  /**< the associated Load */
1679 } avail_entry_t;
1680
1681 /**
1682  * Compare two avail entries.
1683  */
1684 static int cmp_avail_entry(const void *elt, const void *key, size_t size)
1685 {
1686         const avail_entry_t *a = (const avail_entry_t*)elt;
1687         const avail_entry_t *b = (const avail_entry_t*)key;
1688         (void) size;
1689
1690         return a->ptr != b->ptr || a->mode != b->mode;
1691 }  /* cmp_avail_entry */
1692
1693 /**
1694  * Calculate the hash value of an avail entry.
1695  */
1696 static unsigned hash_cache_entry(const avail_entry_t *entry)
1697 {
1698         return get_irn_idx(entry->ptr) * 9 + hash_ptr(entry->mode);
1699 }  /* hash_cache_entry */
1700
1701 /**
1702  * Move loops out of loops if possible.
1703  *
1704  * @param pscc   the loop described by an SCC
1705  * @param env    the loop environment
1706  */
1707 static void move_loads_out_of_loops(scc *pscc, loop_env *env)
1708 {
1709         ir_node   *phi, *load, *next, *other, *next_other;
1710         int       j;
1711         phi_entry *phi_list = NULL;
1712         set       *avail;
1713
1714         /* collect all outer memories */
1715         for (phi = pscc->head; phi != NULL; phi = next) {
1716                 node_entry *ne = get_irn_ne(phi, env);
1717                 next = ne->next;
1718
1719                 /* check all memory Phi's */
1720                 if (! is_Phi(phi))
1721                         continue;
1722
1723                 assert(get_irn_mode(phi) == mode_M && "DFS return non-memory Phi");
1724
1725                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1726                         ir_node    *pred = get_irn_n(phi, j);
1727                         node_entry *pe   = get_irn_ne(pred, env);
1728
1729                         if (pe->pscc != ne->pscc) {
1730                                 /* not in the same SCC, is region const */
1731                                 phi_entry *pe = OALLOC(&env->obst, phi_entry);
1732
1733                                 pe->phi  = phi;
1734                                 pe->pos  = j;
1735                                 pe->next = phi_list;
1736                                 phi_list = pe;
1737                         }
1738                 }
1739         }
1740         /* no Phis no fun */
1741         assert(phi_list != NULL && "DFS found a loop without Phi");
1742
1743         /* for now, we cannot handle more than one input (only reducible cf) */
1744         if (phi_list->next != NULL)
1745                 return;
1746
1747         avail = new_set(cmp_avail_entry, 8);
1748
1749         for (load = pscc->head; load; load = next) {
1750                 ir_mode *load_mode;
1751                 node_entry *ne = get_irn_ne(load, env);
1752                 next = ne->next;
1753
1754                 if (is_Load(load)) {
1755                         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
1756                         ir_node     *ptr = get_Load_ptr(load);
1757
1758                         /* for now, we cannot handle Loads with exceptions */
1759                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1760                                 continue;
1761
1762                         /* for now, we can only move Load(Global) */
1763                         if (! is_SymConst_addr_ent(ptr))
1764                                 continue;
1765                         load_mode = get_Load_mode(load);
1766                         for (other = pscc->head; other != NULL; other = next_other) {
1767                                 node_entry *ne = get_irn_ne(other, env);
1768                                 next_other = ne->next;
1769
1770                                 if (is_Store(other)) {
1771                                         ir_alias_relation rel = get_alias_relation(
1772                                                 get_Store_ptr(other),
1773                                                 get_irn_mode(get_Store_value(other)),
1774                                                 ptr, load_mode);
1775                                         /* if the might be an alias, we cannot pass this Store */
1776                                         if (rel != ir_no_alias)
1777                                                 break;
1778                                 }
1779                                 /* only Phis and pure Calls are allowed here, so ignore them */
1780                         }
1781                         if (other == NULL) {
1782                                 ldst_info_t *ninfo = NULL;
1783                                 phi_entry   *pe;
1784                                 dbg_info    *db;
1785
1786                                 /* yep, no aliasing Store found, Load can be moved */
1787                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1788
1789                                 db   = get_irn_dbg_info(load);
1790                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1791                                         int     pos   = pe->pos;
1792                                         ir_node *phi  = pe->phi;
1793                                         ir_node *blk  = get_nodes_block(phi);
1794                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1795                                         ir_node *irn, *mem;
1796                                         avail_entry_t entry, *res;
1797
1798                                         entry.ptr  = ptr;
1799                                         entry.mode = load_mode;
1800                                         res = set_find(avail_entry_t, avail, &entry, sizeof(entry), hash_cache_entry(&entry));
1801                                         if (res != NULL) {
1802                                                 irn = res->load;
1803                                         } else {
1804                                                 irn = new_rd_Load(db, pred, get_Phi_pred(phi, pos), ptr, load_mode, cons_none);
1805                                                 entry.load = irn;
1806                                                 (void)set_insert(avail_entry_t, avail, &entry, sizeof(entry), hash_cache_entry(&entry));
1807                                                 DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1808                                         }
1809                                         pe->load = irn;
1810                                         ninfo = get_ldst_info(irn, &env->obst);
1811
1812                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(irn, mode_M, pn_Load_M);
1813                                         if (res == NULL) {
1814                                                 /* irn is from cache, so do not set phi pred again.
1815                                                  * There might be other Loads between phi and irn already.
1816                                                  */
1817                                                 set_Phi_pred(phi, pos, mem);
1818                                         }
1819
1820                                         ninfo->projs[pn_Load_res] = new_r_Proj(irn, load_mode, pn_Load_res);
1821                                 }
1822
1823                                 /* now kill the old Load */
1824                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1825                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1826
1827                                 env->changes |= DF_CHANGED;
1828                         }
1829                 }
1830         }
1831         del_set(avail);
1832 }  /* move_loads_out_of_loops */
1833
1834 /**
1835  * Process a loop SCC.
1836  *
1837  * @param pscc  the SCC
1838  * @param env   the loop environment
1839  */
1840 static void process_loop(scc *pscc, loop_env *env)
1841 {
1842         ir_node *irn, *next, *header = NULL;
1843         node_entry *b, *h = NULL;
1844         int j, only_phi, num_outside, process = 0;
1845         ir_node *out_rc;
1846
1847         /* find the header block for this scc */
1848         for (irn = pscc->head; irn; irn = next) {
1849                 node_entry *e = get_irn_ne(irn, env);
1850                 ir_node *block = get_nodes_block(irn);
1851
1852                 next = e->next;
1853                 b = get_irn_ne(block, env);
1854
1855                 if (header != NULL) {
1856                         if (h->POnum < b->POnum) {
1857                                 header = block;
1858                                 h      = b;
1859                         }
1860                 } else {
1861                         header = block;
1862                         h      = b;
1863                 }
1864         }
1865
1866         /* check if this scc contains only Phi, Loads or Stores nodes */
1867         only_phi    = 1;
1868         num_outside = 0;
1869         out_rc      = NULL;
1870         for (irn = pscc->head; irn; irn = next) {
1871                 node_entry *e = get_irn_ne(irn, env);
1872
1873                 next = e->next;
1874                 switch (get_irn_opcode(irn)) {
1875                 case iro_Call:
1876                         if (is_Call_pure(irn)) {
1877                                 /* pure calls can be treated like loads */
1878                                 only_phi = 0;
1879                                 break;
1880                         }
1881                         /* non-pure calls must be handle like may-alias Stores */
1882                         goto fail;
1883                 case iro_CopyB:
1884                         /* cannot handle CopyB yet */
1885                         goto fail;
1886                 case iro_Load:
1887                         process = 1;
1888                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1889                                 /* cannot handle loops with volatile Loads */
1890                                 goto fail;
1891                         }
1892                         only_phi = 0;
1893                         break;
1894                 case iro_Store:
1895                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1896                                 /* cannot handle loops with volatile Stores */
1897                                 goto fail;
1898                         }
1899                         only_phi = 0;
1900                         break;
1901                 default:
1902                         only_phi = 0;
1903                         break;
1904                 case iro_Phi:
1905                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1906                                 ir_node *pred  = get_irn_n(irn, j);
1907                                 node_entry *pe = get_irn_ne(pred, env);
1908
1909                                 if (pe->pscc != e->pscc) {
1910                                         /* not in the same SCC, must be a region const */
1911                                         if (! is_rc(pred, header)) {
1912                                                 /* not a memory loop */
1913                                                 goto fail;
1914                                         }
1915                                         if (out_rc == NULL) {
1916                                                 /* first region constant */
1917                                                 out_rc = pred;
1918                                                 ++num_outside;
1919                                         } else if (out_rc != pred) {
1920                                                 /* another region constant */
1921                                                 ++num_outside;
1922                                         }
1923                                 }
1924                         }
1925                         break;
1926                 }
1927         }
1928         if (! process)
1929                 goto fail;
1930
1931         /* found a memory loop */
1932         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1933         if (only_phi && num_outside == 1) {
1934                 /* a phi cycle with only one real predecessor can be collapsed */
1935                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1936
1937                 for (irn = pscc->head; irn; irn = next) {
1938                         node_entry *e = get_irn_ne(irn, env);
1939                         next = e->next;
1940                         exchange(irn, out_rc);
1941                 }
1942                 env->changes |= DF_CHANGED;
1943                 return;
1944         }
1945
1946 #ifdef DEBUG_libfirm
1947         for (irn = pscc->head; irn; irn = next) {
1948                 node_entry *e = get_irn_ne(irn, env);
1949                 next = e->next;
1950                 DB((dbg, LEVEL_2, " %+F,", irn));
1951         }
1952         DB((dbg, LEVEL_2, "\n"));
1953 #endif
1954         move_loads_out_of_loops(pscc, env);
1955
1956 fail:
1957         ;
1958 }  /* process_loop */
1959
1960 /**
1961  * Process a SCC.
1962  *
1963  * @param pscc  the SCC
1964  * @param env   the loop environment
1965  */
1966 static void process_scc(scc *pscc, loop_env *env)
1967 {
1968         ir_node *head = pscc->head;
1969         node_entry *e = get_irn_ne(head, env);
1970
1971 #ifdef DEBUG_libfirm
1972         {
1973                 ir_node *irn, *next;
1974
1975                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1976                 for (irn = pscc->head; irn; irn = next) {
1977                         node_entry *e = get_irn_ne(irn, env);
1978
1979                         next = e->next;
1980
1981                         DB((dbg, LEVEL_4, " %+F,", irn));
1982                 }
1983                 DB((dbg, LEVEL_4, "\n"));
1984         }
1985 #endif
1986
1987         if (e->next != NULL) {
1988                 /* this SCC has more than one member */
1989                 process_loop(pscc, env);
1990         }
1991 }  /* process_scc */
1992
1993 /**
1994  * Do Tarjan's SCC algorithm and drive load/store optimization.
1995  *
1996  * @param irn  start at this node
1997  * @param env  the loop environment
1998  */
1999 static void dfs(ir_node *irn, loop_env *env)
2000 {
2001         int i, n;
2002         node_entry *node = get_irn_ne(irn, env);
2003
2004         mark_irn_visited(irn);
2005
2006         node->DFSnum = env->nextDFSnum++;
2007         node->low    = node->DFSnum;
2008         push(env, irn);
2009
2010         /* handle preds */
2011         if (is_Phi(irn) || is_Sync(irn)) {
2012                 n = get_irn_arity(irn);
2013                 for (i = 0; i < n; ++i) {
2014                         ir_node *pred = get_irn_n(irn, i);
2015                         node_entry *o = get_irn_ne(pred, env);
2016
2017                         if (!irn_visited(pred)) {
2018                                 dfs(pred, env);
2019                                 node->low = MIN(node->low, o->low);
2020                         }
2021                         if (o->DFSnum < node->DFSnum && o->in_stack)
2022                                 node->low = MIN(o->DFSnum, node->low);
2023                 }
2024         } else if (is_fragile_op(irn)) {
2025                 ir_node *pred = get_memop_mem(irn);
2026                 node_entry *o = get_irn_ne(pred, env);
2027
2028                 if (!irn_visited(pred)) {
2029                         dfs(pred, env);
2030                         node->low = MIN(node->low, o->low);
2031                 }
2032                 if (o->DFSnum < node->DFSnum && o->in_stack)
2033                         node->low = MIN(o->DFSnum, node->low);
2034         } else if (is_Proj(irn)) {
2035                 ir_node *pred = get_Proj_pred(irn);
2036                 node_entry *o = get_irn_ne(pred, env);
2037
2038                 if (!irn_visited(pred)) {
2039                         dfs(pred, env);
2040                         node->low = MIN(node->low, o->low);
2041                 }
2042                 if (o->DFSnum < node->DFSnum && o->in_stack)
2043                         node->low = MIN(o->DFSnum, node->low);
2044         }
2045         else {
2046                  /* IGNORE predecessors */
2047         }
2048
2049         if (node->low == node->DFSnum) {
2050                 scc *pscc = OALLOC(&env->obst, scc);
2051                 ir_node *x;
2052
2053                 pscc->head = NULL;
2054                 do {
2055                         node_entry *e;
2056
2057                         x = pop(env);
2058                         e = get_irn_ne(x, env);
2059                         e->pscc    = pscc;
2060                         e->next    = pscc->head;
2061                         pscc->head = x;
2062                 } while (x != irn);
2063
2064                 process_scc(pscc, env);
2065         }
2066 }  /* dfs */
2067
2068 /**
2069  * Do the DFS on the memory edges a graph.
2070  *
2071  * @param irg  the graph to process
2072  * @param env  the loop environment
2073  */
2074 static void do_dfs(ir_graph *irg, loop_env *env)
2075 {
2076         ir_node  *endblk, *end;
2077         int      i;
2078
2079         inc_irg_visited(irg);
2080
2081         /* visit all memory nodes */
2082         endblk = get_irg_end_block(irg);
2083         for (i = get_Block_n_cfgpreds(endblk) - 1; i >= 0; --i) {
2084                 ir_node *pred = get_Block_cfgpred(endblk, i);
2085
2086                 pred = skip_Proj(pred);
2087                 if (is_Return(pred)) {
2088                         dfs(get_Return_mem(pred), env);
2089                 } else if (is_Raise(pred)) {
2090                         dfs(get_Raise_mem(pred), env);
2091                 } else if (is_fragile_op(pred)) {
2092                         dfs(get_memop_mem(pred), env);
2093                 } else if (is_Bad(pred)) {
2094                         /* ignore non-optimized block predecessor */
2095                 } else {
2096                         assert(0 && "Unknown EndBlock predecessor");
2097                 }
2098         }
2099
2100         /* visit the keep-alives */
2101         end = get_irg_end(irg);
2102         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
2103                 ir_node *ka = get_End_keepalive(end, i);
2104
2105                 if (is_Phi(ka) && !irn_visited(ka))
2106                         dfs(ka, env);
2107         }
2108 }  /* do_dfs */
2109
2110 /**
2111  * Optimize Loads/Stores in loops.
2112  *
2113  * @param irg  the graph
2114  */
2115 static int optimize_loops(ir_graph *irg)
2116 {
2117         loop_env env;
2118
2119         env.stack         = NEW_ARR_F(ir_node *, 128);
2120         env.tos           = 0;
2121         env.nextDFSnum    = 0;
2122         env.POnum         = 0;
2123         env.changes       = 0;
2124         ir_nodehashmap_init(&env.map);
2125         obstack_init(&env.obst);
2126
2127         /* calculate the SCC's and drive loop optimization. */
2128         do_dfs(irg, &env);
2129
2130         DEL_ARR_F(env.stack);
2131         obstack_free(&env.obst, NULL);
2132         ir_nodehashmap_destroy(&env.map);
2133
2134         return env.changes;
2135 }  /* optimize_loops */
2136
2137 void optimize_load_store(ir_graph *irg)
2138 {
2139         walk_env_t env;
2140
2141         assure_irg_properties(irg,
2142                 IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE
2143                 | IR_GRAPH_PROPERTY_CONSISTENT_OUT_EDGES
2144                 | IR_GRAPH_PROPERTY_NO_CRITICAL_EDGES
2145                 | IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE
2146                 | IR_GRAPH_PROPERTY_CONSISTENT_ENTITY_USAGE);
2147
2148         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
2149
2150         assert(get_irg_pinned(irg) != op_pin_state_floats &&
2151                 "LoadStore optimization needs pinned graph");
2152
2153         if (get_opt_alias_analysis()) {
2154                 assure_irp_globals_entity_usage_computed();
2155         }
2156
2157         obstack_init(&env.obst);
2158         env.changes = 0;
2159
2160         /* init the links, then collect Loads/Stores/Proj's in lists */
2161         master_visited = 0;
2162         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
2163
2164         /* now we have collected enough information, optimize */
2165         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
2166
2167         env.changes |= optimize_loops(irg);
2168
2169         obstack_free(&env.obst, NULL);
2170
2171         confirm_irg_properties(irg,
2172                 env.changes
2173                 ? env.changes & CF_CHANGED
2174                         ? IR_GRAPH_PROPERTIES_NONE
2175                         : IR_GRAPH_PROPERTIES_CONTROL_FLOW
2176                 : IR_GRAPH_PROPERTIES_ALL);
2177 }
2178
2179 ir_graph_pass_t *optimize_load_store_pass(const char *name)
2180 {
2181         return def_graph_pass(name ? name : "ldst", optimize_load_store);
2182 }  /* optimize_load_store_pass */