2 * Copyright (C) 1995-2007 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Load/Store optimizations.
23 * @author Michael Beck
32 #include "iroptimize.h"
34 #include "irgraph_t.h"
42 #include "dbginfo_t.h"
43 #include "iropt_dbg.h"
49 #include "opt_polymorphy.h"
54 #include "cacheopt/cachesim.h"
58 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
60 #define MAX_PROJ IMAX(pn_Load_max, pn_Store_max)
63 DF_CHANGED = 1, /**< data flow changed */
64 CF_CHANGED = 2, /**< control flow changed */
70 typedef struct _walk_env_t {
71 struct obstack obst; /**< list of all stores */
72 unsigned changes; /**< a bitmask of graph changes */
76 * flags for Load/Store
79 LDST_VISITED = 1 /**< if set, this Load/Store is already visited */
82 /** A Load/Store info. */
83 typedef struct _ldst_info_t {
84 ir_node *projs[MAX_PROJ]; /**< list of Proj's of this node */
85 ir_node *exc_block; /**< the exception block if available */
86 int exc_idx; /**< predecessor index in the exception block */
87 unsigned flags; /**< flags */
88 unsigned visited; /**< visited counter for breaking loops */
92 * flags for control flow.
95 BLOCK_HAS_COND = 1, /**< Block has conditional control flow */
96 BLOCK_HAS_EXC = 2 /**< Block has exceptional control flow */
102 typedef struct _block_info_t {
103 unsigned flags; /**< flags for the block */
106 /** the master visited flag for loop detection. */
107 static unsigned master_visited = 0;
109 #define INC_MASTER() ++master_visited
110 #define MARK_NODE(info) (info)->visited = master_visited
111 #define NODE_VISITED(info) (info)->visited >= master_visited
114 * get the Load/Store info of a node
116 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env) {
117 ldst_info_t *info = get_irn_link(node);
120 info = obstack_alloc(&env->obst, sizeof(*info));
121 memset(info, 0, sizeof(*info));
122 set_irn_link(node, info);
125 } /* get_ldst_info */
128 * get the Block info of a node
130 static block_info_t *get_block_info(ir_node *node, walk_env_t *env) {
131 block_info_t *info = get_irn_link(node);
134 info = obstack_alloc(&env->obst, sizeof(*info));
135 memset(info, 0, sizeof(*info));
136 set_irn_link(node, info);
139 } /* get_block_info */
142 * update the projection info for a Load/Store
144 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
146 long nr = get_Proj_proj(proj);
148 assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
150 if (info->projs[nr]) {
151 /* there is already one, do CSE */
152 exchange(proj, info->projs[nr]);
156 info->projs[nr] = proj;
162 * update the exception block info for a Load/Store node.
164 * @param info the load/store info struct
165 * @param block the exception handler block for this load/store
166 * @param pos the control flow input of the block
168 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
170 assert(info->exc_block == NULL && "more than one exception block found");
172 info->exc_block = block;
177 /** Return the number of uses of an address node */
178 #define get_irn_n_uses(adr) get_irn_n_edges(adr)
181 * walker, collects all Load/Store/Proj nodes
183 * walks from Start -> End
185 static void collect_nodes(ir_node *node, void *env)
187 ir_op *op = get_irn_op(node);
188 ir_node *pred, *blk, *pred_blk;
189 ldst_info_t *ldst_info;
190 walk_env_t *wenv = env;
196 pred = get_Proj_pred(node);
197 op = get_irn_op(pred);
200 ldst_info = get_ldst_info(pred, wenv);
202 wenv->changes |= update_projs(ldst_info, node);
204 if ((ldst_info->flags & LDST_VISITED) == 0) {
205 adr = get_Load_ptr(pred);
206 ldst_info->flags |= LDST_VISITED;
210 * Place the Proj's to the same block as the
211 * predecessor Load. This is always ok and prevents
212 * "non-SSA" form after optimizations if the Proj
213 * is in a wrong block.
215 blk = get_nodes_block(node);
216 pred_blk = get_nodes_block(pred);
217 if (blk != pred_blk) {
218 wenv->changes |= DF_CHANGED;
219 set_nodes_block(node, pred_blk);
221 } else if (op == op_Store) {
222 ldst_info = get_ldst_info(pred, wenv);
224 wenv->changes |= update_projs(ldst_info, node);
226 if ((ldst_info->flags & LDST_VISITED) == 0) {
227 adr = get_Store_ptr(pred);
228 ldst_info->flags |= LDST_VISITED;
232 * Place the Proj's to the same block as the
233 * predecessor Store. This is always ok and prevents
234 * "non-SSA" form after optimizations if the Proj
235 * is in a wrong block.
237 blk = get_nodes_block(node);
238 pred_blk = get_nodes_block(pred);
239 if (blk != pred_blk) {
240 wenv->changes |= DF_CHANGED;
241 set_nodes_block(node, pred_blk);
244 } else if (op == op_Block) {
247 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
249 block_info_t *bl_info;
251 pred = skip_Proj(get_Block_cfgpred(node, i));
253 /* ignore Bad predecessors, they will be removed later */
257 pred_block = get_nodes_block(pred);
258 bl_info = get_block_info(pred_block, wenv);
260 if (is_fragile_op(pred))
261 bl_info->flags |= BLOCK_HAS_EXC;
262 else if (is_irn_forking(pred))
263 bl_info->flags |= BLOCK_HAS_COND;
265 if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
266 ldst_info = get_ldst_info(pred, wenv);
268 wenv->changes |= update_exc(ldst_info, node, i);
272 } /* collect_nodes */
275 * Returns an entity if the address ptr points to a constant one.
277 * @param ptr the address
279 * @return an entity or NULL
281 static ir_entity *find_constant_entity(ir_node *ptr)
284 ir_op *op = get_irn_op(ptr);
286 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
287 ir_entity *ent = get_SymConst_entity(ptr);
288 if (variability_constant == get_entity_variability(ent))
291 } else if (op == op_Sel) {
292 ir_entity *ent = get_Sel_entity(ptr);
293 ir_type *tp = get_entity_owner(ent);
295 /* Do not fiddle with polymorphism. */
296 if (is_Class_type(get_entity_owner(ent)) &&
297 ((get_entity_n_overwrites(ent) != 0) ||
298 (get_entity_n_overwrittenby(ent) != 0) ) )
301 if (is_Array_type(tp)) {
305 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
307 tarval *tlower, *tupper;
308 ir_node *index = get_Sel_index(ptr, i);
309 tarval *tv = computed_value(index);
311 /* check if the index is constant */
312 if (tv == tarval_bad)
315 bound = get_array_lower_bound(tp, i);
316 tlower = computed_value(bound);
317 bound = get_array_upper_bound(tp, i);
318 tupper = computed_value(bound);
320 if (tlower == tarval_bad || tupper == tarval_bad)
323 if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
325 if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
328 /* ok, bounds check finished */
332 if (variability_constant == get_entity_variability(ent))
336 ptr = get_Sel_ptr(ptr);
340 } /* find_constant_entity */
343 * Return the Selection index of a Sel node from dimension n
345 static long get_Sel_array_index_long(ir_node *n, int dim) {
346 ir_node *index = get_Sel_index(n, dim);
347 assert(get_irn_op(index) == op_Const);
348 return get_tarval_long(get_Const_tarval(index));
349 } /* get_Sel_array_index_long */
352 * Returns the accessed component graph path for an
353 * node computing an address.
355 * @param ptr the node computing the address
356 * @param depth current depth in steps upward from the root
359 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
360 compound_graph_path *res = NULL;
361 ir_entity *root, *field;
364 if (get_irn_op(ptr) == op_SymConst) {
365 /* a SymConst. If the depth is 0, this is an access to a global
366 * entity and we don't need a component path, else we know
367 * at least it's length.
369 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
370 root = get_SymConst_entity(ptr);
371 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
373 assert(get_irn_op(ptr) == op_Sel);
374 /* it's a Sel, go up until we find the root */
375 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
377 /* fill up the step in the path at the current position */
378 field = get_Sel_entity(ptr);
379 path_len = get_compound_graph_path_length(res);
380 pos = path_len - depth - 1;
381 set_compound_graph_path_node(res, pos, field);
383 if (is_Array_type(get_entity_owner(field))) {
384 assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
385 set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
389 } /* rec_get_accessed_path */
391 /** Returns an access path or NULL. The access path is only
392 * valid, if the graph is in phase_high and _no_ address computation is used.
394 static compound_graph_path *get_accessed_path(ir_node *ptr) {
395 return rec_get_accessed_path(ptr, 0);
396 } /* get_accessed_path */
399 static void reduce_adr_usage(ir_node *ptr);
402 * Update a Load that may lost it's usage.
404 static void handle_load_update(ir_node *load) {
405 ldst_info_t *info = get_irn_link(load);
407 /* do NOT touch volatile loads for now */
408 if (get_Load_volatility(load) == volatility_is_volatile)
411 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
412 ir_node *ptr = get_Load_ptr(load);
413 ir_node *mem = get_Load_mem(load);
415 /* a Load which value is neither used nor exception checked, remove it */
416 exchange(info->projs[pn_Load_M], mem);
417 exchange(load, new_Bad());
418 reduce_adr_usage(ptr);
420 } /* handle_load_update */
423 * A Use of an address node is vanished. Check if this was a Proj
424 * node and update the counters.
426 static void reduce_adr_usage(ir_node *ptr) {
428 if (get_irn_n_edges(ptr) <= 0) {
429 /* this Proj is dead now */
430 ir_node *pred = get_Proj_pred(ptr);
433 ldst_info_t *info = get_irn_link(pred);
434 info->projs[get_Proj_proj(ptr)] = NULL;
436 /* this node lost it's result proj, handle that */
437 handle_load_update(pred);
441 } /* reduce_adr_usage */
444 * Check, if an already existing value of mode old_mode can be converted
445 * into the needed one new_mode without loss.
447 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
448 if (old_mode == new_mode)
451 /* if both modes are two-complement ones, we can always convert the
452 Stored value into the needed one. */
453 if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
454 get_mode_arithmetic(old_mode) == irma_twos_complement &&
455 get_mode_arithmetic(new_mode) == irma_twos_complement)
458 } /* can_use_stored_value */
461 * Follow the memory chain as long as there are only Loads
462 * and alias free Stores and try to replace current Load or Store
463 * by a previous ones.
464 * Note that in unreachable loops it might happen that we reach
465 * load again, as well as we can fall into a cycle.
466 * We break such cycles using a special visited flag.
468 * INC_MASTER() must be called before dive into
470 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
472 ldst_info_t *info = get_irn_link(load);
474 ir_node *ptr = get_Load_ptr(load);
475 ir_node *mem = get_Load_mem(load);
476 ir_mode *load_mode = get_Load_mode(load);
478 for (pred = curr; load != pred; ) {
479 ldst_info_t *pred_info = get_irn_link(pred);
482 * BEWARE: one might think that checking the modes is useless, because
483 * if the pointers are identical, they refer to the same object.
484 * This is only true in strong typed languages, not in C were the following
485 * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
487 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
488 can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
490 * a Load immediately after a Store -- a read after write.
491 * We may remove the Load, if both Load & Store does not have an exception handler
492 * OR they are in the same block. In the latter case the Load cannot
493 * throw an exception when the previous Store was quiet.
495 * Why we need to check for Store Exception? If the Store cannot
496 * be executed (ROM) the exception handler might simply jump into
498 * We could make it a little bit better if we would know that the exception
499 * handler of the Store jumps directly to the end...
501 if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
502 get_nodes_block(load) == get_nodes_block(pred)) {
503 ir_node *value = get_Store_value(pred);
505 DBG_OPT_RAW(load, value);
507 /* add an convert if needed */
508 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
509 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
512 if (info->projs[pn_Load_M])
513 exchange(info->projs[pn_Load_M], mem);
516 if (info->projs[pn_Load_X_except]) {
517 exchange( info->projs[pn_Load_X_except], new_Bad());
521 if (info->projs[pn_Load_res])
522 exchange(info->projs[pn_Load_res], value);
524 exchange(load, new_Bad());
525 reduce_adr_usage(ptr);
526 return res | DF_CHANGED;
528 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
529 can_use_stored_value(get_Load_mode(pred), load_mode)) {
531 * a Load after a Load -- a read after read.
532 * We may remove the second Load, if it does not have an exception handler
533 * OR they are in the same block. In the later case the Load cannot
534 * throw an exception when the previous Load was quiet.
536 * Here, there is no need to check if the previous Load has an exception
537 * hander because they would have exact the same exception...
539 if (info->projs[pn_Load_X_except] == NULL || get_nodes_block(load) == get_nodes_block(pred)) {
542 DBG_OPT_RAR(load, pred);
544 /* the result is used */
545 if (info->projs[pn_Load_res]) {
546 if (pred_info->projs[pn_Load_res] == NULL) {
547 /* create a new Proj again */
548 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
550 value = pred_info->projs[pn_Load_res];
552 /* add an convert if needed */
553 if (get_Load_mode(pred) != load_mode) {
554 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
557 exchange(info->projs[pn_Load_res], value);
560 if (info->projs[pn_Load_M])
561 exchange(info->projs[pn_Load_M], mem);
564 if (info->projs[pn_Load_X_except]) {
565 exchange(info->projs[pn_Load_X_except], new_Bad());
569 exchange(load, new_Bad());
570 reduce_adr_usage(ptr);
571 return res |= DF_CHANGED;
575 if (get_irn_op(pred) == op_Store) {
576 /* check if we can pass through this store */
577 ir_alias_relation rel = get_alias_relation(
580 get_irn_mode(get_Store_value(pred)),
582 /* if the might be an alias, we cannot pass this Store */
585 pred = skip_Proj(get_Store_mem(pred));
586 } else if (get_irn_op(pred) == op_Load) {
587 pred = skip_Proj(get_Load_mem(pred));
589 /* follow only Load chains */
593 /* check for cycles */
594 if (NODE_VISITED(pred_info))
596 MARK_NODE(pred_info);
599 if (get_irn_op(pred) == op_Sync) {
602 /* handle all Sync predecessors */
603 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
604 res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
611 } /* follow_Mem_chain */
616 * @param load the Load node
618 static unsigned optimize_load(ir_node *load)
620 ldst_info_t *info = get_irn_link(load);
621 ir_node *mem, *ptr, *new_node;
625 /* do NOT touch volatile loads for now */
626 if (get_Load_volatility(load) == volatility_is_volatile)
629 /* the address of the load to be optimized */
630 ptr = get_Load_ptr(load);
633 * Check if we can remove the exception from a Load:
634 * This can be done, if the address is from an Sel(Alloc) and
635 * the Sel type is a subtype of the allocated type.
637 * This optimizes some often used OO constructs,
638 * like x = new O; x->t;
640 if (info->projs[pn_Load_X_except]) {
642 ir_node *mem = get_Sel_mem(ptr);
644 /* FIXME: works with the current FE, but better use the base */
645 if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
646 /* ok, check the types */
647 ir_entity *ent = get_Sel_entity(ptr);
648 ir_type *s_type = get_entity_type(ent);
649 ir_type *a_type = get_Alloc_type(mem);
651 if (is_SubClass_of(s_type, a_type)) {
652 /* ok, condition met: there can't be an exception because
653 * Alloc guarantees that enough memory was allocated */
655 exchange(info->projs[pn_Load_X_except], new_Bad());
656 info->projs[pn_Load_X_except] = NULL;
660 } else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
661 ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
662 /* simple case: a direct load after an Alloc. Firm Alloc throw
663 * an exception in case of out-of-memory. So, there is no way for an
664 * exception in this load.
665 * This code is constructed by the "exception lowering" in the Jack compiler.
667 exchange(info->projs[pn_Load_X_except], new_Bad());
668 info->projs[pn_Load_X_except] = NULL;
673 /* The mem of the Load. Must still be returned after optimization. */
674 mem = get_Load_mem(load);
676 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
677 /* a Load which value is neither used nor exception checked, remove it */
678 exchange(info->projs[pn_Load_M], mem);
680 exchange(load, new_Bad());
681 reduce_adr_usage(ptr);
682 return res | DF_CHANGED;
685 /* Load from a constant polymorphic field, where we can resolve
687 new_node = transform_node_Load(load);
688 if (new_node != load) {
689 if (info->projs[pn_Load_M]) {
690 exchange(info->projs[pn_Load_M], mem);
691 info->projs[pn_Load_M] = NULL;
693 if (info->projs[pn_Load_X_except]) {
694 exchange(info->projs[pn_Load_X_except], new_Bad());
695 info->projs[pn_Load_X_except] = NULL;
697 if (info->projs[pn_Load_res])
698 exchange(info->projs[pn_Load_res], new_node);
700 exchange(load, new_Bad());
701 reduce_adr_usage(ptr);
702 return res | DF_CHANGED;
705 /* check if we can determine the entity that will be loaded */
706 ent = find_constant_entity(ptr);
708 if ((allocation_static == get_entity_allocation(ent)) &&
709 (visibility_external_allocated != get_entity_visibility(ent))) {
710 /* a static allocation that is not external: there should be NO exception
713 /* no exception, clear the info field as it might be checked later again */
714 if (info->projs[pn_Load_X_except]) {
715 exchange(info->projs[pn_Load_X_except], new_Bad());
716 info->projs[pn_Load_X_except] = NULL;
720 if (variability_constant == get_entity_variability(ent)
721 && is_atomic_entity(ent)) {
722 /* Might not be atomic after
723 lowering of Sels. In this
724 case we could also load, but
725 it's more complicated. */
726 /* more simpler case: we load the content of a constant value:
727 * replace it by the constant itself
731 if (info->projs[pn_Load_M]) {
732 exchange(info->projs[pn_Load_M], mem);
736 if (info->projs[pn_Load_res]) {
737 if (is_atomic_entity(ent)) {
738 ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
741 exchange(info->projs[pn_Load_res], c);
745 exchange(load, new_Bad());
746 reduce_adr_usage(ptr);
748 } else if (variability_constant == get_entity_variability(ent)) {
749 compound_graph_path *path = get_accessed_path(ptr);
754 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
758 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
759 ir_entity *node = get_compound_graph_path_node(path, j);
760 fprintf(stdout, ".%s", get_entity_name(node));
761 if (is_Array_type(get_entity_owner(node)))
762 fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
768 c = get_compound_ent_value_by_path(ent, path);
769 free_compound_graph_path(path);
771 /* printf(" cons: "); DDMN(c); */
773 if (info->projs[pn_Load_M]) {
774 exchange(info->projs[pn_Load_M], mem);
777 if (info->projs[pn_Load_res]) {
778 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
781 exchange(load, new_Bad());
782 reduce_adr_usage(ptr);
785 /* We can not determine a correct access path. E.g., in jack, we load
786 a byte from an object to generate an exception. Happens in test program
788 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
789 get_entity_name(get_irg_entity(current_ir_graph)));
790 printf(" load: "); DDMN(load);
791 printf(" ptr: "); DDMN(ptr);
798 /* Check, if the address of this load is used more than once.
799 * If not, this load cannot be removed in any case. */
800 if (get_irn_n_uses(ptr) <= 1)
804 * follow the memory chain as long as there are only Loads
805 * and try to replace current Load or Store by a previous one.
806 * Note that in unreachable loops it might happen that we reach
807 * load again, as well as we can fall into a cycle.
808 * We break such cycles using a special visited flag.
811 res = follow_Mem_chain(load, skip_Proj(mem));
813 } /* optimize_load */
816 * Check whether a value of mode new_mode would completely overwrite a value
817 * of mode old_mode in memory.
819 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
821 return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
822 } /* is_completely_overwritten */
825 * follow the memory chain as long as there are only Loads and alias free Stores.
827 * INC_MASTER() must be called before dive into
829 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
831 ldst_info_t *info = get_irn_link(store);
833 ir_node *ptr = get_Store_ptr(store);
834 ir_node *mem = get_Store_mem(store);
835 ir_node *value = get_Store_value(store);
836 ir_mode *mode = get_irn_mode(value);
837 ir_node *block = get_nodes_block(store);
839 for (pred = curr; pred != store;) {
840 ldst_info_t *pred_info = get_irn_link(pred);
843 * BEWARE: one might think that checking the modes is useless, because
844 * if the pointers are identical, they refer to the same object.
845 * This is only true in strong typed languages, not is C were the following
846 * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
847 * However, if the mode that is written have a bigger or equal size the the old
848 * one, the old value is completely overwritten and can be killed ...
850 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
851 get_nodes_block(pred) == block &&
852 is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
854 * a Store after a Store in the same block -- a write after write.
855 * We may remove the first Store, if it does not have an exception handler.
857 * TODO: What, if both have the same exception handler ???
859 if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
860 DBG_OPT_WAW(pred, store);
861 exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
862 exchange(pred, new_Bad());
863 reduce_adr_usage(ptr);
866 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
867 value == pred_info->projs[pn_Load_res]) {
869 * a Store of a value after a Load -- a write after read.
870 * We may remove the second Store, if it does not have an exception handler.
872 if (! info->projs[pn_Store_X_except]) {
873 DBG_OPT_WAR(store, pred);
874 exchange( info->projs[pn_Store_M], mem );
875 exchange(store, new_Bad());
876 reduce_adr_usage(ptr);
881 if (get_irn_op(pred) == op_Store) {
882 /* check if we can pass thru this store */
883 ir_alias_relation rel = get_alias_relation(
886 get_irn_mode(get_Store_value(pred)),
888 /* if the might be an alias, we cannot pass this Store */
891 pred = skip_Proj(get_Store_mem(pred));
892 } else if (get_irn_op(pred) == op_Load) {
893 pred = skip_Proj(get_Load_mem(pred));
895 /* follow only Load chains */
899 /* check for cycles */
900 if (NODE_VISITED(pred_info))
902 MARK_NODE(pred_info);
905 if (get_irn_op(pred) == op_Sync) {
908 /* handle all Sync predecessors */
909 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
910 res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
916 } /* follow_Mem_chain_for_Store */
921 * @param store the Store node
923 static unsigned optimize_store(ir_node *store) {
926 if (get_Store_volatility(store) == volatility_is_volatile)
929 ptr = get_Store_ptr(store);
931 /* Check, if the address of this Store is used more than once.
932 * If not, this Store cannot be removed in any case. */
933 if (get_irn_n_uses(ptr) <= 1)
936 mem = get_Store_mem(store);
938 /* follow the memory chain as long as there are only Loads */
940 return follow_Mem_chain_for_Store(store, skip_Proj(mem));
941 } /* optimize_store */
944 * walker, optimizes Phi after Stores to identical places:
945 * Does the following optimization:
948 * val1 val2 val3 val1 val2 val3
950 * Store Store Store \ | /
957 * This reduces the number of stores and allows for predicated execution.
958 * Moves Stores back to the end of a function which may be bad.
960 * This is only possible if the predecessor blocks have only one successor.
962 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
965 ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
967 ir_node **inM, **inD, **projMs;
971 block_info_t *bl_info;
974 /* Must be a memory Phi */
975 if (get_irn_mode(phi) != mode_M)
978 n = get_Phi_n_preds(phi);
982 store = skip_Proj(get_Phi_pred(phi, 0));
984 if (get_irn_op(store) != op_Store)
987 block = get_nodes_block(store);
989 /* abort on dead blocks */
990 if (is_Block_dead(block))
993 /* check if the block is post dominated by Phi-block
994 and has no exception exit */
995 bl_info = get_irn_link(block);
996 if (bl_info->flags & BLOCK_HAS_EXC)
999 phi_block = get_nodes_block(phi);
1000 if (! block_strictly_postdominates(phi_block, block))
1003 /* this is the address of the store */
1004 ptr = get_Store_ptr(store);
1005 mode = get_irn_mode(get_Store_value(store));
1006 info = get_irn_link(store);
1007 exc = info->exc_block;
1009 for (i = 1; i < n; ++i) {
1010 ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
1012 if (get_irn_op(pred) != op_Store)
1015 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1018 info = get_irn_link(pred);
1020 /* check, if all stores have the same exception flow */
1021 if (exc != info->exc_block)
1024 /* abort on dead blocks */
1025 block = get_nodes_block(pred);
1026 if (is_Block_dead(block))
1029 /* check if the block is post dominated by Phi-block
1030 and has no exception exit. Note that block must be different from
1031 Phi-block, else we would move a Store from end End of a block to its
1033 bl_info = get_irn_link(block);
1034 if (bl_info->flags & BLOCK_HAS_EXC)
1036 if (block == phi_block || ! block_postdominates(phi_block, block))
1041 * ok, when we are here, we found all predecessors of a Phi that
1042 * are Stores to the same address and size. That means whatever
1043 * we do before we enter the block of the Phi, we do a Store.
1044 * So, we can move the Store to the current block:
1046 * val1 val2 val3 val1 val2 val3
1048 * | Str | | Str | | Str | \ | /
1054 * Is only allowed if the predecessor blocks have only one successor.
1057 NEW_ARR_A(ir_node *, projMs, n);
1058 NEW_ARR_A(ir_node *, inM, n);
1059 NEW_ARR_A(ir_node *, inD, n);
1060 NEW_ARR_A(int, idx, n);
1062 /* Prepare: Collect all Store nodes. We must do this
1063 first because we otherwise may loose a store when exchanging its
1066 for (i = 0; i < n; ++i)
1067 projMs[i] = get_Phi_pred(phi, i);
1069 /* first step: collect all inputs and kill the node */
1070 for (i = n - 1; i >= 0; --i) {
1071 ir_node *store = get_Proj_pred(projMs[i]);
1072 info = get_irn_link(store);
1074 inM[i] = get_Store_mem(store);
1075 inD[i] = get_Store_value(store);
1076 idx[i] = info->exc_idx;
1079 block = get_nodes_block(phi);
1081 /* second step: create a new memory Phi */
1082 phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1084 /* third step: create a new data Phi */
1085 phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1088 for (i = n - 1; i >= 0; --i) {
1089 ir_node *proj = projMs[i];
1091 exchange(proj, inM[i]);
1094 /* fourth step: create the Store */
1095 store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1097 co_set_irn_name(store, co_get_irn_ident(old_store));
1100 projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1102 info = get_ldst_info(store, wenv);
1103 info->projs[pn_Store_M] = projM;
1105 /* fifths step: repair exception flow */
1107 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1109 info->projs[pn_Store_X_except] = projX;
1110 info->exc_block = exc;
1111 info->exc_idx = idx[0];
1113 for (i = 0; i < n; ++i) {
1114 set_Block_cfgpred(exc, idx[i], projX);
1118 /* the exception block should be optimized as some inputs are identical now */
1124 /* sixth step: replace old Phi */
1125 exchange(phi, projM);
1127 return res | DF_CHANGED;
1128 } /* optimize_phi */
1131 * walker, do the optimizations
1133 static void do_load_store_optimize(ir_node *n, void *env) {
1134 walk_env_t *wenv = env;
1136 switch (get_irn_opcode(n)) {
1139 wenv->changes |= optimize_load(n);
1143 wenv->changes |= optimize_store(n);
1147 wenv->changes |= optimize_phi(n, wenv);
1152 } /* do_load_store_optimize */
1155 * do the load store optimization
1157 void optimize_load_store(ir_graph *irg) {
1160 assert(get_irg_phase_state(irg) != phase_building);
1161 assert(get_irg_pinned(irg) != op_pin_state_floats &&
1162 "LoadStore optimization needs pinned graph");
1164 if (! get_opt_redundant_loadstore())
1169 /* for Phi optimization post-dominators are needed ... */
1170 assure_postdoms(irg);
1172 if (get_opt_alias_analysis()) {
1173 assure_irg_address_taken_computed(irg);
1174 assure_irp_globals_address_taken_computed();
1177 obstack_init(&env.obst);
1180 /* init the links, then collect Loads/Stores/Proj's in lists */
1182 irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1184 /* now we have collected enough information, optimize */
1185 irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1187 obstack_free(&env.obst, NULL);
1189 /* Handle graph state */
1191 set_irg_outs_inconsistent(irg);
1194 if (env.changes & CF_CHANGED) {
1195 /* is this really needed: Yes, control flow changed, block might
1196 have Bad() predecessors. */
1197 set_irg_doms_inconsistent(irg);
1199 } /* optimize_load_store */