2 * Copyright (C) 1995-2008 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 Dataflow driven Load/Store optimizations, uses some ideas from
24 * @author Michael Beck
40 #include "iroptimize.h"
41 #include "irnodemap.h"
42 #include "raw_bitset.h"
46 /* maximum number of output Proj's */
47 #define MAX_PROJ (pn_Load_max > pn_Store_max ? pn_Load_max : pn_Store_max)
50 * Mapping an address to an dense ID.
52 typedef struct address_entry_t {
53 unsigned id; /**< The ID */
60 FLAG_KILL_LOADS = 1, /**< KILL all Loads */
61 FLAG_KILL_STORES = 2, /**< KILL all Stores */
62 FLAG_KILLED_NODE = 4, /**< this node was killed */
63 FLAG_EXCEPTION = 8, /**< this node has exception flow */
64 FLAG_IGNORE = 16, /**< ignore this node (volatile or other) */
65 /** this memop KILLS all addresses */
66 FLAG_KILL_ALL = FLAG_KILL_LOADS|FLAG_KILL_STORES
70 * A value: This represents a value stored at a given address in
71 * memory. Do not confuse with values from value numbering.
73 typedef struct value_t value_t;
75 ir_node *address; /**< the address of this value */
76 ir_node *value; /**< the value itself */
77 ir_mode *mode; /**< the mode of the value */
78 unsigned id; /**< address id */
82 * A memop describes an memory-related operation.
83 * These are Loads/Store and all other ops that might modify
84 * memory (Calls, CopyB) or causing exceptions.
86 typedef struct memop_t memop_t;
88 value_t value; /**< the value of this memop: only defined for Load/Store */
89 ir_node *node; /**< the memory op itself */
90 ir_node *mem; /**< the memory FROM this node */
91 ir_node *replace; /**< the replacement node if this memop is replaced */
92 memop_t *next; /**< links to the next memory op in the block in forward order. */
93 memop_t *prev; /**< links to the previous memory op in the block in forward order. */
94 unsigned flags; /**< memop flags */
95 ir_node *projs[MAX_PROJ]; /**< Projs of this memory op */
99 * Additional data for every basic block.
101 typedef struct block_t block_t;
103 memop_t *memop_forward; /**< topologically sorted list of memory ops in this block */
104 memop_t *memop_backward; /**< last memop in the list */
105 unsigned *avail_out; /**< out-set of available addresses */
106 memop_t **id_2_memop_avail; /**< maps avail address ids to memops */
107 unsigned *anticL_in; /**< in-set of anticipated Load addresses */
108 memop_t **id_2_memop_antic; /**< maps anticipated address ids to memops */
109 ir_node *block; /**< the associated block */
110 block_t *forward_next; /**< next block entry for forward iteration */
111 block_t *backward_next; /**< next block entry for backward iteration */
112 memop_t *avail; /**< used locally for the avail map */
116 * Metadata for this pass.
118 typedef struct ldst_env_t {
119 struct obstack obst; /**< obstack for temporary data */
120 ir_nodemap_t adr_map; /**< Map addresses to */
121 block_t *forward; /**< Inverse post-order list of all blocks Start->End */
122 block_t *backward; /**< Inverse post-order list of all blocks End->Start */
123 ir_node *start_bl; /**< start block of the current graph */
124 ir_node *end_bl; /**< end block of the current graph */
125 unsigned *curr_set; /**< current set of addresses */
126 memop_t **curr_id_2_memop; /**< current map of address ids to memops */
127 unsigned curr_adr_id; /**< number for address mapping */
128 unsigned n_mem_ops; /**< number of memory operations (Loads/Stores) */
129 unsigned rbs_size; /**< size of all bitsets in bytes */
130 int changed; /**< Flags for changed graph state */
135 static firm_dbg_module_t *dbg;
137 /* the one and only environment */
141 * Dumps the block list.
143 * @param ldst environment
145 static void dump_block_list(ldst_env *env) {
150 for (entry = env->forward; entry != NULL; entry = entry->forward_next) {
151 DB((dbg, LEVEL_2, "%+F {", entry->block));
154 for (op = entry->memop_forward; op != NULL; op = op->next) {
156 DB((dbg, LEVEL_2, "\n\t"));
157 } DB((dbg, LEVEL_2, "%+F", op->node));
158 if ((op->flags & FLAG_KILL_ALL) == FLAG_KILL_ALL)
159 DB((dbg, LEVEL_2, "X"));
160 else if (op->flags & FLAG_KILL_LOADS)
161 DB((dbg, LEVEL_2, "L"));
162 else if (op->flags & FLAG_KILL_STORES)
163 DB((dbg, LEVEL_2, "S"));
164 DB((dbg, LEVEL_2, ", "));
168 DB((dbg, LEVEL_2, "\n}\n\n"));
173 * Dumps the current set.
175 * @param bl current block
176 * @param s name of the set
178 static void dump_curr(block_t *bl, const char *s) {
180 unsigned end = env.n_mem_ops * 2 - 1;
183 DB((dbg, LEVEL_2, "%s[%+F] = {", s, bl->block));
185 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
186 memop_t *op = env.curr_id_2_memop[pos];
189 DB((dbg, LEVEL_2, "\n\t"));
191 DB((dbg, LEVEL_2, "<%+F, %+F>, ", op->value.address, op->value.value));
194 DB((dbg, LEVEL_2, "\n}\n"));
198 #define dump_block_list()
199 #define dump_curr(bl, s)
200 #endif /* DEBUG_libfirm */
202 /** Get the block entry for a block node */
203 static block_t *get_block_entry(const ir_node *block) {
204 assert(is_Block(block));
206 return get_irn_link(block);
209 /** Get the memop entry for a memory operation node */
210 static memop_t *get_irn_memop(const ir_node *irn) {
211 assert(! is_Block(irn));
212 return get_irn_link(irn);
216 * Walk over the memory edges from definition to users.
217 * This ensures, that even operation without memory output are found.
219 * @param irn start node
220 * @param pre pre walker function
221 * @param post post walker function
222 * @param ctx context parameter for the walker functions
224 static void walk_memory(ir_node *irn, irg_walk_func *pre, irg_walk_func *post, void *ctx) {
228 mark_irn_visited(irn);
233 mode = get_irn_mode(irn);
234 if (mode == mode_M) {
235 /* every successor uses memory */
236 for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
237 ir_node *succ = get_irn_out(irn, i);
239 if (! irn_visited(succ))
240 walk_memory(succ, pre, post, ctx);
242 } else if (mode == mode_T) {
243 /* only some Proj's uses memory */
244 for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
245 ir_node *proj = get_irn_out(irn, i);
247 if (get_irn_mode(proj) == mode_M && ! irn_visited(proj))
248 walk_memory(proj, pre, post, ctx);
256 * Walks over all memory nodes of a graph.
259 * @param pre pre walker function
260 * @param post post walker function
261 * @param ctx context parameter for the walker functions
263 static void walk_memory_irg(ir_graph *irg, irg_walk_func pre, irg_walk_func post, void *ctx) {
264 inc_irg_visited(irg);
266 ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
269 * there are two possible sources for memory: initial_mem and nomem
270 * we ignore nomem as this should NOT change the memory
272 walk_memory(get_irg_initial_mem(irg), pre, post, ctx);
274 ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
278 * Block walker: allocate an block entry for every block.
280 static void prepare_blocks(ir_node *block, void *ctx) {
281 block_t *entry = obstack_alloc(&env.obst, sizeof(*entry));
285 entry->memop_forward = NULL;
286 entry->memop_backward = NULL;
287 entry->avail_out = NULL;
288 entry->id_2_memop_avail = NULL;
289 entry->anticL_in = NULL;
290 entry->id_2_memop_antic = NULL;
291 entry->block = block;
292 entry->forward_next = env.forward;
293 entry->backward_next = NULL;
295 set_irn_link(block, entry);
297 /* create the list in inverse order */
299 /* remember temporary the last one */
300 env.backward = entry;
304 * Block walker: create backward links for the memops of a block.
306 static void collect_backward(ir_node *block, void *ctx) {
307 block_t *entry = get_block_entry(block);
313 * Do NOT link in the end block yet. We want it to be
314 * the first in the list. This is NOT guaranteed by the walker
315 * if we have endless loops.
317 if (block != env.end_bl) {
318 entry->backward_next = env.backward;
320 /* create the list in inverse order */
321 env.backward = entry;
324 /* create backward links for all memory ops */
326 for (op = entry->memop_forward; op != NULL; op = op->next) {
330 entry->memop_backward = last;
336 * @param irn the IR-node representing the memop
338 static memop_t *alloc_memop(ir_node *irn) {
339 memop_t *m = obstack_alloc(&env.obst, sizeof(*m));
341 m->value.address = NULL;
342 m->value.value = NULL;
343 m->value.mode = NULL;
351 memset(m->projs, 0, sizeof(m->projs));
353 set_irn_link(irn, m);
358 * Create a memop for a Phi-replacement.
360 * @param op the memop to clone
361 * @param phi the Phi-node representing the new value
363 static memop_t *clone_memop_phi(memop_t *op, ir_node *phi) {
364 memop_t *m = obstack_alloc(&env.obst, sizeof(*m));
366 m->value = op->value;
367 m->value.value = phi;
374 set_irn_link(phi, m);
379 * Register an address and allocate an ID for it.
381 * @param adr the IR-node representing the address
383 static unsigned register_address(ir_node *adr) {
384 address_entry *entry;
386 /* skip Confirms and Casts */
388 if (is_Confirm(adr)) {
389 adr = get_Confirm_value(adr);
393 adr = get_Cast_op(adr);
397 entry = ir_nodemap_get(&env.adr_map, adr);
401 entry = obstack_alloc(&env.obst, sizeof(*entry));
403 entry->id = env.curr_adr_id++;
404 ir_nodemap_insert(&env.adr_map, adr, entry);
406 DB((dbg, LEVEL_3, "ADDRESS %+F has ID %u\n", adr, entry->id));
412 * Return the memory properties of a call node.
414 * @param call the call node
416 * return a bitset of mtp_property_const and mtp_property_pure
418 static unsigned get_Call_memory_properties(ir_node *call) {
419 ir_type *call_tp = get_Call_type(call);
420 unsigned prop = get_method_additional_properties(call_tp);
422 /* check first the call type */
423 if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
424 /* try the called entity */
425 ir_node *ptr = get_Call_ptr(call);
427 if (is_Global(ptr)) {
428 ir_entity *ent = get_Global_entity(ptr);
430 prop = get_entity_additional_properties(ent);
433 return prop & (mtp_property_const|mtp_property_pure);
437 * Returns an entity if the address ptr points to a constant one.
439 * @param ptr the address
441 * @return an entity or NULL
443 static ir_entity *find_constant_entity(ir_node *ptr)
446 if (is_SymConst(ptr) && get_SymConst_kind(ptr) == symconst_addr_ent) {
447 return get_SymConst_entity(ptr);
448 } else if (is_Sel(ptr)) {
449 ir_entity *ent = get_Sel_entity(ptr);
450 ir_type *tp = get_entity_owner(ent);
452 /* Do not fiddle with polymorphism. */
453 if (is_Class_type(get_entity_owner(ent)) &&
454 ((get_entity_n_overwrites(ent) != 0) ||
455 (get_entity_n_overwrittenby(ent) != 0) ) )
458 if (is_Array_type(tp)) {
462 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
464 tarval *tlower, *tupper;
465 ir_node *index = get_Sel_index(ptr, i);
466 tarval *tv = computed_value(index);
468 /* check if the index is constant */
469 if (tv == tarval_bad)
472 bound = get_array_lower_bound(tp, i);
473 tlower = computed_value(bound);
474 bound = get_array_upper_bound(tp, i);
475 tupper = computed_value(bound);
477 if (tlower == tarval_bad || tupper == tarval_bad)
480 if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
482 if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
485 /* ok, bounds check finished */
489 if (variability_constant == get_entity_variability(ent))
493 ptr = get_Sel_ptr(ptr);
494 } else if (is_Add(ptr)) {
495 ir_node *l = get_Add_left(ptr);
496 ir_node *r = get_Add_right(ptr);
498 if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
500 else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
505 /* for now, we support only one addition, reassoc should fold all others */
506 if (! is_SymConst(ptr) && !is_Sel(ptr))
508 } else if (is_Sub(ptr)) {
509 ir_node *l = get_Sub_left(ptr);
510 ir_node *r = get_Sub_right(ptr);
512 if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
516 /* for now, we support only one subtraction, reassoc should fold all others */
517 if (! is_SymConst(ptr) && !is_Sel(ptr))
522 } /* find_constant_entity */
525 * Return the Selection index of a Sel node from dimension n
527 static long get_Sel_array_index_long(ir_node *n, int dim) {
528 ir_node *index = get_Sel_index(n, dim);
529 assert(is_Const(index));
530 return get_tarval_long(get_Const_tarval(index));
531 } /* get_Sel_array_index_long */
534 * Returns the accessed component graph path for an
535 * node computing an address.
537 * @param ptr the node computing the address
538 * @param depth current depth in steps upward from the root
541 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
542 compound_graph_path *res = NULL;
543 ir_entity *root, *field, *ent;
544 int path_len, pos, idx;
548 if (is_SymConst(ptr)) {
549 /* a SymConst. If the depth is 0, this is an access to a global
550 * entity and we don't need a component path, else we know
551 * at least its length.
553 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
554 root = get_SymConst_entity(ptr);
555 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
556 } else if (is_Sel(ptr)) {
557 /* it's a Sel, go up until we find the root */
558 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
562 /* fill up the step in the path at the current position */
563 field = get_Sel_entity(ptr);
564 path_len = get_compound_graph_path_length(res);
565 pos = path_len - depth - 1;
566 set_compound_graph_path_node(res, pos, field);
568 if (is_Array_type(get_entity_owner(field))) {
569 assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
570 set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
572 } else if (is_Add(ptr)) {
573 ir_node *l = get_Add_left(ptr);
574 ir_node *r = get_Add_right(ptr);
575 ir_mode *mode = get_irn_mode(ptr);
578 if (is_Const(r) && get_irn_mode(l) == mode) {
580 tv = get_Const_tarval(r);
583 tv = get_Const_tarval(l);
586 mode = get_tarval_mode(tv);
589 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
591 field = get_Sel_entity(ptr);
593 field = get_SymConst_entity(ptr);
596 for (ent = field;;) {
598 tarval *sz, *tv_index, *tlower, *tupper;
601 tp = get_entity_type(ent);
602 if (! is_Array_type(tp))
604 ent = get_array_element_entity(tp);
605 size = get_type_size_bytes(get_entity_type(ent));
606 sz = new_tarval_from_long(size, mode);
608 tv_index = tarval_div(tmp, sz);
609 tmp = tarval_mod(tmp, sz);
611 if (tv_index == tarval_bad || tmp == tarval_bad)
614 assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
615 bound = get_array_lower_bound(tp, 0);
616 tlower = computed_value(bound);
617 bound = get_array_upper_bound(tp, 0);
618 tupper = computed_value(bound);
620 if (tlower == tarval_bad || tupper == tarval_bad)
623 if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
625 if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
628 /* ok, bounds check finished */
631 if (! tarval_is_null(tmp)) {
632 /* access to some struct/union member */
636 /* should be at least ONE array */
640 res = rec_get_accessed_path(ptr, depth + idx);
644 path_len = get_compound_graph_path_length(res);
645 pos = path_len - depth - idx;
647 for (ent = field;;) {
649 tarval *sz, *tv_index;
652 tp = get_entity_type(ent);
653 if (! is_Array_type(tp))
655 ent = get_array_element_entity(tp);
656 set_compound_graph_path_node(res, pos, ent);
658 size = get_type_size_bytes(get_entity_type(ent));
659 sz = new_tarval_from_long(size, mode);
661 tv_index = tarval_div(tv, sz);
662 tv = tarval_mod(tv, sz);
664 /* worked above, should work again */
665 assert(tv_index != tarval_bad && tv != tarval_bad);
667 /* bounds already checked above */
668 index = get_tarval_long(tv_index);
669 set_compound_graph_path_array_index(res, pos, index);
672 } else if (is_Sub(ptr)) {
673 ir_node *l = get_Sub_left(ptr);
674 ir_node *r = get_Sub_right(ptr);
677 tv = get_Const_tarval(r);
682 } /* rec_get_accessed_path */
685 * Returns an access path or NULL. The access path is only
686 * valid, if the graph is in phase_high and _no_ address computation is used.
688 static compound_graph_path *get_accessed_path(ir_node *ptr) {
689 compound_graph_path *gr = rec_get_accessed_path(ptr, 0);
691 } /* get_accessed_path */
693 typedef struct path_entry {
695 struct path_entry *next;
699 static ir_node *rec_find_compound_ent_value(ir_node *ptr, path_entry *next) {
700 path_entry entry, *p;
701 ir_entity *ent, *field;
702 ir_initializer_t *initializer;
708 if (is_SymConst(ptr)) {
710 ent = get_SymConst_entity(ptr);
711 initializer = get_entity_initializer(ent);
712 for (p = next; p != NULL;) {
713 if (initializer->kind != IR_INITIALIZER_COMPOUND)
715 n = get_initializer_compound_n_entries(initializer);
716 tp = get_entity_type(ent);
718 if (is_Array_type(tp)) {
719 ent = get_array_element_entity(tp);
724 initializer = get_initializer_compound_value(initializer, 0);
728 if (p->index >= (int) n)
730 initializer = get_initializer_compound_value(initializer, p->index);
735 tp = get_entity_type(ent);
736 while (is_Array_type(tp)) {
737 ent = get_array_element_entity(tp);
738 tp = get_entity_type(ent);
740 n = get_initializer_compound_n_entries(initializer);
743 initializer = get_initializer_compound_value(initializer, 0);
746 switch (initializer->kind) {
747 case IR_INITIALIZER_CONST:
748 return get_initializer_const_value(initializer);
749 case IR_INITIALIZER_TARVAL:
750 case IR_INITIALIZER_NULL:
754 } else if (is_Sel(ptr)) {
755 entry.ent = field = get_Sel_entity(ptr);
756 tp = get_entity_owner(field);
757 if (is_Array_type(tp)) {
758 assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
759 entry.index = get_Sel_array_index_long(ptr, 0) - get_array_lower_bound_int(tp, 0);
761 int i, n_members = get_compound_n_members(tp);
762 for (i = 0; i < n_members; ++i) {
763 if (get_compound_member(tp, i) == field)
766 if (i >= n_members) {
767 /* not found: should NOT happen */
772 return rec_find_compound_ent_value(get_Sel_ptr(ptr), &entry);
773 } else if (is_Add(ptr)) {
774 ir_node *l = get_Add_left(ptr);
775 ir_node *r = get_Add_right(ptr);
781 tv = get_Const_tarval(r);
784 tv = get_Const_tarval(l);
787 mode = get_tarval_mode(tv);
789 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
791 field = get_Sel_entity(ptr);
793 field = get_SymConst_entity(ptr);
796 /* count needed entries */
798 for (ent = field;;) {
799 tp = get_entity_type(ent);
800 if (! is_Array_type(tp))
802 ent = get_array_element_entity(tp);
805 /* should be at least ONE entry */
809 /* allocate the right number of entries */
810 NEW_ARR_A(path_entry, p, pos);
814 for (ent = field;;) {
816 tarval *sz, *tv_index, *tlower, *tupper;
820 tp = get_entity_type(ent);
821 if (! is_Array_type(tp))
823 ent = get_array_element_entity(tp);
825 p[pos].next = &p[pos + 1];
827 size = get_type_size_bytes(get_entity_type(ent));
828 sz = new_tarval_from_long(size, mode);
830 tv_index = tarval_div(tv, sz);
831 tv = tarval_mod(tv, sz);
833 if (tv_index == tarval_bad || tv == tarval_bad)
836 assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
837 bound = get_array_lower_bound(tp, 0);
838 tlower = computed_value(bound);
839 bound = get_array_upper_bound(tp, 0);
840 tupper = computed_value(bound);
842 if (tlower == tarval_bad || tupper == tarval_bad)
845 if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
847 if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
850 /* ok, bounds check finished */
851 index = get_tarval_long(tv_index);
852 p[pos].index = index;
855 if (! tarval_is_null(tv)) {
856 /* hmm, wrong access */
859 p[pos - 1].next = next;
860 return rec_find_compound_ent_value(ptr, p);
861 } else if (is_Sub(ptr)) {
862 ir_node *l = get_Sub_left(ptr);
863 ir_node *r = get_Sub_right(ptr);
866 tv = get_Const_tarval(r);
871 } /* rec_find_compound_ent_value */
873 static ir_node *find_compound_ent_value(ir_node *ptr) {
874 return rec_find_compound_ent_value(ptr, NULL);
875 } /* find_compound_ent_value */
878 * Mark a Load memop to be replace by a definition
880 * @param op the Load memop
882 static void mark_replace_load(memop_t *op, ir_node *def) {
884 op->flags |= FLAG_KILLED_NODE;
886 } /* mark_replace_load */
889 * Mark a Store memop to be removed.
891 * @param op the Store memop
893 static void mark_remove_store(memop_t *op) {
894 op->flags |= FLAG_KILLED_NODE;
896 } /* mark_remove_store */
899 * Update a memop for a Load.
903 static void update_Load_memop(memop_t *m) {
905 ir_node *load = m->node;
909 if (get_Load_volatility(load) == volatility_is_volatile)
910 m->flags |= FLAG_IGNORE;
912 ptr = get_Load_ptr(load);
914 m->value.address = ptr;
916 for (i = get_irn_n_outs(load) - 1; i >= 0; --i) {
917 ir_node *proj = get_irn_out(load, i);
920 /* beware of keep edges */
924 pn = get_Proj_proj(proj);
928 m->value.value = proj;
929 m->value.mode = get_irn_mode(proj);
931 case pn_Load_X_except:
932 m->flags |= FLAG_EXCEPTION;
937 case pn_Load_X_regular:
940 panic("Unsupported Proj from Load %+F", proj);
944 /* check if we can determine the entity that will be loaded */
945 ent = find_constant_entity(ptr);
948 allocation_static == get_entity_allocation(ent) &&
949 visibility_external_allocated != get_entity_visibility(ent)) {
950 /* a static allocation that is not external: there should be NO exception
951 * when loading even if we cannot replace the load itself. */
952 ir_node *value = NULL;
954 /* no exception, clear the m fields as it might be checked later again */
955 if (m->projs[pn_Load_X_except]) {
956 exchange(m->projs[pn_Load_X_except], new_Bad());
957 m->projs[pn_Load_X_except] = NULL;
958 m->flags &= ~FLAG_EXCEPTION;
961 if (m->projs[pn_Load_X_regular]) {
962 exchange(m->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
963 m->projs[pn_Load_X_regular] = NULL;
967 if (variability_constant == get_entity_variability(ent)) {
968 if (is_atomic_entity(ent)) {
969 /* Might not be atomic after lowering of Sels. In this case we
970 * could also load, but it's more complicated. */
971 /* more simpler case: we load the content of a constant value:
972 * replace it by the constant itself */
973 value = get_atomic_ent_value(ent);
974 } else if (ent->has_initializer) {
975 /* new style initializer */
976 value = find_compound_ent_value(ptr);
978 /* old style initializer */
979 compound_graph_path *path = get_accessed_path(ptr);
982 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
984 value = get_compound_ent_value_by_path(ent, path);
985 DB((dbg, LEVEL_1, " Constant access at %F%F resulted in %+F\n", ent, path, value));
986 free_compound_graph_path(path);
990 value = can_replace_load_by_const(load, value);
994 /* we completely replace the load by this value */
995 DB((dbg, LEVEL_1, "Replacing Load %+F by constant %+F\n", m->node, value));
996 mark_replace_load(m, value);
1001 if (m->value.value != NULL && !(m->flags & FLAG_IGNORE)) {
1002 /* only create an address if this node is NOT killed immediately or ignored */
1003 m->value.id = register_address(ptr);
1006 /* no user, KILL it */
1007 m->flags |= FLAG_KILLED_NODE;
1012 * Update a memop for a Store.
1014 * @param m the memop
1016 static void update_Store_memop(memop_t *m) {
1018 ir_node *store = m->node;
1019 ir_node *adr = get_Store_ptr(store);
1021 if (get_Store_volatility(store) == volatility_is_volatile) {
1022 m->flags |= FLAG_IGNORE;
1024 /* only create an address if this node is NOT ignored */
1025 m->value.id = register_address(adr);
1029 m->value.address = adr;
1031 for (i = get_irn_n_outs(store) - 1; i >= 0; --i) {
1032 ir_node *proj = get_irn_out(store, i);
1035 /* beware of keep edges */
1039 pn = get_Proj_proj(proj);
1040 m->projs[pn] = proj;
1042 case pn_Store_X_except:
1043 m->flags |= FLAG_EXCEPTION;
1048 case pn_Store_X_regular:
1051 panic("Unsupported Proj from Store %+F", proj);
1054 m->value.value = get_Store_value(store);
1055 m->value.mode = get_irn_mode(m->value.value);
1059 * Update a memop for a Call.
1061 * @param m the memop
1063 static void update_Call_memop(memop_t *m) {
1064 ir_node *call = m->node;
1065 unsigned prop = get_Call_memory_properties(call);
1068 if (prop & mtp_property_const) {
1069 /* A constant call did NOT use memory at all, we
1070 can kick it from the list. */
1071 } else if (prop & mtp_property_pure) {
1072 /* pure calls READ memory */
1073 m->flags = FLAG_KILL_STORES;
1075 m->flags = FLAG_KILL_ALL;
1077 for (i = get_irn_n_outs(call) - 1; i >= 0; --i) {
1078 ir_node *proj = get_irn_out(call, i);
1080 /* beware of keep edges */
1084 switch (get_Proj_proj(proj)) {
1085 case pn_Call_X_except:
1086 m->flags |= FLAG_EXCEPTION;
1088 case pn_Call_M_regular:
1096 * Update a memop for a Div/Mod/Quot/DivMod.
1098 * @param m the memop
1100 static void update_DivOp_memop(memop_t *m) {
1101 ir_node *div = m->node;
1104 for (i = get_irn_n_outs(div) - 1; i >= 0; --i) {
1105 ir_node *proj = get_irn_out(div, i);
1107 /* beware of keep edges */
1111 switch (get_Proj_proj(proj)) {
1112 case pn_Generic_X_except:
1113 m->flags |= FLAG_EXCEPTION;
1115 case pn_Generic_M_regular:
1123 * Update a memop for a Phi.
1125 * @param m the memop
1127 static void update_Phi_memop(memop_t *m) {
1128 /* the Phi is it's own mem */
1133 * Memory walker: collect all memory ops and build topological lists.
1135 static void collect_memops(ir_node *irn, void *ctx) {
1142 /* we can safely ignore ProjM's except the initial memory */
1143 if (irn != get_irg_initial_mem(current_ir_graph))
1147 op = alloc_memop(irn);
1148 block = get_nodes_block(irn);
1149 entry = get_block_entry(block);
1152 update_Phi_memop(op);
1153 /* Phis must be always placed first */
1154 op->next = entry->memop_forward;
1155 entry->memop_forward = op;
1156 if (entry->memop_backward == NULL)
1157 entry->memop_backward = op;
1159 switch (get_irn_opcode(irn)) {
1161 update_Load_memop(op);
1164 update_Store_memop(op);
1167 update_Call_memop(op);
1174 /* initial memory */
1179 /* we can those to find the memory edge */
1185 update_DivOp_memop(op);
1189 /* TODO: handle some builtins */
1191 /* unsupported operation */
1192 op->flags = FLAG_KILL_ALL;
1196 /* all other should be placed last */
1197 if (entry->memop_backward == NULL) {
1198 entry->memop_forward = entry->memop_backward = op;
1200 entry->memop_backward->next = op;
1201 entry->memop_backward = op;
1207 * Find an address in the current set.
1209 * @param value the value to be searched for
1211 static memop_t *find_address(const value_t *value) {
1212 if (rbitset_is_set(env.curr_set, value->id)) {
1213 memop_t *res = env.curr_id_2_memop[value->id];
1215 if (res->value.mode == value->mode)
1217 /* allow hidden casts */
1218 if (get_mode_arithmetic(res->value.mode) == irma_twos_complement &&
1219 get_mode_arithmetic(value->mode) == irma_twos_complement &&
1220 get_mode_size_bits(res->value.mode) == get_mode_size_bits(value->mode))
1227 * Find an address in the avail_out set.
1229 * @param bl the block
1230 * @param value the value to be searched for
1232 static memop_t *find_address_avail(const block_t *bl, const value_t *value) {
1233 if (rbitset_is_set(bl->avail_out, value->id)) {
1234 memop_t *res = bl->id_2_memop_avail[value->id];
1236 if (res->value.mode == value->mode)
1238 /* allow hidden casts */
1239 if (get_mode_arithmetic(res->value.mode) == irma_twos_complement &&
1240 get_mode_arithmetic(value->mode) == irma_twos_complement &&
1241 get_mode_size_bits(res->value.mode) == get_mode_size_bits(value->mode))
1248 * Kill all Loads from the current set.
1250 static void kill_all_loads(void) {
1252 unsigned end = env.n_mem_ops * 2 - 1;
1254 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
1255 memop_t *op = env.curr_id_2_memop[pos];
1257 if (! is_Store(op->node))
1258 rbitset_clear(env.curr_set, pos);
1263 * Kill all Stores from the current set.
1265 static void kill_all_stores(void) {
1267 unsigned end = env.n_mem_ops * 2 - 1;
1269 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
1270 memop_t *op = env.curr_id_2_memop[pos];
1272 if (is_Store(op->node))
1273 rbitset_clear(env.curr_set, pos);
1278 * Kill all addresses from the current set.
1280 static void kill_all(void) {
1281 rbitset_clear_all(env.curr_set, env.rbs_size);
1284 rbitset_set(env.curr_set, env.rbs_size - 1);
1289 * Kill Stores that are not alias free due to a Load value from the current set.
1291 * @param value the Load value
1293 static void kill_stores(const value_t *value) {
1295 unsigned end = env.n_mem_ops * 2 - 1;
1297 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
1298 memop_t *op = env.curr_id_2_memop[pos];
1300 if (is_Store(op->node)) {
1301 if (ir_no_alias != get_alias_relation(current_ir_graph, value->address, value->mode,
1302 op->value.address, op->value.mode)) {
1303 rbitset_clear(env.curr_set, pos);
1304 env.curr_id_2_memop[pos] = NULL;
1311 * Kill memops that are not alias free due to a Store value from the current set.
1313 * @param value the Store value
1315 static void kill_memops(const value_t *value) {
1317 unsigned end = env.n_mem_ops * 2 - 1;
1319 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
1320 memop_t *op = env.curr_id_2_memop[pos];
1322 if (ir_no_alias != get_alias_relation(current_ir_graph, value->address, value->mode,
1323 op->value.address, op->value.mode)) {
1324 rbitset_clear(env.curr_set, pos);
1325 env.curr_id_2_memop[pos] = NULL;
1331 * Add the value of a memop to the current set.
1333 * @param op the memory op
1335 static void add_memop(memop_t *op) {
1336 rbitset_set(env.curr_set, op->value.id);
1337 env.curr_id_2_memop[op->value.id] = op;
1341 * Add the value of a memop to the avail_out set.
1343 * @param bl the block
1344 * @param op the memory op
1346 static void add_memop_avail(block_t *bl, memop_t *op) {
1347 rbitset_set(bl->avail_out, op->value.id);
1348 bl->id_2_memop_avail[op->value.id] = op;
1352 * Update a value of a memop to the avail_out set.
1354 * @param bl the block
1355 * @param op the memory op
1357 static void update_memop_avail(block_t *bl, memop_t *op) {
1358 if (rbitset_is_set(bl->avail_out, op->value.id))
1359 bl->id_2_memop_avail[op->value.id] = op;
1363 * Check, if we can convert a value of one mode to another mode
1364 * without changing the representation of bits.
1366 static int can_convert_to(const ir_mode *from, const ir_mode *to) {
1367 if (get_mode_arithmetic(from) == irma_twos_complement &&
1368 get_mode_arithmetic(to) == irma_twos_complement &&
1369 get_mode_size_bits(from) == get_mode_size_bits(to))
1375 * Add a Conv if needed.
1377 static ir_node *conv_to(ir_node *irn, ir_mode *mode) {
1378 ir_mode *other = get_irn_mode(irn);
1379 if (other != mode) {
1380 /* different modes: check if conversion is possible without changing the bits */
1381 if (can_convert_to(other, mode)) {
1382 ir_node *block = get_nodes_block(irn);
1383 return new_r_Conv(current_ir_graph, block, irn, mode);
1385 /* otherwise not possible ... yet */
1392 * Do forward dataflow analysis on the given block and calculate the
1393 * GEN and KILL in the current (avail) set.
1395 * @param bl the block
1397 static void calc_gen_kill_avail(block_t *bl) {
1401 for (op = bl->memop_forward; op != NULL; op = op->next) {
1402 switch (get_irn_opcode(op->node)) {
1410 if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
1411 /* do we have this already? */
1412 memop_t *other = find_address(&op->value);
1413 if (other != NULL && other != op) {
1414 def = conv_to(other->value.value, op->value.mode);
1416 #ifdef DEBUG_libfirm
1417 if (is_Store(other->node)) {
1419 DB((dbg, LEVEL_1, "RAW %+F <- %+F(%+F)\n", op->node, def, other->node));
1422 DB((dbg, LEVEL_1, "RAR %+F <- %+F(%+F)\n", op->node, def, other->node));
1425 mark_replace_load(op, def);
1431 /* add this value */
1432 kill_stores(&op->value);
1438 if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
1439 /* do we have this store already */
1440 memop_t *other = find_address(&op->value);
1441 if (other != NULL) {
1442 if (is_Store(other->node)) {
1443 if (op != other && get_nodes_block(other->node) == get_nodes_block(op->node)) {
1445 * A WAW in the same block we can kick the first store.
1446 * This is a shortcut: we know that the second Store will be anticipated
1449 DB((dbg, LEVEL_1, "WAW %+F <- %+F\n", op->node, other->node));
1450 mark_remove_store(other);
1451 /* FIXME: a Load might be get freed due to this killed store */
1453 } else if (other->value.value == op->value.value) {
1455 DB((dbg, LEVEL_1, "WAR %+F <- %+F\n", op->node, other->node));
1456 mark_remove_store(op);
1458 /* we overwrite the value that was loaded */
1462 /* add this value */
1463 kill_memops(&op->value);
1469 switch (op->flags & (FLAG_KILL_LOADS|FLAG_KILL_STORES)) {
1470 case FLAG_KILL_LOADS|FLAG_KILL_STORES:
1473 case FLAG_KILL_LOADS:
1476 case FLAG_KILL_STORES:
1486 #define BYTE_SIZE(x) (((x) + 7) >> 3)
1489 * Do forward dataflow analysis on a given block to calculate the avail_out set
1490 * for this block only.
1492 * @param block the block
1494 static void forward_avail(block_t *bl) {
1495 /* fill the data from the current block */
1496 env.curr_id_2_memop = bl->id_2_memop_avail;
1497 env.curr_set = bl->avail_out;
1499 calc_gen_kill_avail(bl);
1500 dump_curr(bl, "Avail_out");
1504 * Do backward dataflow analysis on a given block to calculate the antic set
1505 * of Loaded addresses.
1507 * @param bl the block
1509 * @return non-zero if the set has changed since last iteration
1511 static int backward_antic(block_t *bl) {
1513 int n = get_Block_n_cfg_outs(bl->block);
1516 ir_node *succ = get_Block_cfg_out(bl->block, 0);
1517 block_t *succ_bl = get_block_entry(succ);
1520 rbitset_cpy(env.curr_set, succ_bl->anticL_in, env.rbs_size);
1521 memcpy(env.curr_id_2_memop, succ_bl->id_2_memop_antic, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1523 for (i = n - 1; i > 0; --i) {
1524 ir_node *succ = get_Block_cfg_out(bl->block, i);
1525 block_t *succ_bl = get_block_entry(succ);
1527 rbitset_and(env.curr_set, succ_bl->anticL_in, env.rbs_size);
1530 /* block ends with a noreturn call */
1535 /* cleanup: kill those Loads which address is not available */
1536 for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
1537 memop_t *op = succ_bl->id_2_memop[pos];
1538 ir_node *ptr = get_Load_ptr(op->node);
1539 ir_node *ptr_bl = get_nodes_block(ptr);
1541 if (!block_dominates(ptr_bl, bl->block))
1542 rbitset_clear(env.curr_set, pos);
1546 dump_curr(bl, "AnticL_out");
1548 for (op = bl->memop_backward; op != NULL; op = op->prev) {
1549 switch (get_irn_opcode(op->node)) {
1557 if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
1563 if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
1564 /* a Store: check which memops must be killed */
1565 kill_memops(&op->value);
1569 switch (op->flags & (FLAG_KILL_LOADS|FLAG_KILL_STORES)) {
1570 case FLAG_KILL_LOADS|FLAG_KILL_STORES:
1573 case FLAG_KILL_LOADS:
1576 case FLAG_KILL_STORES:
1577 /*kill_all_stores();*/
1585 memcpy(bl->id_2_memop_antic, env.curr_id_2_memop, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1586 if (! rbitset_equal(bl->anticL_in, env.curr_set, env.rbs_size)) {
1588 rbitset_cpy(bl->anticL_in, env.curr_set, env.rbs_size);
1589 dump_curr(bl, "AnticL_in*");
1592 dump_curr(bl, "AnticL_in");
1597 * Replace a Load memop by a already known value.
1599 * @param op the Load memop
1601 static void replace_load(memop_t *op) {
1602 ir_node *load = op->node;
1603 ir_node *def = skip_Id(op->replace);
1608 DB((dbg, LEVEL_1, "Replacing %+F by definition %+F\n", load, is_Proj(def) ? get_Proj_pred(def) : def));
1610 if (op->flags & FLAG_EXCEPTION) {
1611 /* bad: this node is unused and executed for exception only */
1612 DB((dbg, LEVEL_1, "Unused %+F executed for exception only ...\n", load));
1615 DB((dbg, LEVEL_1, "Killing unused %+F\n", load));
1618 if (op->mem != NULL) {
1619 /* in rare cases a Load might have NO memory */
1620 exchange(op->mem, get_Load_mem(load));
1622 proj = op->projs[pn_Load_res];
1624 mode = get_irn_mode(proj);
1625 if (get_irn_mode(def) != mode) {
1627 dbg_info *db = get_irn_dbg_info(load);
1628 ir_node *block = get_nodes_block(proj);
1629 def = new_rd_Conv(db, current_ir_graph, block, def, mode);
1631 exchange(proj, def);
1633 proj = op->projs[pn_Load_X_except];
1635 exchange(proj, new_Bad());
1637 proj = op->projs[pn_Load_X_regular];
1639 exchange(proj, new_r_Jmp(current_ir_graph, get_nodes_block(load)));
1644 * Remove a Store memop.
1646 * @param op the Store memop
1648 static void remove_store(memop_t *op) {
1649 ir_node *store = op->node;
1652 DB((dbg, LEVEL_1, "Removing %+F\n", store));
1654 if (op->mem != NULL) {
1655 /* in rare cases a Store might have no memory */
1656 exchange(op->mem, get_Store_mem(store));
1658 proj = op->projs[pn_Store_X_except];
1660 exchange(proj, new_Bad());
1662 proj = op->projs[pn_Store_X_regular];
1664 exchange(proj, new_r_Jmp(current_ir_graph, get_nodes_block(store)));
1670 * Do all necessary replacements for a given block.
1672 * @param bl the block
1674 static void do_replacements(block_t *bl) {
1677 for (op = bl->memop_forward; op != NULL; op = op->next) {
1678 if (op->flags & FLAG_KILLED_NODE) {
1679 switch (get_irn_opcode(op->node)) {
1692 * Calculate the Avail_out sets for all basic blocks.
1694 static void calcAvail(void) {
1695 memop_t **tmp_memop = env.curr_id_2_memop;
1696 unsigned *tmp_set = env.curr_set;
1699 /* calculate avail_out */
1700 DB((dbg, LEVEL_2, "Calculate Avail_out\n"));
1702 /* iterate over all blocks in in any order, skip the start block */
1703 for (bl = env.forward->forward_next; bl != NULL; bl = bl->forward_next) {
1707 /* restore the current sets */
1708 env.curr_id_2_memop = tmp_memop;
1709 env.curr_set = tmp_set;
1713 * Calculate the Antic_in sets for all basic blocks.
1715 static void calcAntic(void) {
1718 /* calculate antic_out */
1719 DB((dbg, LEVEL_2, "Calculate Antic_in\n"));
1724 DB((dbg, LEVEL_2, "Iteration %d:\n=========\n", i));
1728 /* over all blocks in reverse post order */
1729 for (bl = env.backward->backward_next; bl != NULL; bl = bl->backward_next) {
1730 need_iter |= backward_antic(bl);
1733 } while (need_iter);
1734 DB((dbg, LEVEL_2, "Get anticipated Load set after %d iterations\n", i));
1738 * Return the node representing the last memory in a block.
1740 * @param bl the block
1742 static ir_node *find_first_memory(block_t *bl) {
1744 if (bl->memop_forward != NULL) {
1745 return bl->memop_forward->node;
1747 /* if there is NO memory in this block, go to the post dominator */
1748 bl = get_block_entry(get_Block_ipostdom(bl->block));
1753 * Return the node representing the last memory in a block.
1755 * @param bl the block
1757 static ir_node *find_last_memory(block_t *bl) {
1759 if (bl->memop_backward != NULL) {
1760 return bl->memop_backward->mem;
1762 /* if there is NO memory in this block, go to the dominator */
1763 bl = get_block_entry(get_Block_idom(bl->block));
1768 * Reroute all memory users of old memory
1769 * to a new memory IR-node.
1771 * @param omem the old memory IR-node
1772 * @param nmem the new memory IR-node
1774 static void reroute_all_mem_users(ir_node *omem, ir_node *nmem) {
1777 for (i = get_irn_n_outs(omem) - 1; i >= 0; --i) {
1779 ir_node *user = get_irn_out_ex(omem, i, &n_pos);
1781 set_irn_n(user, n_pos, nmem);
1784 /* all edges previously point to omem now point to nmem */
1785 nmem->out = omem->out;
1789 * Reroute memory users of old memory that are dominated by a given block
1790 * to a new memory IR-node.
1792 * @param omem the old memory IR-node
1793 * @param nmem the new memory IR-node
1794 * @param pass_bl the block the memory must pass
1796 static void reroute_mem_through(ir_node *omem, ir_node *nmem, ir_node *pass_bl) {
1797 int i, j, n = get_irn_n_outs(omem);
1798 ir_def_use_edge *edges = NEW_ARR_D(ir_def_use_edge, &env.obst, n + 1);
1800 for (i = j = 0; i < n; ++i) {
1802 ir_node *user = get_irn_out_ex(omem, i, &n_pos);
1803 ir_node *use_bl = get_nodes_block(user);
1807 use_bl = get_Block_cfgpred_block(use_bl, n_pos);
1809 if (block_dominates(pass_bl, use_bl)) {
1810 /* found an user that is dominated */
1812 edges[j].pos = n_pos;
1813 edges[j].use = user;
1815 set_irn_n(user, n_pos, nmem);
1819 /* Modify the out structure: we create a new out edge array on our
1820 temporary obstack here. This should be no problem, as we invalidate the edges
1821 at the end either. */
1822 /* first entry is used for the length */
1828 * insert Loads, making partly redundant Loads fully redundant
1830 static int insert_Load(block_t *bl) {
1831 ir_node *block = bl->block;
1832 int i, n = get_Block_n_cfgpreds(block);
1834 unsigned end = env.n_mem_ops * 2 - 1;
1836 ir_node *pred = get_Block_cfgpred_block(bl->block, 0);
1837 block_t *pred_bl = get_block_entry(pred);
1839 DB((dbg, LEVEL_3, "processing %+F\n", block));
1841 rbitset_cpy(env.curr_set, pred_bl->avail_out, env.rbs_size);
1847 NEW_ARR_A(ir_node *, ins, n);
1849 /* more than one predecessors, calculate the join for all avail_outs */
1850 for (i = n - 1; i > 0; --i) {
1851 ir_node *pred = skip_Proj(get_Block_cfgpred(block, i));
1852 block_t *pred_bl = get_block_entry(get_nodes_block(pred));
1854 rbitset_and(env.curr_set, pred_bl->avail_out, env.rbs_size);
1856 if (is_Load(pred) || is_Store(pred)) {
1857 /* We reached this block by an exception from a Load or Store:
1858 * the memop creating the exception was NOT completed than, kill it
1860 memop_t *exc_op = get_irn_memop(pred);
1861 rbitset_clear(env.curr_set, exc_op->value.id);
1866 * Ensure that all values are in the map: build Phi's if necessary:
1867 * Note: the last bit is the sentinel and ALWAYS set, so start with -2.
1869 for (pos = env.rbs_size - 2; pos >= 0; --pos) {
1870 if (! rbitset_is_set(env.curr_set, pos))
1871 env.curr_id_2_memop[pos] = NULL;
1873 ir_node *pred = get_Block_cfgpred_block(bl->block, 0);
1874 block_t *pred_bl = get_block_entry(pred);
1879 first = pred_bl->id_2_memop_avail[pos];
1880 ins[0] = first->value.value;
1881 mode = get_irn_mode(ins[0]);
1883 for (i = 1; i < n; ++i) {
1884 pred = get_Block_cfgpred_block(bl->block, i);
1885 pred_bl = get_block_entry(pred);
1887 ins[i] = conv_to(pred_bl->id_2_memop_avail[pos]->value.value, mode);
1888 if (ins[i] != ins[0]) {
1890 if (ins[i] == NULL) {
1891 /* conversion failed */
1901 env.curr_id_2_memop[pos] = first;
1905 ir_node *phi = new_r_Phi(current_ir_graph, bl->block, n, ins, mode);
1906 memop_t *phiop = alloc_memop(phi);
1908 phiop->value = first->value;
1909 phiop->value.value = phi;
1911 /* no need to link it in, as it is a DATA phi */
1913 env.curr_id_2_memop[pos] = phiop;
1915 DB((dbg, LEVEL_3, "Created new %+F on merging value for address %+F\n", phi, first->value.address));
1919 /* not possible because of different modes, delete the entry */
1920 rbitset_clear(env.curr_set, pos);
1926 /* only one predecessor, simply copy the map */
1927 memcpy(env.curr_id_2_memop, pred_bl->id_2_memop_avail, env.rbs_size * sizeof(bl->id_2_memop_avail[0]));
1931 /* recalculate avail by gen and kill */
1932 calc_gen_kill_avail(bl);
1934 if (!rbitset_equal(bl->avail_out, env.curr_set, env.rbs_size)) {
1935 /* the avail set has changed */
1936 rbitset_cpy(bl->avail_out, env.curr_set, env.rbs_size);
1937 memcpy(bl->id_2_memop_avail, env.curr_id_2_memop, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1938 dump_curr(bl, "Avail_out*");
1945 /* check for partly redundant values */
1946 for (pos = rbitset_next(bl->anticL_in, pos, 1); pos != end; pos = rbitset_next(bl->anticL_in, pos + 1, 1)) {
1947 memop_t *op = bl->id_2_memop_antic[pos];
1948 int have_some, all_same;
1951 assert(is_Load(op->node));
1953 if (op->flags & FLAG_KILLED_NODE)
1955 DB((dbg, LEVEL_3, "anticipated %+F\n", op->node));
1960 for (i = n - 1; i >= 0; --i) {
1961 ir_node *pred = get_Block_cfgpred_block(block, i);
1962 block_t *pred_bl = get_block_entry(pred);
1963 memop_t *e = find_address_avail(pred_bl, &op->value);
1964 ir_mode *mode = op->value.mode;
1967 ir_node *block = get_nodes_block(op->value.address);
1968 if (! block_dominates(block, pred)) {
1969 /* cannot place a copy here */
1973 DB((dbg, LEVEL_3, "%+F is not available in predecessor %+F\n", op->node, pred));
1974 pred_bl->avail = NULL;
1977 if (e->value.mode != mode && !can_convert_to(e->value.mode, mode)) {
1978 /* cannot create a Phi due to different modes */
1984 DB((dbg, LEVEL_3, "%+F is available for %+F in predecessor %+F\n", e->node, op->node, pred));
1987 else if (first != e->node)
1991 if (have_some && !all_same) {
1992 ir_mode *mode = op->value.mode;
1995 NEW_ARR_A(ir_node *, in, n);
1997 for (i = n - 1; i >= 0; --i) {
1998 ir_node *pred = get_Block_cfgpred_block(block, i);
1999 block_t *pred_bl = get_block_entry(pred);
2001 if (pred_bl->avail == NULL) {
2002 /* create a new Load here and make to make it fully redundant */
2003 dbg_info *db = get_irn_dbg_info(op->node);
2004 ir_node *last_mem = find_last_memory(pred_bl);
2005 ir_node *load, *def;
2008 assert(last_mem != NULL);
2009 load = new_rd_Load(db, current_ir_graph, pred, last_mem, op->value.address, mode, cons_none);
2010 def = new_r_Proj(current_ir_graph, pred, load, mode, pn_Load_res);
2011 DB((dbg, LEVEL_1, "Created new %+F in %+F for party redundant %+F\n", load, pred, op->node));
2013 new_op = alloc_memop(load);
2014 new_op->mem = new_r_Proj(current_ir_graph, pred, load, mode_M, pn_Load_M);
2015 new_op->value.address = op->value.address;
2016 new_op->value.id = op->value.id;
2017 new_op->value.mode = mode;
2018 new_op->value.value = def;
2020 new_op->projs[pn_Load_M] = new_op->mem;
2021 new_op->projs[pn_Load_res] = def;
2023 new_op->prev = pred_bl->memop_backward;
2024 pred_bl->memop_backward = new_op;
2026 if (pred_bl->memop_forward == NULL)
2027 pred_bl->memop_forward = new_op;
2029 if (get_nodes_block(last_mem) == pred) {
2030 /* We have add a new last memory op in pred block.
2031 If pred had already a last mem, reroute all memory
2033 reroute_all_mem_users(last_mem, new_op->mem);
2035 /* reroute only those memory going through the pre block */
2036 reroute_mem_through(last_mem, new_op->mem, pred);
2039 /* we added this load at the end, so it will be avail anyway */
2040 add_memop_avail(pred_bl, new_op);
2041 pred_bl->avail = new_op;
2043 in[i] = conv_to(pred_bl->avail->value.value, mode);
2045 phi = new_r_Phi(current_ir_graph, block, n, in, mode);
2046 DB((dbg, LEVEL_1, "Created new %+F in %+F for now redundant %+F\n", phi, block, op->node));
2048 if (get_nodes_block(op->node) == block) {
2049 /* The redundant node was in the current block:
2050 In that case, DO NOT update avail_out. If it was NOT
2051 avail although it is executed in this bLock, it is killed by a later
2054 memop_t *phi_op = clone_memop_phi(op, phi);
2056 update_memop_avail(bl, phi_op);
2058 mark_replace_load(op, phi);
2060 /* The redundant node is NOT in the current block and anticipated. */
2061 memop_t *phi_op = clone_memop_phi(op, phi);
2063 add_memop_avail(bl, phi_op);
2065 /* propagate it downwards */
2068 /* clear it so we do not found it the next iteration */
2069 rbitset_clear(bl->anticL_in, pos);
2076 * Insert Loads upwards.
2078 static void insert_Loads_upwards(void) {
2082 /* recalculate antic_out and insert Loads */
2083 DB((dbg, LEVEL_2, "Inserting Loads\n"));
2087 DB((dbg, LEVEL_2, "Iteration %d:\n=========\n", i));
2091 /* over all blocks in reverse post order, skip the start block */
2092 for (bl = env.forward->forward_next; bl != NULL; bl = bl->forward_next) {
2093 need_iter |= insert_Load(bl);
2096 } while (need_iter);
2098 DB((dbg, LEVEL_2, "Finished Load inserting after %d iterations\n", i));
2101 int opt_ldst(ir_graph *irg) {
2103 ir_graph *rem = current_ir_graph;
2105 current_ir_graph = irg;
2107 FIRM_DBG_REGISTER(dbg, "firm.opt.ldst");
2108 // firm_dbg_set_mask(dbg, -1);
2110 DB((dbg, LEVEL_1, "\nDoing Load/Store optimization on %+F\n", irg));
2112 /* we need landing pads */
2113 remove_critical_cf_edges(irg);
2115 dump_ir_block_graph(irg, "-XXX");
2117 if (get_opt_alias_analysis()) {
2118 assure_irg_entity_usage_computed(irg);
2119 assure_irp_globals_entity_usage_computed();
2122 obstack_init(&env.obst);
2123 ir_nodemap_init(&env.adr_map);
2126 env.backward = NULL;
2127 env.curr_adr_id = 0;
2130 env.start_bl = get_irg_start_block(irg);
2131 env.end_bl = get_irg_end_block(irg);
2134 assure_irg_outs(irg);
2136 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2138 /* first step: allocate block entries: produces an
2139 inverse post-order list for the CFG */
2140 set_irn_link(env.end_bl, NULL);
2141 irg_out_block_walk(get_irg_start_block(irg), NULL, prepare_blocks, NULL);
2143 if (get_block_entry(env.end_bl) == NULL) {
2145 * The end block is NOT reachable due to endless loops
2146 * or no_return calls. Ensure that it is initialized.
2147 * Note that this places the entry for the end block first, so we must fix this.
2148 * env.backwards points to th last block for this purpose.
2150 prepare_blocks(env.end_bl, NULL);
2153 env.forward = bl->forward_next;
2154 bl->forward_next = NULL;
2156 env.backward->forward_next = bl;
2159 /* second step: find and sort all memory ops */
2160 walk_memory_irg(irg, collect_memops, NULL, NULL);
2162 if (env.n_mem_ops == 0) {
2167 /* create the backward links */
2168 env.backward = NULL;
2169 irg_block_walk_graph(irg, NULL, collect_backward, NULL);
2171 /* link the end block in */
2172 bl = get_block_entry(env.end_bl);
2173 bl->backward_next = env.backward;
2176 /* check that we really start with the start / end block */
2177 assert(env.forward->block == env.start_bl);
2178 assert(env.backward->block == env.end_bl);
2180 /* create address sets: we know that 2 * n_mem_ops - 1 is an upper bound for all possible addresses */
2181 env.rbs_size = 2 * env.n_mem_ops;
2183 /* create the current set */
2184 env.curr_set = rbitset_obstack_alloc(&env.obst, env.rbs_size);
2185 rbitset_set(env.curr_set, env.rbs_size - 1);
2186 env.curr_id_2_memop = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
2187 memset(env.curr_id_2_memop, 0, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
2189 for (bl = env.forward; bl != NULL; bl = bl->forward_next) {
2190 /* set sentinel bits */
2191 bl->avail_out = rbitset_obstack_alloc(&env.obst, env.rbs_size);
2192 rbitset_set(bl->avail_out, env.rbs_size - 1);
2194 bl->id_2_memop_avail = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
2195 memset(bl->id_2_memop_avail, 0, env.rbs_size * sizeof(bl->id_2_memop_avail[0]));
2197 bl->anticL_in = rbitset_obstack_alloc(&env.obst, env.rbs_size);
2198 rbitset_set(bl->anticL_in, env.rbs_size - 1);
2200 bl->id_2_memop_antic = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
2201 memset(bl->id_2_memop_antic, 0, env.rbs_size * sizeof(bl->id_2_memop_antic[0]));
2204 // dump_block_list(&env);
2209 insert_Loads_upwards();
2212 /* over all blocks in reverse post order */
2213 for (bl = env.forward; bl != NULL; bl = bl->forward_next) {
2214 do_replacements(bl);
2217 /* not only invalidate but free them. We might allocate new out arrays
2218 on our obstack which will be deleted yet. */
2220 set_irg_entity_usage_state(irg, ir_entity_usage_not_computed);
2224 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2225 ir_nodemap_destroy(&env.adr_map);
2226 obstack_free(&env.obst, NULL);
2228 dump_ir_block_graph(irg, "-YYY");
2230 current_ir_graph = rem;
2232 return env.changed != 0;