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"
52 #include "irphase_t.h"
56 /** The debug handle. */
57 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
60 #include "cacheopt/cachesim.h"
64 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
66 #define MAX_PROJ IMAX(pn_Load_max, pn_Store_max)
69 DF_CHANGED = 1, /**< data flow changed */
70 CF_CHANGED = 2, /**< control flow changed */
76 typedef struct _walk_env_t {
77 struct obstack obst; /**< list of all stores */
78 unsigned changes; /**< a bitmask of graph changes */
82 * flags for Load/Store
85 LDST_VISITED = 1 /**< if set, this Load/Store is already visited */
88 /** A Load/Store info. */
89 typedef struct _ldst_info_t {
90 ir_node *projs[MAX_PROJ]; /**< list of Proj's of this node */
91 ir_node *exc_block; /**< the exception block if available */
92 int exc_idx; /**< predecessor index in the exception block */
93 unsigned flags; /**< flags */
94 unsigned visited; /**< visited counter for breaking loops */
98 * flags for control flow.
101 BLOCK_HAS_COND = 1, /**< Block has conditional control flow */
102 BLOCK_HAS_EXC = 2 /**< Block has exceptional control flow */
108 typedef struct _block_info_t {
109 unsigned flags; /**< flags for the block */
112 /** the master visited flag for loop detection. */
113 static unsigned master_visited = 0;
115 #define INC_MASTER() ++master_visited
116 #define MARK_NODE(info) (info)->visited = master_visited
117 #define NODE_VISITED(info) (info)->visited >= master_visited
120 * get the Load/Store info of a node
122 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst) {
123 ldst_info_t *info = get_irn_link(node);
126 info = obstack_alloc(obst, sizeof(*info));
127 memset(info, 0, sizeof(*info));
128 set_irn_link(node, info);
131 } /* get_ldst_info */
134 * get the Block info of a node
136 static block_info_t *get_block_info(ir_node *node, struct obstack *obst) {
137 block_info_t *info = get_irn_link(node);
140 info = obstack_alloc(obst, sizeof(*info));
141 memset(info, 0, sizeof(*info));
142 set_irn_link(node, info);
145 } /* get_block_info */
148 * update the projection info for a Load/Store
150 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
152 long nr = get_Proj_proj(proj);
154 assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
156 if (info->projs[nr]) {
157 /* there is already one, do CSE */
158 exchange(proj, info->projs[nr]);
162 info->projs[nr] = proj;
168 * update the exception block info for a Load/Store node.
170 * @param info the load/store info struct
171 * @param block the exception handler block for this load/store
172 * @param pos the control flow input of the block
174 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
176 assert(info->exc_block == NULL && "more than one exception block found");
178 info->exc_block = block;
183 /** Return the number of uses of an address node */
184 #define get_irn_n_uses(adr) get_irn_n_edges(adr)
187 * walker, collects all Load/Store/Proj nodes
189 * walks from Start -> End
191 static void collect_nodes(ir_node *node, void *env)
193 ir_op *op = get_irn_op(node);
194 ir_node *pred, *blk, *pred_blk;
195 ldst_info_t *ldst_info;
196 walk_env_t *wenv = env;
202 pred = get_Proj_pred(node);
203 op = get_irn_op(pred);
206 ldst_info = get_ldst_info(pred, &wenv->obst);
208 wenv->changes |= update_projs(ldst_info, node);
210 if ((ldst_info->flags & LDST_VISITED) == 0) {
211 adr = get_Load_ptr(pred);
212 ldst_info->flags |= LDST_VISITED;
216 * Place the Proj's to the same block as the
217 * predecessor Load. This is always ok and prevents
218 * "non-SSA" form after optimizations if the Proj
219 * is in a wrong block.
221 blk = get_nodes_block(node);
222 pred_blk = get_nodes_block(pred);
223 if (blk != pred_blk) {
224 wenv->changes |= DF_CHANGED;
225 set_nodes_block(node, pred_blk);
227 } else if (op == op_Store) {
228 ldst_info = get_ldst_info(pred, &wenv->obst);
230 wenv->changes |= update_projs(ldst_info, node);
232 if ((ldst_info->flags & LDST_VISITED) == 0) {
233 adr = get_Store_ptr(pred);
234 ldst_info->flags |= LDST_VISITED;
238 * Place the Proj's to the same block as the
239 * predecessor Store. This is always ok and prevents
240 * "non-SSA" form after optimizations if the Proj
241 * is in a wrong block.
243 blk = get_nodes_block(node);
244 pred_blk = get_nodes_block(pred);
245 if (blk != pred_blk) {
246 wenv->changes |= DF_CHANGED;
247 set_nodes_block(node, pred_blk);
250 } else if (op == op_Block) {
253 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
254 ir_node *pred_block, *proj;
255 block_info_t *bl_info;
258 pred = proj = get_Block_cfgpred(node, i);
261 pred = get_Proj_pred(proj);
262 is_exc = get_Proj_proj(proj) == pn_Generic_X_except;
265 /* ignore Bad predecessors, they will be removed later */
269 pred_block = get_nodes_block(pred);
270 bl_info = get_block_info(pred_block, &wenv->obst);
272 if (is_fragile_op(pred) && is_exc)
273 bl_info->flags |= BLOCK_HAS_EXC;
274 else if (is_irn_forking(pred))
275 bl_info->flags |= BLOCK_HAS_COND;
277 if (is_exc && (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store)) {
278 ldst_info = get_ldst_info(pred, &wenv->obst);
280 wenv->changes |= update_exc(ldst_info, node, i);
284 } /* collect_nodes */
287 * Returns an entity if the address ptr points to a constant one.
289 * @param ptr the address
291 * @return an entity or NULL
293 static ir_entity *find_constant_entity(ir_node *ptr)
296 ir_op *op = get_irn_op(ptr);
298 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
299 ir_entity *ent = get_SymConst_entity(ptr);
300 if (variability_constant == get_entity_variability(ent))
303 } else if (op == op_Sel) {
304 ir_entity *ent = get_Sel_entity(ptr);
305 ir_type *tp = get_entity_owner(ent);
307 /* Do not fiddle with polymorphism. */
308 if (is_Class_type(get_entity_owner(ent)) &&
309 ((get_entity_n_overwrites(ent) != 0) ||
310 (get_entity_n_overwrittenby(ent) != 0) ) )
313 if (is_Array_type(tp)) {
317 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
319 tarval *tlower, *tupper;
320 ir_node *index = get_Sel_index(ptr, i);
321 tarval *tv = computed_value(index);
323 /* check if the index is constant */
324 if (tv == tarval_bad)
327 bound = get_array_lower_bound(tp, i);
328 tlower = computed_value(bound);
329 bound = get_array_upper_bound(tp, i);
330 tupper = computed_value(bound);
332 if (tlower == tarval_bad || tupper == tarval_bad)
335 if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
337 if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
340 /* ok, bounds check finished */
344 if (variability_constant == get_entity_variability(ent))
348 ptr = get_Sel_ptr(ptr);
352 } /* find_constant_entity */
355 * Return the Selection index of a Sel node from dimension n
357 static long get_Sel_array_index_long(ir_node *n, int dim) {
358 ir_node *index = get_Sel_index(n, dim);
359 assert(get_irn_op(index) == op_Const);
360 return get_tarval_long(get_Const_tarval(index));
361 } /* get_Sel_array_index_long */
364 * Returns the accessed component graph path for an
365 * node computing an address.
367 * @param ptr the node computing the address
368 * @param depth current depth in steps upward from the root
371 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
372 compound_graph_path *res = NULL;
373 ir_entity *root, *field;
376 if (get_irn_op(ptr) == op_SymConst) {
377 /* a SymConst. If the depth is 0, this is an access to a global
378 * entity and we don't need a component path, else we know
379 * at least it's length.
381 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
382 root = get_SymConst_entity(ptr);
383 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
385 assert(get_irn_op(ptr) == op_Sel);
386 /* it's a Sel, go up until we find the root */
387 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
389 /* fill up the step in the path at the current position */
390 field = get_Sel_entity(ptr);
391 path_len = get_compound_graph_path_length(res);
392 pos = path_len - depth - 1;
393 set_compound_graph_path_node(res, pos, field);
395 if (is_Array_type(get_entity_owner(field))) {
396 assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
397 set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
401 } /* rec_get_accessed_path */
403 /** Returns an access path or NULL. The access path is only
404 * valid, if the graph is in phase_high and _no_ address computation is used.
406 static compound_graph_path *get_accessed_path(ir_node *ptr) {
407 return rec_get_accessed_path(ptr, 0);
408 } /* get_accessed_path */
411 static void reduce_adr_usage(ir_node *ptr);
414 * Update a Load that may lost it's usage.
416 static void handle_load_update(ir_node *load) {
417 ldst_info_t *info = get_irn_link(load);
419 /* do NOT touch volatile loads for now */
420 if (get_Load_volatility(load) == volatility_is_volatile)
423 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
424 ir_node *ptr = get_Load_ptr(load);
425 ir_node *mem = get_Load_mem(load);
427 /* a Load which value is neither used nor exception checked, remove it */
428 exchange(info->projs[pn_Load_M], mem);
429 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
430 exchange(load, new_Bad());
431 reduce_adr_usage(ptr);
433 } /* handle_load_update */
436 * A Use of an address node is vanished. Check if this was a Proj
437 * node and update the counters.
439 static void reduce_adr_usage(ir_node *ptr) {
441 if (get_irn_n_edges(ptr) <= 0) {
442 /* this Proj is dead now */
443 ir_node *pred = get_Proj_pred(ptr);
446 ldst_info_t *info = get_irn_link(pred);
447 info->projs[get_Proj_proj(ptr)] = NULL;
449 /* this node lost it's result proj, handle that */
450 handle_load_update(pred);
454 } /* reduce_adr_usage */
457 * Check, if an already existing value of mode old_mode can be converted
458 * into the needed one new_mode without loss.
460 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
461 if (old_mode == new_mode)
464 /* if both modes are two-complement ones, we can always convert the
465 Stored value into the needed one. */
466 if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
467 get_mode_arithmetic(old_mode) == irma_twos_complement &&
468 get_mode_arithmetic(new_mode) == irma_twos_complement)
471 } /* can_use_stored_value */
474 * Follow the memory chain as long as there are only Loads
475 * and alias free Stores and try to replace current Load or Store
476 * by a previous ones.
477 * Note that in unreachable loops it might happen that we reach
478 * load again, as well as we can fall into a cycle.
479 * We break such cycles using a special visited flag.
481 * INC_MASTER() must be called before dive into
483 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
485 ldst_info_t *info = get_irn_link(load);
487 ir_node *ptr = get_Load_ptr(load);
488 ir_node *mem = get_Load_mem(load);
489 ir_mode *load_mode = get_Load_mode(load);
491 for (pred = curr; load != pred; ) {
492 ldst_info_t *pred_info = get_irn_link(pred);
495 * BEWARE: one might think that checking the modes is useless, because
496 * if the pointers are identical, they refer to the same object.
497 * This is only true in strong typed languages, not in C were the following
498 * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
500 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
501 can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
503 * a Load immediately after a Store -- a read after write.
504 * We may remove the Load, if both Load & Store does not have an exception handler
505 * OR they are in the same MacroBlock. In the latter case the Load cannot
506 * throw an exception when the previous Store was quiet.
508 * Why we need to check for Store Exception? If the Store cannot
509 * be executed (ROM) the exception handler might simply jump into
510 * the load MacroBlock :-(
511 * We could make it a little bit better if we would know that the exception
512 * handler of the Store jumps directly to the end...
514 if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
515 get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
516 ir_node *value = get_Store_value(pred);
518 DBG_OPT_RAW(load, value);
520 /* add an convert if needed */
521 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
522 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
525 if (info->projs[pn_Load_M])
526 exchange(info->projs[pn_Load_M], mem);
529 if (info->projs[pn_Load_X_except]) {
530 exchange( info->projs[pn_Load_X_except], new_Bad());
533 if (info->projs[pn_Load_X_regular]) {
534 exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
538 if (info->projs[pn_Load_res])
539 exchange(info->projs[pn_Load_res], value);
541 exchange(load, new_Bad());
542 reduce_adr_usage(ptr);
543 return res | DF_CHANGED;
545 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
546 can_use_stored_value(get_Load_mode(pred), load_mode)) {
548 * a Load after a Load -- a read after read.
549 * We may remove the second Load, if it does not have an exception handler
550 * OR they are in the same MacroBlock. In the later case the Load cannot
551 * throw an exception when the previous Load was quiet.
553 * Here, there is no need to check if the previous Load has an exception
554 * hander because they would have exact the same exception...
556 if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
559 DBG_OPT_RAR(load, pred);
561 /* the result is used */
562 if (info->projs[pn_Load_res]) {
563 if (pred_info->projs[pn_Load_res] == NULL) {
564 /* create a new Proj again */
565 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
567 value = pred_info->projs[pn_Load_res];
569 /* add an convert if needed */
570 if (get_Load_mode(pred) != load_mode) {
571 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
574 exchange(info->projs[pn_Load_res], value);
577 if (info->projs[pn_Load_M])
578 exchange(info->projs[pn_Load_M], mem);
581 if (info->projs[pn_Load_X_except]) {
582 exchange(info->projs[pn_Load_X_except], new_Bad());
585 if (info->projs[pn_Load_X_regular]) {
586 exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
590 exchange(load, new_Bad());
591 reduce_adr_usage(ptr);
592 return res |= DF_CHANGED;
596 if (is_Store(pred)) {
597 /* check if we can pass through this store */
598 ir_alias_relation rel = get_alias_relation(
601 get_irn_mode(get_Store_value(pred)),
603 /* if the might be an alias, we cannot pass this Store */
606 pred = skip_Proj(get_Store_mem(pred));
607 } else if (get_irn_op(pred) == op_Load) {
608 pred = skip_Proj(get_Load_mem(pred));
610 /* follow only Load chains */
614 /* check for cycles */
615 if (NODE_VISITED(pred_info))
617 MARK_NODE(pred_info);
623 /* handle all Sync predecessors */
624 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
625 res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
632 } /* follow_Mem_chain */
637 * @param load the Load node
639 static unsigned optimize_load(ir_node *load)
641 ldst_info_t *info = get_irn_link(load);
642 ir_node *mem, *ptr, *new_node;
646 /* do NOT touch volatile loads for now */
647 if (get_Load_volatility(load) == volatility_is_volatile)
650 /* the address of the load to be optimized */
651 ptr = get_Load_ptr(load);
654 * Check if we can remove the exception from a Load:
655 * This can be done, if the address is from an Sel(Alloc) and
656 * the Sel type is a subtype of the allocated type.
658 * This optimizes some often used OO constructs,
659 * like x = new O; x->t;
661 if (info->projs[pn_Load_X_except]) {
663 ir_node *mem = get_Sel_mem(ptr);
665 /* FIXME: works with the current FE, but better use the base */
666 if (is_Alloc(skip_Proj(mem))) {
667 /* ok, check the types */
668 ir_entity *ent = get_Sel_entity(ptr);
669 ir_type *s_type = get_entity_type(ent);
670 ir_type *a_type = get_Alloc_type(mem);
672 if (is_SubClass_of(s_type, a_type)) {
673 /* ok, condition met: there can't be an exception because
674 * Alloc guarantees that enough memory was allocated */
676 exchange(info->projs[pn_Load_X_except], new_Bad());
677 info->projs[pn_Load_X_except] = NULL;
678 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
679 info->projs[pn_Load_X_regular] = NULL;
683 } else if (is_Alloc(skip_Proj(skip_Cast(ptr)))) {
684 /* simple case: a direct load after an Alloc. Firm Alloc throw
685 * an exception in case of out-of-memory. So, there is no way for an
686 * exception in this load.
687 * This code is constructed by the "exception lowering" in the Jack compiler.
689 exchange(info->projs[pn_Load_X_except], new_Bad());
690 info->projs[pn_Load_X_except] = NULL;
691 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
692 info->projs[pn_Load_X_regular] = NULL;
697 /* The mem of the Load. Must still be returned after optimization. */
698 mem = get_Load_mem(load);
700 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
701 /* a Load which value is neither used nor exception checked, remove it */
702 exchange(info->projs[pn_Load_M], mem);
704 if (info->projs[pn_Load_X_regular]) {
705 /* should not happen, but if it does, remove it */
706 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
709 exchange(load, new_Bad());
710 reduce_adr_usage(ptr);
711 return res | DF_CHANGED;
714 /* Load from a constant polymorphic field, where we can resolve
716 new_node = transform_node_Load(load);
717 if (new_node != load) {
718 if (info->projs[pn_Load_M]) {
719 exchange(info->projs[pn_Load_M], mem);
720 info->projs[pn_Load_M] = NULL;
722 if (info->projs[pn_Load_X_except]) {
723 exchange(info->projs[pn_Load_X_except], new_Bad());
724 info->projs[pn_Load_X_except] = NULL;
727 if (info->projs[pn_Load_X_regular]) {
728 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
729 info->projs[pn_Load_X_regular] = NULL;
732 if (info->projs[pn_Load_res])
733 exchange(info->projs[pn_Load_res], new_node);
735 exchange(load, new_Bad());
736 reduce_adr_usage(ptr);
737 return res | DF_CHANGED;
740 /* check if we can determine the entity that will be loaded */
741 ent = find_constant_entity(ptr);
743 if ((allocation_static == get_entity_allocation(ent)) &&
744 (visibility_external_allocated != get_entity_visibility(ent))) {
745 /* a static allocation that is not external: there should be NO exception
748 /* no exception, clear the info field as it might be checked later again */
749 if (info->projs[pn_Load_X_except]) {
750 exchange(info->projs[pn_Load_X_except], new_Bad());
751 info->projs[pn_Load_X_except] = NULL;
754 if (info->projs[pn_Load_X_regular]) {
755 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
756 info->projs[pn_Load_X_regular] = NULL;
760 if (variability_constant == get_entity_variability(ent)
761 && is_atomic_entity(ent)) {
762 /* Might not be atomic after
763 lowering of Sels. In this
764 case we could also load, but
765 it's more complicated. */
766 /* more simpler case: we load the content of a constant value:
767 * replace it by the constant itself
771 if (info->projs[pn_Load_M]) {
772 exchange(info->projs[pn_Load_M], mem);
776 if (info->projs[pn_Load_res]) {
777 if (is_atomic_entity(ent)) {
778 ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
781 exchange(info->projs[pn_Load_res], c);
785 exchange(load, new_Bad());
786 reduce_adr_usage(ptr);
788 } else if (variability_constant == get_entity_variability(ent)) {
789 compound_graph_path *path = get_accessed_path(ptr);
794 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
798 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
799 ir_entity *node = get_compound_graph_path_node(path, j);
800 fprintf(stdout, ".%s", get_entity_name(node));
801 if (is_Array_type(get_entity_owner(node)))
802 fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
808 c = get_compound_ent_value_by_path(ent, path);
809 free_compound_graph_path(path);
811 /* printf(" cons: "); DDMN(c); */
813 if (info->projs[pn_Load_M]) {
814 exchange(info->projs[pn_Load_M], mem);
817 if (info->projs[pn_Load_res]) {
818 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
821 exchange(load, new_Bad());
822 reduce_adr_usage(ptr);
825 /* We can not determine a correct access path. E.g., in jack, we load
826 a byte from an object to generate an exception. Happens in test program
828 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
829 get_entity_name(get_irg_entity(current_ir_graph)));
830 printf(" load: "); DDMN(load);
831 printf(" ptr: "); DDMN(ptr);
838 /* Check, if the address of this load is used more than once.
839 * If not, this load cannot be removed in any case. */
840 if (get_irn_n_uses(ptr) <= 1)
844 * follow the memory chain as long as there are only Loads
845 * and try to replace current Load or Store by a previous one.
846 * Note that in unreachable loops it might happen that we reach
847 * load again, as well as we can fall into a cycle.
848 * We break such cycles using a special visited flag.
851 res = follow_Mem_chain(load, skip_Proj(mem));
853 } /* optimize_load */
856 * Check whether a value of mode new_mode would completely overwrite a value
857 * of mode old_mode in memory.
859 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
861 return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
862 } /* is_completely_overwritten */
865 * follow the memory chain as long as there are only Loads and alias free Stores.
867 * INC_MASTER() must be called before dive into
869 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
871 ldst_info_t *info = get_irn_link(store);
873 ir_node *ptr = get_Store_ptr(store);
874 ir_node *mem = get_Store_mem(store);
875 ir_node *value = get_Store_value(store);
876 ir_mode *mode = get_irn_mode(value);
877 ir_node *block = get_nodes_block(store);
878 ir_node *mblk = get_Block_MacroBlock(block);
880 for (pred = curr; pred != store;) {
881 ldst_info_t *pred_info = get_irn_link(pred);
884 * BEWARE: one might think that checking the modes is useless, because
885 * if the pointers are identical, they refer to the same object.
886 * This is only true in strong typed languages, not is C were the following
887 * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
888 * However, if the mode that is written have a bigger or equal size the the old
889 * one, the old value is completely overwritten and can be killed ...
891 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
892 get_nodes_MacroBlock(pred) == mblk &&
893 is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
895 * a Store after a Store in the same block -- a write after write.
896 * We may remove the first Store, if it does not have an exception handler.
898 * TODO: What, if both have the same exception handler ???
900 if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
901 DBG_OPT_WAW(pred, store);
902 exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
903 exchange(pred, new_Bad());
904 reduce_adr_usage(ptr);
907 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
908 value == pred_info->projs[pn_Load_res]) {
910 * a Store of a value after a Load -- a write after read.
911 * We may remove the second Store, if it does not have an exception handler.
913 if (! info->projs[pn_Store_X_except]) {
914 DBG_OPT_WAR(store, pred);
915 exchange(info->projs[pn_Store_M], mem);
916 exchange(store, new_Bad());
917 reduce_adr_usage(ptr);
922 if (is_Store(pred)) {
923 /* check if we can pass thru this store */
924 ir_alias_relation rel = get_alias_relation(
927 get_irn_mode(get_Store_value(pred)),
929 /* if the might be an alias, we cannot pass this Store */
932 pred = skip_Proj(get_Store_mem(pred));
933 } else if (get_irn_op(pred) == op_Load) {
934 pred = skip_Proj(get_Load_mem(pred));
936 /* follow only Load chains */
940 /* check for cycles */
941 if (NODE_VISITED(pred_info))
943 MARK_NODE(pred_info);
949 /* handle all Sync predecessors */
950 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
951 res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
957 } /* follow_Mem_chain_for_Store */
962 * @param store the Store node
964 static unsigned optimize_store(ir_node *store) {
967 if (get_Store_volatility(store) == volatility_is_volatile)
970 ptr = get_Store_ptr(store);
972 /* Check, if the address of this Store is used more than once.
973 * If not, this Store cannot be removed in any case. */
974 if (get_irn_n_uses(ptr) <= 1)
977 mem = get_Store_mem(store);
979 /* follow the memory chain as long as there are only Loads */
981 return follow_Mem_chain_for_Store(store, skip_Proj(mem));
982 } /* optimize_store */
985 * walker, optimizes Phi after Stores to identical places:
986 * Does the following optimization:
989 * val1 val2 val3 val1 val2 val3
991 * Store Store Store \ | /
998 * This reduces the number of stores and allows for predicated execution.
999 * Moves Stores back to the end of a function which may be bad.
1001 * This is only possible if the predecessor blocks have only one successor.
1003 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1006 ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1008 ir_node **inM, **inD, **projMs;
1010 dbg_info *db = NULL;
1012 block_info_t *bl_info;
1015 /* Must be a memory Phi */
1016 if (get_irn_mode(phi) != mode_M)
1019 n = get_Phi_n_preds(phi);
1023 /* must be only one user */
1024 projM = get_Phi_pred(phi, 0);
1025 if (get_irn_n_edges(projM) != 1)
1028 store = skip_Proj(projM);
1030 if (get_irn_op(store) != op_Store)
1033 block = get_nodes_block(store);
1035 /* abort on dead blocks */
1036 if (is_Block_dead(block))
1039 /* check if the block is post dominated by Phi-block
1040 and has no exception exit */
1041 bl_info = get_irn_link(block);
1042 if (bl_info->flags & BLOCK_HAS_EXC)
1045 phi_block = get_nodes_block(phi);
1046 if (! block_strictly_postdominates(phi_block, block))
1049 /* this is the address of the store */
1050 ptr = get_Store_ptr(store);
1051 mode = get_irn_mode(get_Store_value(store));
1052 info = get_irn_link(store);
1053 exc = info->exc_block;
1055 for (i = 1; i < n; ++i) {
1056 ir_node *pred = get_Phi_pred(phi, i);
1058 if (get_irn_n_edges(pred) != 1)
1061 pred = skip_Proj(pred);
1062 if (!is_Store(pred))
1065 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1068 info = get_irn_link(pred);
1070 /* check, if all stores have the same exception flow */
1071 if (exc != info->exc_block)
1074 /* abort on dead blocks */
1075 block = get_nodes_block(pred);
1076 if (is_Block_dead(block))
1079 /* check if the block is post dominated by Phi-block
1080 and has no exception exit. Note that block must be different from
1081 Phi-block, else we would move a Store from end End of a block to its
1083 bl_info = get_irn_link(block);
1084 if (bl_info->flags & BLOCK_HAS_EXC)
1086 if (block == phi_block || ! block_postdominates(phi_block, block))
1091 * ok, when we are here, we found all predecessors of a Phi that
1092 * are Stores to the same address and size. That means whatever
1093 * we do before we enter the block of the Phi, we do a Store.
1094 * So, we can move the Store to the current block:
1096 * val1 val2 val3 val1 val2 val3
1098 * | Str | | Str | | Str | \ | /
1104 * Is only allowed if the predecessor blocks have only one successor.
1107 NEW_ARR_A(ir_node *, projMs, n);
1108 NEW_ARR_A(ir_node *, inM, n);
1109 NEW_ARR_A(ir_node *, inD, n);
1110 NEW_ARR_A(int, idx, n);
1112 /* Prepare: Collect all Store nodes. We must do this
1113 first because we otherwise may loose a store when exchanging its
1116 for (i = n - 1; i >= 0; --i) {
1119 projMs[i] = get_Phi_pred(phi, i);
1120 assert(is_Proj(projMs[i]));
1122 store = get_Proj_pred(projMs[i]);
1123 info = get_irn_link(store);
1125 inM[i] = get_Store_mem(store);
1126 inD[i] = get_Store_value(store);
1127 idx[i] = info->exc_idx;
1129 block = get_nodes_block(phi);
1131 /* second step: create a new memory Phi */
1132 phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1134 /* third step: create a new data Phi */
1135 phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1137 /* rewire memory and kill the node */
1138 for (i = n - 1; i >= 0; --i) {
1139 ir_node *proj = projMs[i];
1142 ir_node *store = get_Proj_pred(proj);
1143 exchange(proj, inM[i]);
1148 /* fourth step: create the Store */
1149 store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1151 co_set_irn_name(store, co_get_irn_ident(old_store));
1154 projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1156 info = get_ldst_info(store, &wenv->obst);
1157 info->projs[pn_Store_M] = projM;
1159 /* fifths step: repair exception flow */
1161 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1163 info->projs[pn_Store_X_except] = projX;
1164 info->exc_block = exc;
1165 info->exc_idx = idx[0];
1167 for (i = 0; i < n; ++i) {
1168 set_Block_cfgpred(exc, idx[i], projX);
1172 /* the exception block should be optimized as some inputs are identical now */
1178 /* sixth step: replace old Phi */
1179 exchange(phi, projM);
1181 return res | DF_CHANGED;
1182 } /* optimize_phi */
1185 * walker, do the optimizations
1187 static void do_load_store_optimize(ir_node *n, void *env) {
1188 walk_env_t *wenv = env;
1190 switch (get_irn_opcode(n)) {
1193 wenv->changes |= optimize_load(n);
1197 wenv->changes |= optimize_store(n);
1201 wenv->changes |= optimize_phi(n, wenv);
1206 } /* do_load_store_optimize */
1209 typedef struct scc {
1210 ir_node *head; /**< the head of the list */
1213 /** A node entry. */
1214 typedef struct node_entry {
1215 unsigned DFSnum; /**< the DFS number of this node */
1216 unsigned low; /**< the low number of this node */
1217 ir_node *header; /**< the header of this node */
1218 int in_stack; /**< flag, set if the node is on the stack */
1219 ir_node *next; /**< link to the next node the the same scc */
1220 scc *pscc; /**< the scc of this node */
1221 unsigned POnum; /**< the post order number for blocks */
1224 /** A loop entry. */
1225 typedef struct loop_env {
1226 ir_phase ph; /**< the phase object */
1227 ir_node **stack; /**< the node stack */
1228 int tos; /**< tos index */
1229 unsigned nextDFSnum; /**< the current DFS number */
1230 unsigned POnum; /**< current post order number */
1232 unsigned changes; /**< a bitmask of graph changes */
1236 * Gets the node_entry of a node
1238 static node_entry *get_irn_ne(ir_node *irn, loop_env *env) {
1239 ir_phase *ph = &env->ph;
1240 node_entry *e = phase_get_irn_data(&env->ph, irn);
1243 e = phase_alloc(ph, sizeof(*e));
1244 memset(e, 0, sizeof(*e));
1245 phase_set_irn_data(ph, irn, e);
1251 * Push a node onto the stack.
1253 * @param env the loop environment
1254 * @param n the node to push
1256 static void push(loop_env *env, ir_node *n) {
1259 if (env->tos == ARR_LEN(env->stack)) {
1260 int nlen = ARR_LEN(env->stack) * 2;
1261 ARR_RESIZE(ir_node *, env->stack, nlen);
1263 env->stack[env->tos++] = n;
1264 e = get_irn_ne(n, env);
1269 * pop a node from the stack
1271 * @param env the loop environment
1273 * @return The topmost node
1275 static ir_node *pop(loop_env *env) {
1276 ir_node *n = env->stack[--env->tos];
1277 node_entry *e = get_irn_ne(n, env);
1284 * Check if irn is a region constant.
1285 * The block or irn must strictly dominate the header block.
1287 * @param irn the node to check
1288 * @param header_block the header block of the induction variable
1290 static int is_rc(ir_node *irn, ir_node *header_block) {
1291 ir_node *block = get_nodes_block(irn);
1293 return (block != header_block) && block_dominates(block, header_block);
1296 typedef struct phi_entry phi_entry;
1298 ir_node *phi; /**< A phi with a region const memory. */
1299 int pos; /**< The position of the region const memory */
1300 ir_node *load; /**< the newly created load for this phi */
1305 * Move loops out of loops if possible
1307 static void move_loads_in_loops(scc *pscc, loop_env *env) {
1308 ir_node *phi, *load, *next, *other, *next_other;
1311 phi_entry *phi_list = NULL;
1313 /* collect all outer memories */
1314 for (phi = pscc->head; phi != NULL; phi = next) {
1315 node_entry *ne = get_irn_ne(phi, env);
1318 /* check all memory Phi's */
1319 if (! is_Phi(phi) || get_irn_mode(phi) != mode_M)
1322 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1323 ir_node *pred = get_irn_n(phi, j);
1324 node_entry *pe = get_irn_ne(pred, env);
1326 if (pe->pscc != ne->pscc) {
1327 /* not in the same SCC, is region const */
1328 phi_entry *pe = phase_alloc(&env->ph, sizeof(*pe));
1332 pe->next = phi_list;
1338 for (load = pscc->head; load; load = next) {
1340 node_entry *ne = get_irn_ne(load, env);
1343 if (is_Load(load)) {
1344 ldst_info_t *info = get_irn_link(load);
1345 ir_node *ptr = get_Load_ptr(load);
1347 /* for now, we cannot handle Loads with exceptions */
1348 if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1351 /* for now, we can only handle Load(SymConst) */
1352 if (! is_SymConst(ptr) || get_SymConst_kind(ptr) != symconst_addr_ent)
1354 ent = get_SymConst_entity(ptr);
1356 load_mode = get_Load_mode(load);
1357 if (get_entity_address_taken(ent) == ir_address_not_taken) {
1358 /* Shortcut: If the addres is never taken, this address if complete alias free*/
1362 for (other = pscc->head; other != NULL; other = next_other) {
1363 node_entry *ne = get_irn_ne(other, env);
1364 next_other = ne->next;
1366 if (is_Store(other)) {
1367 ir_alias_relation rel = get_alias_relation(
1369 get_Store_ptr(other),
1370 get_irn_mode(get_Store_value(other)),
1372 /* if the might be an alias, we cannot pass this Store */
1373 if (rel != no_alias)
1377 if (other == NULL) {
1382 /* for now, we cannot handle more than one input */
1383 if (phi_list->next != NULL)
1386 /* yep, no aliasing Store found, Load can be moved */
1387 DB((dbg, LEVEL_1, " Found a Load that could be moved: %+F\n", load));
1389 db = get_irn_dbg_info(load);
1390 for (pe = phi_list; pe != NULL; pe = pe->next) {
1392 ir_node *phi = pe->phi;
1393 ir_node *blk = get_nodes_block(phi);
1394 ir_node *pred = get_Block_cfgpred_block(blk, pos);
1397 pe->load = irn = new_rd_Load(db, current_ir_graph, pred, get_Phi_pred(phi, pos), ptr, load_mode);
1398 ninfo = get_ldst_info(pred, phase_obst(&env->ph));
1400 ninfo->projs[pn_Load_M] = mem = new_r_Proj(current_ir_graph, pred, irn, mode_M, pn_Load_M);
1401 set_Phi_pred(phi, pos, mem);
1403 ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1405 DB((dbg, LEVEL_1, " Created %+F in %+F\n", irn, pred));
1408 /* now kill the old Load */
1409 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1410 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1412 env->changes |= DF_CHANGED;
1416 } /* move_loads_in_loops */
1419 * Process a loop SCC.
1421 * @param pscc the SCC
1422 * @param env the loop environment
1424 static void process_loop(scc *pscc, loop_env *env) {
1425 ir_node *irn, *next, *header = NULL;
1426 node_entry *b, *h = NULL;
1427 int j, only_phi, num_outside, process = 0;
1430 /* find the header block for this scc */
1431 for (irn = pscc->head; irn; irn = next) {
1432 node_entry *e = get_irn_ne(irn, env);
1433 ir_node *block = get_nodes_block(irn);
1436 b = get_irn_ne(block, env);
1439 if (h->POnum < b->POnum) {
1450 /* check if this scc contains only Phi, Loads or Stores nodes */
1454 for (irn = pscc->head; irn; irn = next) {
1455 node_entry *e = get_irn_ne(irn, env);
1458 switch (get_irn_opcode(irn)) {
1461 /* cannot handle Calls or CopyB yet */
1465 if (get_Load_volatility(irn) == volatility_is_volatile) {
1466 /* cannot handle loops with volatile Loads */
1472 if (get_Store_volatility(irn) == volatility_is_volatile) {
1473 /* cannot handle loops with volatile Stores */
1482 for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1483 ir_node *pred = get_irn_n(irn, j);
1484 node_entry *pe = get_irn_ne(pred, env);
1486 if (pe->pscc != e->pscc) {
1487 /* not in the same SCC, must be a region const */
1488 if (! is_rc(pred, header)) {
1489 /* not a memory loop */
1495 } else if (out_rc != pred) {
1506 /* found a memory loop */
1507 DB((dbg, LEVEL_2, " Found a memory loop:\n "));
1508 if (only_phi && num_outside == 1) {
1509 /* a phi cycle with only one real predecessor can be collapsed */
1510 DB((dbg, LEVEL_2, " Found an USELESS Phi cycle:\n "));
1512 for (irn = pscc->head; irn; irn = next) {
1513 node_entry *e = get_irn_ne(irn, env);
1516 exchange(irn, out_rc);
1518 env->changes |= DF_CHANGED;
1522 /* set the header for every node in this scc */
1523 for (irn = pscc->head; irn; irn = next) {
1524 node_entry *e = get_irn_ne(irn, env);
1527 DB((dbg, LEVEL_2, " %+F,", irn));
1529 DB((dbg, LEVEL_2, "\n"));
1531 move_loads_in_loops(pscc, env);
1535 } /* process_loop */
1540 * @param pscc the SCC
1541 * @param env the loop environment
1543 static void process_scc(scc *pscc, loop_env *env) {
1544 ir_node *head = pscc->head;
1545 node_entry *e = get_irn_ne(head, env);
1547 #ifdef DEBUG_libfirm
1549 ir_node *irn, *next;
1551 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1552 for (irn = pscc->head; irn; irn = next) {
1553 node_entry *e = get_irn_ne(irn, env);
1557 DB((dbg, LEVEL_4, " %+F,", irn));
1559 DB((dbg, LEVEL_4, "\n"));
1563 if (e->next != NULL) {
1564 /* this SCC has more than one member */
1565 process_loop(pscc, env);
1569 * Do Tarjan's SCC algorithm and drive load/store optimization.
1571 * @param irn start at this node
1572 * @param env the loop environment
1574 static void dfs(ir_node *irn, loop_env *env)
1577 node_entry *node = get_irn_ne(irn, env);
1579 mark_irn_visited(irn);
1581 /* do not put blocks into the scc */
1582 if (is_Block(irn)) {
1583 n = get_irn_arity(irn);
1584 for (i = 0; i < n; ++i) {
1585 ir_node *pred = get_irn_n(irn, i);
1587 if (irn_not_visited(pred))
1592 ir_node *block = get_nodes_block(irn);
1594 node->DFSnum = env->nextDFSnum++;
1595 node->low = node->DFSnum;
1598 /* handle the block */
1599 if (irn_not_visited(block))
1602 n = get_irn_arity(irn);
1603 for (i = 0; i < n; ++i) {
1604 ir_node *pred = get_irn_n(irn, i);
1605 node_entry *o = get_irn_ne(pred, env);
1607 if (irn_not_visited(pred)) {
1609 node->low = MIN(node->low, o->low);
1611 if (o->DFSnum < node->DFSnum && o->in_stack)
1612 node->low = MIN(o->DFSnum, node->low);
1614 if (node->low == node->DFSnum) {
1615 scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1623 e = get_irn_ne(x, env);
1625 e->next = pscc->head;
1629 process_scc(pscc, env);
1635 * Do the DFS by starting at the End node of a graph.
1637 * @param irg the graph to process
1638 * @param env the loop environment
1640 static void do_dfs(ir_graph *irg, loop_env *env) {
1641 ir_graph *rem = current_ir_graph;
1642 ir_node *end = get_irg_end(irg);
1645 current_ir_graph = irg;
1646 inc_irg_visited(irg);
1648 /* visit all visible nodes */
1651 /* visit the keep-alives */
1652 n = get_End_n_keepalives(end);
1653 for (i = 0; i < n; ++i) {
1654 ir_node *ka = get_End_keepalive(end, i);
1656 if (irn_not_visited(ka))
1659 current_ir_graph = rem;
1663 * Initialize new phase data. We do this always explicit, so return NULL here
1665 static void *init_loop_data(ir_phase *ph, ir_node *irn, void *data) {
1670 } /* init_loop_data */
1673 * Optimize Loads/Stores in loops.
1675 * @param irg the graph
1677 static int optimize_loops(ir_graph *irg) {
1680 env.stack = NEW_ARR_F(ir_node *, 128);
1685 phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
1687 /* calculate the SCC's and drive loop optimization. */
1690 DEL_ARR_F(env.stack);
1691 phase_free(&env.ph);
1694 } /* optimize_loops */
1697 * do the load store optimization
1699 void optimize_load_store(ir_graph *irg) {
1702 FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
1703 firm_dbg_set_mask(dbg, SET_LEVEL_1);
1705 assert(get_irg_phase_state(irg) != phase_building);
1706 assert(get_irg_pinned(irg) != op_pin_state_floats &&
1707 "LoadStore optimization needs pinned graph");
1709 if (! get_opt_redundant_loadstore())
1712 /* we need landing pads */
1713 remove_critical_cf_edges(irg);
1717 /* loop optimizations need dominators ... */
1720 /* for Phi optimization post-dominators are needed ... */
1721 assure_postdoms(irg);
1723 if (get_opt_alias_analysis()) {
1724 assure_irg_address_taken_computed(irg);
1725 assure_irp_globals_address_taken_computed();
1728 obstack_init(&env.obst);
1731 /* init the links, then collect Loads/Stores/Proj's in lists */
1733 irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1735 /* now we have collected enough information, optimize */
1736 irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1738 env.changes |= optimize_loops(irg);
1740 obstack_free(&env.obst, NULL);
1742 /* Handle graph state */
1744 set_irg_outs_inconsistent(irg);
1747 if (env.changes & CF_CHANGED) {
1748 /* is this really needed: Yes, control flow changed, block might
1749 have Bad() predecessors. */
1750 set_irg_doms_inconsistent(irg);
1752 } /* optimize_load_store */