2 * Copyright (C) 1995-2010 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 * @author Christian Helmer
23 * @brief loop inversion and loop unrolling
30 #include "iroptimize.h"
48 #include "irbackedge_t.h"
49 #include "irphase_t.h"
53 DEBUG_ONLY(static firm_dbg_module_t *dbg);
55 /* DBG print stats for every procedure. */
56 #define LOOP_OPT_STATS 0
58 /* DBG: Ignore node limits and process every possible loop. */
59 #define LOOP_IGNORE_NODE_LIMITS 0
62 * Convenience macro for iterating over every phi node of the given block.
63 * Requires phi list per block.
65 #define for_each_phi(block, phi) \
66 for ((phi) = get_Block_phis( (block) ); (phi) ; (phi) = get_Phi_next((phi)))
68 #define for_each_phi_safe(head, phi, next) \
69 for ((phi) = (head), (next) = (head) ? get_Phi_next((head)) : NULL; \
70 (phi) ; (phi) = (next), (next) = (next) ? get_Phi_next((next)) : NULL)
72 /* Currently processed loop. */
73 static ir_loop *cur_loop;
75 /* Flag for kind of unrolling. */
79 } unrolling_kind_flag;
81 /* Condition for performing visiting a node during copy_walk. */
82 typedef unsigned walker_condition(ir_node *);
84 /* Node and position of a predecessor. */
85 typedef struct entry_edge {
91 /* Node info for unrolling. */
92 typedef struct unrolling_node_info {
95 } unrolling_node_info;
97 /* Outs of the nodes head. */
98 static entry_edge *cur_head_outs;
100 /* Information about the loop head */
101 static ir_node *loop_head = NULL;
102 static unsigned loop_head_valid = 1;
104 /* List of all inner loops, that are processed. */
105 static ir_loop **loops;
109 #define count_stats(val) (++val)
110 #define print_stats() (do_print_stats())
111 #define reset_stats() (do_reset_stats())
114 typedef struct loop_stats_t {
118 unsigned too_large_adapted;
119 unsigned cc_limit_reached;
120 unsigned calls_limit;
122 unsigned u_simple_counting_loop;
123 unsigned constant_unroll;
124 unsigned invariant_unroll;
129 static loop_stats_t stats;
131 /* Set stats to sero */
132 static void do_reset_stats(void)
134 memset(&stats, 0, sizeof(loop_stats_t));
138 static void do_print_stats(void)
140 DB((dbg, LEVEL_2, "---------------------------------------\n"));
141 DB((dbg, LEVEL_2, "loops : %d\n",stats.loops));
142 DB((dbg, LEVEL_2, "inverted : %d\n",stats.inverted));
143 DB((dbg, LEVEL_2, "too_large : %d\n",stats.too_large));
144 DB((dbg, LEVEL_2, "too_large_adapted : %d\n",stats.too_large_adapted));
145 DB((dbg, LEVEL_2, "cc_limit_reached : %d\n",stats.cc_limit_reached));
146 DB((dbg, LEVEL_2, "calls_limit : %d\n",stats.calls_limit));
147 DB((dbg, LEVEL_2, "u_simple_counting : %d\n",stats.u_simple_counting_loop));
148 DB((dbg, LEVEL_2, "constant_unroll : %d\n",stats.constant_unroll));
149 DB((dbg, LEVEL_2, "invariant_unroll : %d\n",stats.invariant_unroll));
150 DB((dbg, LEVEL_2, "=======================================\n"));
154 #define count_stats(val) ((void)0)
155 #define print_stats() ((void)0)
156 #define reset_stats() ((void)0)
160 /* Commandline parameters */
161 typedef struct loop_opt_params_t {
162 unsigned max_loop_size; /* Maximum number of nodes */
163 int depth_adaption; /* Loop nest depth adaption */
164 unsigned allowed_calls; /* Number of calls allowed */
165 unsigned count_phi:1; /* Count phi nodes */
166 unsigned count_proj:1; /* Count projections */
168 unsigned max_cc_size; /* Maximum condition chain size */
170 unsigned allow_const_unrolling:1;
171 unsigned allow_invar_unrolling:1;
175 static loop_opt_params_t opt_params;
177 /* Loop analysis informations */
178 typedef struct loop_info_t {
179 unsigned nodes; /* node count */
180 unsigned ld_st; /* load and store nodes */
181 unsigned calls; /* number of calls */
182 unsigned cf_outs; /* number of cf edges which leave the loop */
183 entry_edge cf_out; /* single loop leaving cf edge */
184 int be_src_pos; /* position of the single own backedge in the head */
187 unsigned cc_size; /* nodes in the condition chain */
190 unsigned max_unroll; /* Number of unrolls satisfying max_loop_size */
191 unsigned exit_cond; /* 1 if condition==true exits the loop. */
192 unsigned latest_value:1; /* 1 if condition is checked against latest counter value */
193 unsigned needs_backedge:1; /* 0 if loop is completely unrolled */
194 unsigned decreasing:1; /* Step operation is_Sub, or step is<0 */
196 /* IV informations of a simple loop */
200 ir_node *iteration_phi;
203 tarval *count_tar; /* Number of loop iterations */
205 ir_node *duff_cond; /* Duff mod */
206 unrolling_kind_flag unroll_kind; /* constant or invariant unrolling */
209 /* Information about the current loop */
210 static loop_info_t loop_info;
212 /* Outs of the condition chain (loop inversion). */
213 static ir_node **cc_blocks;
214 /* df/cf edges with def in the condition chain */
215 static entry_edge *cond_chain_entries;
216 /* Array of df loops found in the condition chain. */
217 static entry_edge *head_df_loop;
218 /* Number of blocks in cc */
219 static unsigned inversion_blocks_in_cc;
222 /* Cf/df edges leaving the loop.
223 * Called entries here, as they are used to enter the loop with walkers. */
224 static entry_edge *loop_entries;
225 /* Number of unrolls to perform */
226 static int unroll_nr;
227 /* Phase is used to keep copies of nodes. */
228 static ir_phase *phase;
230 /* Loop operations. */
231 typedef enum loop_op_t {
237 /* Saves which loop operation to do until after basic tests. */
238 static loop_op_t loop_op;
240 /************************************************************************/
242 /* Returns the maximum nodes for the given nest depth */
243 static unsigned get_max_nodes_adapted(unsigned depth)
245 int adapt_permil = opt_params.depth_adaption * depth;
246 unsigned permil_change;
248 if (adapt_permil < -1000)
251 permil_change = 1000 + adapt_permil;
252 return (opt_params.max_loop_size * permil_change) / 1000;
255 /* Reset nodes link. For use with a walker. */
256 static void reset_link(ir_node *node, void *env)
259 set_irn_link(node, NULL);
262 /* Returns 0 if the node or block is not in cur_loop. */
263 static unsigned is_in_loop(ir_node *node)
265 return (get_irn_loop(get_block(node)) == cur_loop);
268 /* Returns 0 if the given edge is not a backedge
269 * with its pred in the cur_loop. */
270 static unsigned is_own_backedge(ir_node *n, int pos)
272 return (is_backedge(n, pos) && is_in_loop(get_irn_n(n, pos)));
275 /* Finds loop head and some loop_info as calls or else if necessary. */
276 static void get_loop_info(ir_node *node, void *env)
278 unsigned node_in_loop, pred_in_loop;
282 arity = get_irn_arity(node);
283 for (i = 0; i < arity; i++) {
284 ir_node *pred = get_irn_n(node, i);
286 pred_in_loop = is_in_loop(pred);
287 node_in_loop = is_in_loop(node);
289 /* collect some loop information */
291 if (is_Phi(node) && opt_params.count_phi)
293 else if (is_Proj(node) && opt_params.count_proj)
295 else if (!is_Confirm(node) && !is_Const(node) && !is_SymConst(node))
298 if (is_Load(node) || is_Store(node))
305 /* Find the loops head/the blocks with cfpred outside of the loop */
306 if (is_Block(node) && node_in_loop && !pred_in_loop && loop_head_valid) {
307 ir_node *cfgpred = get_Block_cfgpred(node, i);
309 if (!is_in_loop(cfgpred)) {
310 DB((dbg, LEVEL_5, "potential head %+F because inloop and pred %+F not inloop\n",
312 /* another head? We do not touch this. */
313 if (loop_head && loop_head != node) {
323 /* Finds all edges with users outside of the loop
324 * and definition inside the loop. */
325 static void get_loop_entries(ir_node *node, void *env)
327 unsigned node_in_loop, pred_in_loop;
331 arity = get_irn_arity(node);
332 for (i = 0; i < arity; ++i) {
333 ir_node *pred = get_irn_n(node, i);
335 pred_in_loop = is_in_loop(pred);
336 node_in_loop = is_in_loop(node);
338 if (pred_in_loop && !node_in_loop) {
343 ARR_APP1(entry_edge, loop_entries, entry);
345 if (is_Block(node)) {
347 loop_info.cf_out = entry;
354 static ir_node *ssa_second_def;
355 static ir_node *ssa_second_def_block;
358 * Walks the graph bottom up, searching for definitions and creates phis.
360 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode, int first)
368 DB((dbg, LEVEL_5, "ssa search_def_and_create_phis: block %N\n", block));
370 /* Prevents creation of phi that would be bad anyway.
371 * Dead and bad blocks. */
372 if (get_irn_arity(block) < 1 || is_Bad(block)) {
373 DB((dbg, LEVEL_5, "ssa bad %N\n", block));
377 if (block == ssa_second_def_block && !first) {
378 DB((dbg, LEVEL_5, "ssa found second definition: use second def %N\n", ssa_second_def));
379 return ssa_second_def;
382 /* already processed this block? */
383 if (irn_visited(block)) {
384 ir_node *value = (ir_node *) get_irn_link(block);
385 DB((dbg, LEVEL_5, "ssa already visited: use linked %N\n", value));
389 irg = get_irn_irg(block);
390 assert(block != get_irg_start_block(irg));
392 /* a Block with only 1 predecessor needs no Phi */
393 n_cfgpreds = get_Block_n_cfgpreds(block);
394 if (n_cfgpreds == 1) {
395 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
398 DB((dbg, LEVEL_5, "ssa 1 pred: walk pred %N\n", pred_block));
400 value = search_def_and_create_phis(pred_block, mode, 0);
401 set_irn_link(block, value);
402 mark_irn_visited(block);
407 /* create a new Phi */
408 NEW_ARR_A(ir_node*, in, n_cfgpreds);
409 for (i = 0; i < n_cfgpreds; ++i)
410 in[i] = new_Unknown(mode);
412 phi = new_r_Phi(block, n_cfgpreds, in, mode);
413 /* Important: always keep block phi list up to date. */
414 add_Block_phi(block, phi);
415 DB((dbg, LEVEL_5, "ssa phi creation: link new phi %N to block %N\n", phi, block));
416 set_irn_link(block, phi);
417 mark_irn_visited(block);
419 /* set Phi predecessors */
420 for (i = 0; i < n_cfgpreds; ++i) {
422 ir_node *pred_block = get_Block_cfgpred_block(block, i);
423 assert(pred_block != NULL);
424 pred_val = search_def_and_create_phis(pred_block, mode, 0);
426 assert(pred_val != NULL);
428 DB((dbg, LEVEL_5, "ssa phi pred:phi %N, pred %N\n", phi, pred_val));
429 set_irn_n(phi, i, pred_val);
437 * Given a set of values this function constructs SSA-form for the users of the
438 * first value (the users are determined through the out-edges of the value).
439 * Works without using the dominance tree.
441 static void construct_ssa(ir_node *orig_block, ir_node *orig_val,
442 ir_node *second_block, ir_node *second_val)
446 const ir_edge_t *edge;
447 const ir_edge_t *next;
449 assert(orig_block && orig_val && second_block && second_val &&
450 "no parameter of construct_ssa may be NULL");
452 if (orig_val == second_val)
455 irg = get_irn_irg(orig_val);
457 ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
458 inc_irg_visited(irg);
460 mode = get_irn_mode(orig_val);
461 set_irn_link(orig_block, orig_val);
462 mark_irn_visited(orig_block);
464 ssa_second_def_block = second_block;
465 ssa_second_def = second_val;
467 /* Only fix the users of the first, i.e. the original node */
468 foreach_out_edge_safe(orig_val, edge, next) {
469 ir_node *user = get_edge_src_irn(edge);
470 int j = get_edge_src_pos(edge);
471 ir_node *user_block = get_nodes_block(user);
478 DB((dbg, LEVEL_5, "original user %N\n", user));
481 ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
482 newval = search_def_and_create_phis(pred_block, mode, 1);
484 newval = search_def_and_create_phis(user_block, mode, 1);
486 if (newval != user && !is_Bad(newval))
487 set_irn_n(user, j, newval);
490 ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
494 /***** Unrolling Helper Functions *****/
496 /* Assign the copy with index nr to node n */
497 static void set_unroll_copy(ir_node *n, int nr, ir_node *cp)
499 unrolling_node_info *info;
500 assert(nr != 0 && "0 reserved");
502 info = (unrolling_node_info *)phase_get_irn_data(phase, n);
506 info = XMALLOCZ(unrolling_node_info);
507 arr = NEW_ARR_F(ir_node *, unroll_nr);
509 memset(info->copies, 0, (unroll_nr) * sizeof(ir_node *));
511 phase_set_irn_data(phase, n, info);
516 info->copies[nr] = cp;
519 /* Returns a nodes copy if it exists, else NULL. */
520 static ir_node *get_unroll_copy(ir_node *n, int nr)
523 unrolling_node_info *info = (unrolling_node_info *)phase_get_irn_data(phase, n);
527 cp = info->copies[nr];
532 /***** Inversion Helper Functions *****/
534 /* Sets copy cp of node n. */
535 static void set_inversion_copy(ir_node *n, ir_node *cp)
537 phase_set_irn_data(phase, n, cp);
540 /* Getter of copy of n for inversion */
541 static ir_node *get_inversion_copy(ir_node *n)
543 ir_node *cp = (ir_node *)phase_get_irn_data(phase, n);
547 /* Resets block mark for given node. For use with walker */
548 static void reset_block_mark(ir_node *node, void * env)
553 set_Block_mark(node, 0);
556 /* Returns mark of node, or its block if node is not a block.
557 * Used in this context to determine if node is in the condition chain. */
558 static unsigned is_nodes_block_marked(ir_node* node)
561 return get_Block_mark(node);
563 return get_Block_mark(get_block(node));
566 /* Extends a nodes ins by node new.
567 * NOTE: This is slow if a node n needs to be extended more than once. */
568 static int extend_irn(ir_node *n, ir_node *new)
572 int arity = get_irn_arity(n);
573 int new_arity = arity + 1;
575 NEW_ARR_A(ir_node *, ins, new_arity);
577 for(i = 0; i < arity; ++i) {
578 ins[i] = get_irn_n(n, i);
582 set_irn_in(n, new_arity, ins);
586 /* Extends a block by a copy of its pred at pos,
587 * fixing also the phis in the same way. */
588 static void extend_ins_by_copy(ir_node *block, int pos)
593 assert(is_Block(block));
595 /* Extend block by copy of definition at pos */
596 pred = get_irn_n(block, pos);
597 new_in = get_inversion_copy(pred);
598 DB((dbg, LEVEL_5, "Extend block %N by %N cp of %N\n", block, new_in, pred));
599 extend_irn(block, new_in);
601 /* Extend block phis by copy of definition at pos */
602 for_each_phi(block, phi) {
605 pred = get_irn_n(phi, pos);
606 cp = get_inversion_copy(pred);
607 /* If the phis in is not in the condition chain (eg. a constant),
608 * there is no copy. */
614 DB((dbg, LEVEL_5, "Extend phi %N by %N cp of %N\n", phi, new_in, pred));
615 extend_irn(phi, new_in);
619 /* Returns the number of blocks backedges. With or without alien bes. */
620 static int get_backedge_n(ir_node *block, unsigned with_alien)
624 int arity = get_irn_arity(block);
626 assert(is_Block(block) && "We only required backedges of blocks.");
628 for (i = 0; i < arity; ++i) {
629 ir_node *pred = get_irn_n(block, i);
630 if (is_backedge(block, i) && (with_alien || is_in_loop(pred)))
636 /* Returns a raw copy of the given node.
637 * Attributes are kept/set according to the needs of loop inversion. */
638 static ir_node *copy_node(ir_node *node)
643 cp = exact_copy(node);
644 arity = get_irn_arity(node);
646 /* Keep backedge info */
647 for (i = 0; i < arity; ++i) {
648 if (is_backedge(node, i))
653 set_Block_mark(cp, 0);
661 * This walker copies all walked nodes.
662 * If the walk_condition is true for a node, it is copied.
663 * All nodes node_info->copy have to be NULL prior to every walk.
664 * Order of ins is important for later usage.
666 static void copy_walk(ir_node *node, walker_condition *walk_condition,
673 ir_graph *irg = current_ir_graph;
676 * break condition and cycle resolver, creating temporary node copies
678 if (get_irn_visited(node) >= get_irg_visited(irg)) {
679 /* Here we rely on nodestate's copy being initialized with NULL */
680 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
681 if (get_inversion_copy(node) == NULL) {
682 cp = copy_node(node);
683 set_inversion_copy(node, cp);
685 DB((dbg, LEVEL_5, "The TEMP copy of %N is created %N\n", node, cp));
691 mark_irn_visited(node);
693 if (!is_Block(node)) {
694 ir_node *pred = get_nodes_block(node);
695 if (walk_condition(pred))
696 DB((dbg, LEVEL_5, "walk block %N\n", pred));
697 copy_walk(pred, walk_condition, set_loop);
700 arity = get_irn_arity(node);
702 NEW_ARR_A(ir_node *, cpin, arity);
704 for (i = 0; i < arity; ++i) {
705 ir_node *pred = get_irn_n(node, i);
707 if (walk_condition(pred)) {
708 DB((dbg, LEVEL_5, "walk node %N\n", pred));
709 copy_walk(pred, walk_condition, set_loop);
710 cpin[i] = get_inversion_copy(pred);
711 DB((dbg, LEVEL_5, "copy of %N gets new in %N which is copy of %N\n",
712 node, get_inversion_copy(pred), pred));
718 /* copy node / finalize temp node */
719 if (get_inversion_copy(node) == NULL) {
720 /* No temporary copy existent */
721 cp = copy_node(node);
722 set_inversion_copy(node, cp);
723 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
725 /* temporary copy is existent but without correct ins */
726 cp = get_inversion_copy(node);
727 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
730 if (!is_Block(node)) {
731 ir_node *cpblock = get_inversion_copy(get_nodes_block(node));
733 set_nodes_block(cp, cpblock );
735 add_Block_phi(cpblock, cp);
738 /* Keeps phi list of temporary node. */
739 set_irn_in(cp, ARR_LEN(cpin), cpin);
743 * This walker copies all walked nodes.
744 * If the walk_condition is true for a node, it is copied.
745 * All nodes node_info->copy have to be NULL prior to every walk.
746 * Order of ins is important for later usage.
747 * Takes copy_index, to phase-link copy at specific index.
749 static void copy_walk_n(ir_node *node,
750 walker_condition *walk_condition, int copy_index)
758 * break condition and cycle resolver, creating temporary node copies
760 if (irn_visited(node)) {
761 /* Here we rely on nodestate's copy being initialized with NULL */
762 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
763 if (get_unroll_copy(node, copy_index) == NULL) {
766 set_unroll_copy(node, copy_index, u);
767 DB((dbg, LEVEL_5, "The TEMP unknown of %N is created %N\n", node, u));
773 mark_irn_visited(node);
775 if (!is_Block(node)) {
776 ir_node *block = get_nodes_block(node);
777 if (walk_condition(block))
778 DB((dbg, LEVEL_5, "walk block %N\n", block));
779 copy_walk_n(block, walk_condition, copy_index);
782 arity = get_irn_arity(node);
783 NEW_ARR_A(ir_node *, cpin, arity);
785 for (i = 0; i < arity; ++i) {
786 ir_node *pred = get_irn_n(node, i);
788 if (walk_condition(pred)) {
789 DB((dbg, LEVEL_5, "walk node %N\n", pred));
790 copy_walk_n(pred, walk_condition, copy_index);
791 cpin[i] = get_unroll_copy(pred, copy_index);
797 /* copy node / finalize temp node */
798 cp = get_unroll_copy(node, copy_index);
799 if (cp == NULL || is_Unknown(cp)) {
800 cp = copy_node(node);
801 set_unroll_copy(node, copy_index, cp);
802 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
804 /* temporary copy is existent but without correct ins */
805 cp = get_unroll_copy(node, copy_index);
806 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
809 if (!is_Block(node)) {
810 ir_node *cpblock = get_unroll_copy(get_nodes_block(node), copy_index);
812 set_nodes_block(cp, cpblock );
814 add_Block_phi(cpblock, cp);
817 /* Keeps phi list of temporary node. */
818 set_irn_in(cp, ARR_LEN(cpin), cpin);
821 /* Removes alle Blocks with non marked predecessors from the condition chain. */
822 static void unmark_not_allowed_cc_blocks(void)
824 int blocks = ARR_LEN(cc_blocks);
827 for(i = 0; i < blocks; ++i) {
828 ir_node *block = cc_blocks[i];
830 int arity = get_irn_arity(block);
832 /* Head is an exception. */
833 if (block == loop_head)
836 for(a = 0; a < arity; ++a) {
837 if (! is_nodes_block_marked(get_irn_n(block, a))) {
838 set_Block_mark(block, 0);
839 --inversion_blocks_in_cc;
840 DB((dbg, LEVEL_5, "Removed %N from cc (blocks in cc %d)\n",
841 block, inversion_blocks_in_cc));
849 /* Unmarks all cc blocks using cc_blocks except head. */
850 static void unmark_cc_blocks(void)
852 int blocks = ARR_LEN(cc_blocks);
855 for(i = 0; i < blocks; ++i) {
856 ir_node *block = cc_blocks[i];
858 /* Head is an exception. */
859 if (block != loop_head)
860 set_Block_mark(block, 0);
862 inversion_blocks_in_cc = 1;
865 loop_info.cc_size = 0;
869 * Populates head_entries with (node, pred_pos) tuple
870 * whereas the node's pred at pred_pos is in the cc but not the node itself.
871 * Also finds df loops inside the cc.
872 * Head and condition chain blocks have been marked previously.
874 static void get_head_outs(ir_node *node, void *env)
877 int arity = get_irn_arity(node);
880 for (i = 0; i < arity; ++i) {
881 if (!is_nodes_block_marked(node) && is_nodes_block_marked(get_irn_n(node, i))) {
885 /* Saving also predecessor seems redundant, but becomes
886 * necessary when changing position of it, before
887 * dereferencing it.*/
888 entry.pred = get_irn_n(node, i);
889 ARR_APP1(entry_edge, cur_head_outs, entry);
893 arity = get_irn_arity(loop_head);
895 /* Find df loops inside the cc */
896 if (is_Phi(node) && get_nodes_block(node) == loop_head) {
897 for (i = 0; i < arity; ++i) {
898 if (is_own_backedge(loop_head, i)) {
899 if (is_nodes_block_marked(get_irn_n(node, i))) {
903 entry.pred = get_irn_n(node, i);
904 ARR_APP1(entry_edge, head_df_loop, entry);
905 DB((dbg, LEVEL_5, "Found incc assignment node %N @%d is pred %N, graph %N %N\n",
906 node, i, entry.pred, current_ir_graph, get_irg_start_block(current_ir_graph)));
914 * Find condition chains, and add them to be inverted
915 * A block belongs to the chain if a condition branches out of the loop.
916 * (Some blocks need to be removed once again.)
917 * Returns 1 if the given block belongs to the condition chain.
919 static unsigned find_condition_chain(ir_node *block)
921 const ir_edge_t *edge;
925 unsigned nodes_n = 0;
927 mark_irn_visited(block);
929 DB((dbg, LEVEL_5, "condition_chains for block %N\n", block));
932 foreach_out_edge_kind(block, edge, EDGE_KIND_NORMAL) {
936 /* Check if node count would exceed maximum cc size.
938 * This is not optimal, as we search depth-first and break here,
939 * continuing with another subtree. */
940 if (loop_info.cc_size + nodes_n > opt_params.max_cc_size) {
941 set_Block_mark(block, 0);
945 /* Check if block only has a jmp instruction. */
947 foreach_out_edge(block, edge) {
948 ir_node *src = get_edge_src_irn(edge);
950 if (! is_Block(src) && ! is_Jmp(src)) {
955 /* Check cf outs if one is leaving the loop,
956 * or if this node has a backedge. */
957 foreach_block_succ(block, edge) {
958 ir_node *src = get_edge_src_irn(edge);
959 int pos = get_edge_src_pos(edge);
961 if (! is_in_loop(src))
964 /* Inverting blocks with backedge outs leads to a cf edge
965 * from the inverted head, into the inverted head (skipping the body).
966 * As the body becomes the new loop head,
967 * this would introduce another loop in the existing loop.
968 * This loop inversion cannot cope with this case. */
969 if (is_backedge(src, pos)) {
975 /* We need all predecessors to already belong to the condition chain.
976 * Example of wrong case: * == in cc
987 /* Collect blocks containing only a Jmp.
988 * Do not collect blocks with backedge outs. */
989 if ((jmp_only == 1 || mark == 1) && has_be == 0) {
990 set_Block_mark(block, 1);
991 ++inversion_blocks_in_cc;
992 loop_info.cc_size += nodes_n;
993 DB((dbg, LEVEL_5, "block %N is part of condition chain\n", block));
994 ARR_APP1(ir_node *, cc_blocks, block);
996 set_Block_mark(block, 0);
999 foreach_block_succ(block, edge) {
1000 ir_node *src = get_edge_src_irn( edge );
1002 if (is_in_loop(src) && ! irn_visited(src))
1003 find_condition_chain(src);
1010 * Rewires the copied condition chain. Removes backedges.
1011 * as this condition chain is prior to the loop.
1012 * Copy of loop_head must have phi list and old (unfixed) backedge info of the loop head.
1013 * (loop_head is already fixed, we cannot rely on it.)
1015 static void fix_copy_inversion(void)
1020 ir_node *phi, *next;
1021 ir_node *head_cp = get_inversion_copy(loop_head);
1022 int arity = get_irn_arity(head_cp);
1023 int backedges = get_backedge_n(head_cp, 0);
1024 int new_arity = arity - backedges;
1028 NEW_ARR_A(ir_node *, ins, new_arity);
1031 /* Remove block backedges */
1032 for(i = 0; i < arity; ++i) {
1033 if (!is_backedge(head_cp, i))
1034 ins[pos++] = get_irn_n(head_cp, i);
1037 new_head = new_Block(new_arity, ins);
1039 phis = NEW_ARR_F(ir_node *, 0);
1041 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1043 NEW_ARR_A(ir_node *, ins, new_arity);
1045 for(i = 0; i < arity; ++i) {
1046 if (!is_backedge(head_cp, i))
1047 ins[pos++] = get_irn_n(phi, i);
1049 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1050 new_head, new_arity, ins,
1052 ARR_APP1(ir_node *, phis, new_phi);
1056 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1057 exchange(phi, phis[pos++]);
1060 exchange(head_cp, new_head);
1065 /* Puts the original condition chain at the end of the loop,
1066 * subsequently to the body.
1067 * Relies on block phi list and correct backedges.
1069 static void fix_head_inversion(void)
1073 ir_node *phi, *next;
1075 int arity = get_irn_arity(loop_head);
1076 int backedges = get_backedge_n(loop_head, 0);
1077 int new_arity = backedges;
1081 NEW_ARR_A(ir_node *, ins, new_arity);
1084 /* Keep only backedges */
1085 for(i = 0; i < arity; ++i) {
1086 if (is_own_backedge(loop_head, i))
1087 ins[pos++] = get_irn_n(loop_head, i);
1090 new_head = new_Block(new_arity, ins);
1092 phis = NEW_ARR_F(ir_node *, 0);
1094 for_each_phi(loop_head, phi) {
1096 DB((dbg, LEVEL_5, "Fixing phi %N of loop head\n", phi));
1098 NEW_ARR_A(ir_node *, ins, new_arity);
1101 for (i = 0; i < arity; ++i) {
1102 ir_node *pred = get_irn_n(phi, i);
1104 if (is_own_backedge(loop_head, i)) {
1105 /* If assignment is in the condition chain,
1106 * we need to create a phi in the new loop head.
1107 * This can only happen for df, not cf. See find_condition_chains. */
1108 if (is_nodes_block_marked(pred)) {
1109 /* Cannot do this here. */
1110 ins[pos++] = pred; /*fix_inner_cc_definitions(phi, pred);*/
1117 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1118 new_head, new_arity, ins,
1121 ARR_APP1(ir_node *, phis, new_phi);
1123 DB((dbg, LEVEL_5, "fix inverted head should exch %N by %N (arity %d)\n", phi, new_phi, pos ));
1127 for_each_phi_safe(get_Block_phis(loop_head), phi, next) {
1128 DB((dbg, LEVEL_5, "fix inverted exch phi %N by %N\n", phi, phis[pos]));
1129 if (phis[pos] != phi)
1130 exchange(phi, phis[pos++]);
1135 DB((dbg, LEVEL_5, "fix inverted head exch head block %N by %N\n", loop_head, new_head));
1136 exchange(loop_head, new_head);
1139 /* Does the loop inversion. */
1140 static void inversion_walk(entry_edge *head_entries)
1145 * The order of rewiring bottom-up is crucial.
1146 * Any change of the order leads to lost information that would be needed later.
1149 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1151 /* 1. clone condition chain */
1152 inc_irg_visited(current_ir_graph);
1154 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1155 entry_edge entry = head_entries[i];
1156 ir_node *pred = get_irn_n(entry.node, entry.pos);
1158 DB((dbg, LEVEL_5, "\nInit walk block %N\n", pred));
1160 copy_walk(pred, is_nodes_block_marked, cur_loop);
1163 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1165 /* 2. Extends the head control flow successors ins
1166 * with the definitions of the copied head node. */
1167 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1168 entry_edge head_out = head_entries[i];
1170 if (is_Block(head_out.node))
1171 extend_ins_by_copy(head_out.node, head_out.pos);
1174 /* 3. construct_ssa for users of definitions in the condition chain,
1175 * as there is now a second definition. */
1176 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1177 entry_edge head_out = head_entries[i];
1179 /* Ignore keepalives */
1180 if (is_End(head_out.node))
1183 /* Construct ssa for assignments in the condition chain. */
1184 if (!is_Block(head_out.node)) {
1185 ir_node *pred, *cppred, *block, *cpblock;
1187 pred = head_out.pred;
1188 cppred = get_inversion_copy(pred);
1189 block = get_nodes_block(pred);
1190 cpblock = get_nodes_block(cppred);
1191 construct_ssa(block, pred, cpblock, cppred);
1196 * If there is an assignment in the condition chain
1197 * with a user also in the condition chain,
1198 * the dominance frontier is in the new loop head.
1199 * The dataflow loop is completely in the condition chain.
1204 * Phi_cp | | copied condition chain
1208 * Phi* | | new loop head with newly created phi.
1210 * Phi | | original, inverted condition chain
1215 for (i = 0; i < ARR_LEN(head_df_loop); ++i) {
1216 entry_edge head_out = head_df_loop[i];
1218 /* Construct ssa for assignments in the condition chain. */
1219 ir_node *pred, *cppred, *block, *cpblock;
1221 pred = head_out.pred;
1222 cppred = get_inversion_copy(pred);
1223 assert(cppred && pred);
1224 block = get_nodes_block(pred);
1225 cpblock = get_nodes_block(cppred);
1226 construct_ssa(block, pred, cpblock, cppred);
1229 /* 4. Remove the ins which are no backedges from the original condition chain
1230 * as the cc is now subsequent to the body. */
1231 fix_head_inversion();
1233 /* 5. Remove the backedges of the copied condition chain,
1234 * because it is going to be the new 'head' in advance to the loop. */
1235 fix_copy_inversion();
1238 /* Performs loop inversion of cur_loop if possible and reasonable. */
1239 static void loop_inversion(void)
1241 unsigned do_inversion = 1;
1242 unsigned has_cc = 0;
1244 /*inversion_head_node_limit = INT_MAX;*/
1245 ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1247 /* Reset block marks.
1248 * We use block marks to flag blocks of the original condition chain. */
1249 irg_walk_graph(current_ir_graph, reset_block_mark, NULL, NULL);
1251 /*loop_info.blocks = get_loop_n_blocks(cur_loop);*/
1252 cond_chain_entries = NEW_ARR_F(entry_edge, 0);
1253 head_df_loop = NEW_ARR_F(entry_edge, 0);
1255 /*head_inversion_node_count = 0;*/
1256 inversion_blocks_in_cc = 0;
1258 /* Use phase to keep copy of nodes from the condition chain. */
1259 phase = new_phase(current_ir_graph, phase_irn_init_default);
1261 /* Search for condition chains and temporarily save the blocks in an array. */
1262 cc_blocks = NEW_ARR_F(ir_node *, 0);
1263 inc_irg_visited(current_ir_graph);
1264 has_cc = find_condition_chain(loop_head);
1266 unmark_not_allowed_cc_blocks();
1267 DEL_ARR_F(cc_blocks);
1269 #if LOOP_IGNORE_NODE_LIMITS
1270 (void) unmark_cc_blocks;
1272 /* Condition chain too large.
1273 * Loop should better be small enough to fit into the cache. */
1274 /* FIXME Of course, we should take a small enough cc in the first place,
1275 * which is not that simple. (bin packing) */
1276 if (loop_info.cc_size > opt_params.max_cc_size) {
1277 count_stats(stats.cc_limit_reached);
1279 /* Only head taken? */
1280 if (inversion_blocks_in_cc == 1)
1283 /* Unmark cc blocks except the head.
1284 * Invert head only for possible unrolling. */
1289 /* We also catch endless loops here,
1290 * because they do not have a condition chain. */
1291 if (inversion_blocks_in_cc < 1) {
1294 "Loop contains %d (less than 1) invertible blocks => No Inversion done.\n",
1295 inversion_blocks_in_cc));
1299 cur_head_outs = NEW_ARR_F(entry_edge, 0);
1301 /* Get all edges pointing into the condition chain. */
1302 irg_walk_graph(current_ir_graph, get_head_outs, NULL, NULL);
1304 /* Do the inversion */
1305 inversion_walk(cur_head_outs);
1307 DEL_ARR_F(cur_head_outs);
1309 /* Duplicated blocks changed doms */
1310 set_irg_doms_inconsistent(current_ir_graph);
1311 /* Loop content changed */
1312 set_irg_loopinfo_inconsistent(current_ir_graph);
1313 /* TODO are they? Depends on set_irn_in and set_irn_n exchange and new_node. */
1314 set_irg_outs_inconsistent(current_ir_graph);
1316 count_stats(stats.inverted);
1321 DEL_ARR_F(cond_chain_entries);
1322 DEL_ARR_F(head_df_loop);
1324 ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1327 /* Fix the original loop_heads ins for invariant unrolling case. */
1328 static void unrolling_fix_loop_head_inv(void)
1332 ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, 0);
1333 ir_node *head_pred = get_irn_n(loop_head, loop_info.be_src_pos);
1334 ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1336 /* Original loop_heads ins are:
1337 * duff block and the own backedge */
1339 ins[0] = loop_condition;
1342 set_irn_in(loop_head, 2, ins);
1344 for_each_phi(loop_head, phi) {
1345 ir_node *pred = get_irn_n(phi, loop_info.be_src_pos);
1346 ir_node *last_pred = get_unroll_copy(pred, unroll_nr - 1);
1349 ins[1] = get_irn_link(phi);
1351 set_irn_in(phi, 2, ins);
1355 /* Removes previously created phis with only 1 in. */
1356 static void correct_phis(ir_node *node, void *env)
1359 if (is_Phi(node) && get_irn_arity(node) == 1) {
1363 in[0] = get_irn_n(node, 0);
1365 exch = new_rd_Phi(get_irn_dbg_info(node),
1366 get_nodes_block(node), 1, in,
1367 get_irn_mode(node));
1369 exchange(node, exch);
1373 /* Unrolling: Rewire floating copies. */
1374 static void place_copies(int copies)
1376 ir_node *loophead = loop_head;
1378 int be_src_pos = loop_info.be_src_pos;
1380 /* Serialize loops by fixing their head ins.
1381 * Processed are the copies.
1382 * The original loop is done after that, to keep backedge infos. */
1383 for (c = 0; c < copies; ++c) {
1384 ir_node *upper = get_unroll_copy(loophead, c);
1385 ir_node *lower = get_unroll_copy(loophead, c + 1);
1387 ir_node *topmost_be_block = get_nodes_block(get_irn_n(loophead, be_src_pos));
1389 /* Important: get the preds first and then their copy. */
1390 ir_node *upper_be_block = get_unroll_copy(topmost_be_block, c);
1391 ir_node *new_jmp = new_r_Jmp(upper_be_block);
1392 DB((dbg, LEVEL_5, " place_copies upper %N lower %N\n", upper, lower));
1394 DB((dbg, LEVEL_5, "topmost be block %N \n", topmost_be_block));
1396 if (loop_info.unroll_kind == constant) {
1399 set_irn_in(lower, 1, ins);
1401 for_each_phi(loophead, phi) {
1402 ir_node *topmost_def = get_irn_n(phi, be_src_pos);
1403 ir_node *upper_def = get_unroll_copy(topmost_def, c);
1404 ir_node *lower_phi = get_unroll_copy(phi, c + 1);
1406 /* It is possible, that the value used
1407 * in the OWN backedge path is NOT defined in this loop. */
1408 if (is_in_loop(topmost_def))
1411 ins[0] = topmost_def;
1413 set_irn_in(lower_phi, 1, ins);
1414 /* Need to replace phis with 1 in later. */
1417 /* Invariant case */
1418 /* Every node has 2 ins. One from the duff blocks
1419 * and one from the previous unrolled loop. */
1421 /* Calculate corresponding projection of mod result for this copy c */
1422 ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, unroll_nr - c - 1);
1426 set_irn_in(lower, 1, ins);
1428 for_each_phi(loophead, phi) {
1429 ir_node *topmost_phi_pred = get_irn_n(phi, be_src_pos);
1430 ir_node *upper_phi_pred;
1434 lower_phi = get_unroll_copy(phi, c + 1);
1435 duff_phi = get_irn_link(lower_phi);
1437 if (is_in_loop(topmost_phi_pred)) {
1438 upper_phi_pred = get_unroll_copy(topmost_phi_pred, c);
1440 upper_phi_pred = topmost_phi_pred;
1443 ins[0] = upper_phi_pred;
1446 set_irn_in(lower_phi, 2, ins);
1451 /* Reconnect loop landing pad with last copy. */
1452 for (i = 0; i < ARR_LEN(loop_entries); ++i) {
1453 entry_edge edge = loop_entries[i];
1454 /* Last copy is at the bottom */
1455 ir_node *new_pred = get_unroll_copy(edge.pred, copies);
1456 set_irn_n(edge.node, edge.pos, new_pred);
1459 /* Fix original loops head.
1460 * Done in the end, as ins and be info were needed before. */
1461 if (loop_info.unroll_kind == constant) {
1463 ir_node *head_pred = get_irn_n(loop_head, be_src_pos);
1464 ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1466 set_irn_n(loop_head, loop_info.be_src_pos, loop_condition);
1468 for_each_phi(loop_head, phi) {
1469 ir_node *pred = get_irn_n(phi, be_src_pos);
1472 /* It is possible, that the value used
1473 * in the OWN backedge path is NOT defined in this loop. */
1474 if (is_in_loop(pred))
1475 last_pred = get_unroll_copy(pred, copies);
1478 set_irn_n(phi, be_src_pos, last_pred);
1481 unrolling_fix_loop_head_inv();
1485 /* Copies the cur_loop several times. */
1486 static void copy_loop(entry_edge *cur_loop_outs, int copies)
1490 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1492 for (c = 0; c < copies; ++c) {
1494 inc_irg_visited(current_ir_graph);
1496 DB((dbg, LEVEL_5, " ### Copy_loop copy nr: %d ###\n", c));
1497 for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1498 entry_edge entry = cur_loop_outs[i];
1499 ir_node *pred = get_irn_n(entry.node, entry.pos);
1501 copy_walk_n(pred, is_in_loop, c + 1);
1505 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1509 /* Creates a new phi from the given phi node omitting own bes,
1510 * using be_block as supplier of backedge informations. */
1511 static ir_node *clone_phis_sans_bes(ir_node *node, ir_node *be_block)
1514 int arity = get_irn_arity(node);
1517 assert(get_irn_arity(node) == get_irn_arity(be_block));
1518 assert(is_Phi(node));
1520 ins = NEW_ARR_F(ir_node *, arity);
1521 for (i = 0; i < arity; ++i) {
1522 if (! is_own_backedge(be_block, i)) {
1523 ins[c] = get_irn_n(node, i);
1527 ir_node *pred = get_inr_n(node, i);
1528 if (! is_in_loop(pred)) {
1535 return new_r_Phi(get_nodes_block(node), c, ins, get_irn_mode(node));
1538 /* Creates a new block from the given block node omitting own bes,
1539 * using be_block as supplier of backedge informations. */
1540 static ir_node *clone_block_sans_bes(ir_node *node, ir_node *be_block)
1543 int arity = get_irn_arity(node);
1546 assert(get_irn_arity(node) == get_irn_arity(be_block));
1547 assert(is_Block(node));
1549 ins = NEW_ARR_F(ir_node *, arity);
1550 for (i = 0; i < arity; ++i) {
1551 if (! is_own_backedge(be_block, i)) {
1552 ins[c] = get_irn_n(node, i);
1557 return new_Block(c, ins);
1560 /* Creates blocks for duffs device, using previously obtained
1561 * informations about the iv.
1563 static void create_duffs_block(void)
1567 ir_node *block1, *count_block, *duff_block;
1568 ir_node *ems, *ems_divmod, *ems_mod_proj, *cmp_null,
1569 *cmp_proj, *ems_mode_cond, *x_true, *x_false, *const_null;
1570 ir_node *true_val, *false_val;
1573 ir_node *duff_mod, *proj, *cond;
1575 ir_node *count, *correction, *unroll_c;
1576 ir_node *cmp_bad_count, *good_count, *bad_count, *count_phi, *bad_count_neg;
1578 mode = get_irn_mode(loop_info.end_val);
1579 const_null = new_Const(get_mode_null(mode));
1582 * 1. Calculate first approach to count.
1583 * Condition: (end - start) % step == 0 */
1584 block1 = clone_block_sans_bes(loop_head, loop_head);
1586 /* Create loop entry phis in first duff block
1587 * as it becomes the loops preheader */
1588 if (loop_info.unroll_kind == invariant) {
1590 for_each_phi(loop_head, phi) {
1591 ir_node *new_phi = clone_phis_sans_bes(phi, loop_head);
1592 set_nodes_block(new_phi, block1);
1596 ems = new_r_Sub(block1, loop_info.end_val, loop_info.start_val,
1597 get_irn_mode(loop_info.end_val));
1599 ems_divmod = new_r_DivMod(block1,
1604 op_pin_state_pinned);
1606 ems_mod_proj = new_r_Proj(ems_divmod, mode, pn_DivMod_res_mod);
1607 cmp_null = new_r_Cmp(block1, ems_mod_proj, const_null);
1608 cmp_proj = new_r_Proj(cmp_null, mode, pn_Cmp_Eq);
1609 ems_mode_cond = new_Cond(cmp_proj);
1611 /* ems % step == 0 */
1612 x_true = new_Proj(ems_mode_cond, mode_X, pn_Cond_true);
1613 /* ems % step != 0 */
1614 x_false = new_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1618 * Assures, duffs device receives a valid count.
1620 * decreasing: count < 0
1621 * increasing: count > 0
1626 count_block = new_Block(2, ins);
1628 /* Increase loop-taken-count depending on the loop condition
1629 * uses the latest iv to compare to. */
1630 if (loop_info.latest_value == 1) {
1631 /* ems % step == 0 : +0 */
1632 true_val = new_Const(get_mode_null(mode));
1633 /* ems % step != 0 : +1 */
1634 false_val = new_Const(get_mode_one(mode));
1636 tarval *tv_two = new_tarval_from_long(2, mode);
1637 /* ems % step == 0 : +1 */
1638 true_val = new_Const(get_mode_one(mode));
1639 /* ems % step != 0 : +2 */
1640 false_val = new_Const(tv_two);
1646 correction = new_r_Phi(count_block, 2, ins, mode);
1648 count = new_r_Proj(ems_divmod, mode, pn_DivMod_res_div);
1650 /* (end - start) / step + correction */
1651 count = new_Add(count, correction, mode);
1653 cmp_bad_count = new_r_Cmp(count_block, count, const_null);
1655 /* We preconditioned the loop to be tail-controlled.
1656 * So, if count is something 'wrong' like 0,
1657 * negative/positive (depending on step direction),
1658 * we may take the loop once (tail-contr.) and leave it
1659 * to the existing condition, to break; */
1661 /* Depending on step direction, we have to check for > or < 0 */
1662 if (loop_info.decreasing == 1) {
1663 bad_count_neg = new_r_Proj(cmp_bad_count, mode_X, pn_Cmp_Lt);
1665 bad_count_neg = new_r_Proj(cmp_bad_count, mode_X, pn_Cmp_Gt);
1668 bad_count_neg = new_Cond(bad_count_neg);
1669 good_count = new_Proj(bad_count_neg, mode_X, pn_Cond_true);
1670 bad_count = new_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1673 * Contains module to decide which loop to start from. */
1675 ins[0] = good_count;
1677 duff_block = new_Block(2, ins);
1679 /* Matze: I commented this line out because I was in the process of
1680 * removing the Abs node. I don't understand that line at all anyway
1681 * since no other code here checks for the presence of an Abs or creates
1682 * one. So how can we know here that "count" is an Abs node... */
1684 /* count wants to be positive */
1685 ins[0] = get_Abs_op(count);
1687 /* Manually feed the aforementioned count = 1 (bad case)*/
1688 ins[1] = new_Const(get_mode_one(mode));
1689 count_phi = new_r_Phi(duff_block, 2, ins, mode);
1691 unroll_c = new_Const(new_tarval_from_long((long)unroll_nr, mode));
1693 /* count % unroll_nr */
1694 duff_mod = new_r_Mod(duff_block,
1699 op_pin_state_pinned);
1701 proj = new_Proj(duff_mod, mode_X, pn_Mod_res);
1702 cond = new_Cond(proj);
1704 loop_info.duff_cond = cond;
1707 /* Returns 1 if given node is not in loop,
1708 * or if it is a phi of the loop head with only loop invariant defs.
1710 static unsigned is_loop_invariant_def(ir_node *node)
1714 if (! is_in_loop(node))
1717 /* If this is a phi of the loophead shared by more than 1 loop,
1718 * we need to check if all defs are not in the loop. */
1721 block = get_nodes_block(node);
1723 /* To prevent unexpected situations. */
1724 if (block != loop_head)
1727 for (i = 0; i < get_irn_arity(node); ++i) {
1728 /* Check if all bes are just loopbacks. */
1729 if (is_own_backedge(block, i) && get_irn_n(node, i) != node)
1736 /* Returns 1 if one pred of node is invariant and the other is not.
1737 * invar_pred and other are set analogously. */
1738 static unsigned get_invariant_pred(ir_node *node, ir_node **invar_pred, ir_node **other)
1740 ir_node *pred0 = get_irn_n(node, 0);
1741 ir_node *pred1 = get_irn_n(node, 1);
1746 if (is_loop_invariant_def(pred0)) {
1747 *invar_pred = pred0;
1751 if (is_loop_invariant_def(pred1)) {
1752 if (invar_pred != NULL)
1753 /* RETURN. We do not want both preds to be invariant. */
1757 *invar_pred = pred1;
1764 /* Starts from a phi that may belong to an iv.
1765 * If an add forms a loop with iteration_phi,
1766 * and add uses a constant, 1 is returned
1767 * and 'start' as well as 'add' are sane. */
1768 static unsigned get_start_and_add(ir_node *iteration_phi, unrolling_kind_flag role)
1771 ir_node *found_add = loop_info.add;
1772 int arity = get_irn_arity(iteration_phi);
1774 DB((dbg, LEVEL_4, "Find start and add from %N\n", iteration_phi));
1776 for (i = 0; i < arity; ++i) {
1778 /* Find start_val which needs to be pred of the iteration_phi.
1779 * If start_val already known, sanity check. */
1780 if (!is_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1781 ir_node *found_start_val = get_irn_n(loop_info.iteration_phi, i);
1783 DB((dbg, LEVEL_4, "found_start_val %N\n", found_start_val));
1785 /* We already found a start_val it has to be always the same. */
1786 if (loop_info.start_val && found_start_val != loop_info.start_val)
1789 if ((role == constant) && !(is_SymConst(found_start_val) || is_Const(found_start_val)))
1791 else if((role == constant) && !(is_loop_invariant_def(found_start_val)))
1794 loop_info.start_val = found_start_val;
1797 /* The phi has to be in the loop head.
1798 * Follow all own backedges. Every value supplied from these preds of the phi
1799 * needs to origin from the same add. */
1800 if (is_own_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1801 ir_node *new_found = get_irn_n(loop_info.iteration_phi,i);
1803 DB((dbg, LEVEL_4, "is add? %N\n", new_found));
1805 if (! (is_Add(new_found) || is_Sub(new_found)) || (found_add && found_add != new_found))
1808 found_add = new_found;
1812 loop_info.add = found_add;
1818 /* Returns 1 if one pred of node is a const value and the other is not.
1819 * const_pred and other are set analogously. */
1820 static unsigned get_const_pred(ir_node *node, ir_node **const_pred, ir_node **other)
1822 ir_node *pred0 = get_irn_n(node, 0);
1823 ir_node *pred1 = get_irn_n(node, 1);
1825 DB((dbg, LEVEL_4, "Checking for constant pred of %N\n", node));
1830 /*DB((dbg, LEVEL_4, "is %N const\n", pred0));*/
1831 if (is_Const(pred0) || is_SymConst(pred0)) {
1832 DB((dbg, LEVEL_1, "%N is constant\n", pred0));
1833 *const_pred = pred0;
1837 /*DB((dbg, LEVEL_4, "is %N const\n", pred1));*/
1838 if (is_Const(pred1) || is_SymConst(pred1)) {
1839 if (*const_pred != NULL) {
1840 DB((dbg, LEVEL_1, "%N is ALSO constant\n", pred1));
1841 /* RETURN. We do not want both preds to be constant. */
1845 DB((dbg, LEVEL_4, "%N is constant\n", pred1));
1847 *const_pred = pred1;
1850 if (*const_pred == NULL)
1856 /* Returns the mathematically inverted pn_Cmp. */
1857 static pn_Cmp get_math_inverted_case(pn_Cmp proj)
1873 panic("Unhandled pn_Cmp.");
1877 /* norm_proj means we do not exit the loop. */
1878 static unsigned simulate_next(tarval **count_tar,
1879 tarval *stepped, tarval *step_tar, tarval *end_tar, pn_Cmp norm_proj)
1883 DB((dbg, LEVEL_1, "Loop taken if (stepped)%ld %s (end)%ld ",
1884 get_tarval_long(stepped),
1885 get_pnc_string((norm_proj)),
1886 get_tarval_long(end_tar)));
1887 DB((dbg, LEVEL_1, "comparing latest value %d\n", loop_info.latest_value));
1889 /* If current iv does not stay in the loop,
1890 * this run satisfied the exit condition. */
1891 if (! (tarval_cmp(stepped, end_tar) & norm_proj))
1894 DB((dbg, LEVEL_1, "Result: (stepped)%ld IS %s (end)%ld\n",
1895 get_tarval_long(stepped),
1896 get_pnc_string(tarval_cmp(stepped, end_tar)),
1897 get_tarval_long(end_tar)));
1900 if (is_Add(loop_info.add))
1901 next = tarval_add(stepped, step_tar);
1904 next = tarval_sub(stepped, step_tar, get_irn_mode(loop_info.end_val));
1906 DB((dbg, LEVEL_1, "Loop taken if %ld %s %ld ",
1907 get_tarval_long(next),
1908 get_pnc_string(norm_proj),
1909 get_tarval_long(end_tar)));
1910 DB((dbg, LEVEL_1, "comparing latest value %d\n", loop_info.latest_value));
1912 /* Increase steps. */
1913 *count_tar = tarval_add(*count_tar, get_tarval_one(get_tarval_mode(*count_tar)));
1915 /* Next has to fail the loop condition, or we will never exit. */
1916 if (! (tarval_cmp(next, end_tar) & norm_proj))
1922 /* Check if loop meets requirements for a 'simple loop':
1923 * - Exactly one cf out
1925 * - Max nodes after unrolling
1929 * Returns Projection of cmp node or NULL; */
1930 static ir_node *is_simple_loop(void)
1933 unsigned loop_depth, max_loop_nodes_adapted;
1934 ir_node *loop_block, *exit_block, *projx, *cond, *projres, *loop_condition;
1936 /* Maximum of one condition, and no endless loops. */
1937 if (loop_info.cf_outs != 1)
1940 DB((dbg, LEVEL_4, "1 loop exit\n"));
1943 /* Ignore loop size. Probably not wise in other than testcases. */
1944 (void) max_loop_nodes_adapted;
1947 loop_info.max_unroll = 6;
1949 /* Calculate maximum unroll_nr keeping node count below limit. */
1950 loop_depth = get_loop_depth(cur_loop) - 1;
1951 max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
1953 loop_info.max_unroll = opt_params.max_loop_size / loop_info.nodes;
1954 if (loop_info.max_unroll < 2) {
1955 count_stats(stats.too_large);
1959 DB((dbg, LEVEL_4, "maximum unroll factor %u, to not exceed node limit \n",
1960 loop_info.max_unroll));
1962 arity = get_irn_arity(loop_head);
1963 /* RETURN if we have more than 1 be. */
1964 /* Get my backedges without alien bes. */
1966 for (i = 0; i < arity; ++i) {
1967 ir_node *pred = get_irn_n(loop_head, i);
1968 if (is_own_backedge(loop_head, i)) {
1970 /* Our simple loops may have only one backedge. */
1973 loop_block = get_nodes_block(pred);
1974 loop_info.be_src_pos = i;
1979 DB((dbg, LEVEL_4, "loop has 1 own backedge.\n"));
1981 exit_block = get_nodes_block(loop_info.cf_out.pred);
1982 /* The loop has to be tail-controlled.
1983 * This can be changed/improved,
1984 * but we would need a duff iv. */
1985 if (exit_block != loop_block)
1988 DB((dbg, LEVEL_4, "tail-controlled loop.\n"));
1990 /* find value on which loop exit depends */
1991 projx = loop_info.cf_out.pred;
1992 cond = get_irn_n(projx, 0);
1993 projres = get_irn_n(cond, 0);
1994 loop_condition = get_irn_n(projres, 0);
1996 if (!is_Cmp(loop_condition))
1999 DB((dbg, LEVEL_5, "projection is %s\n", get_pnc_string(get_Proj_proj(projx))));
2001 switch(get_Proj_proj(projx)) {
2003 loop_info.exit_cond = 0;
2006 loop_info.exit_cond = 1;
2009 panic("Cond Proj_proj other than true/false");
2012 DB((dbg, LEVEL_4, "Valid Cmp.\n"));
2017 /* Returns 1 if all nodes are mode_Iu or mode_Is. */
2018 static unsigned are_mode_I(ir_node *n1, ir_node* n2, ir_node *n3)
2020 ir_mode *m1 = get_irn_mode(n1);
2021 ir_mode *m2 = get_irn_mode(n2);
2022 ir_mode *m3 = get_irn_mode(n3);
2024 if ((m1 == mode_Iu && m2 == mode_Iu && m3 == mode_Iu) ||
2025 (m1 == mode_Is && m2 == mode_Is && m3 == mode_Is))
2031 /* Checks if cur_loop is a simple tail-controlled counting loop
2032 * with start and end value loop invariant, step constant. */
2033 static unsigned get_unroll_decision_invariant(void)
2036 ir_node *projres, *loop_condition, *iteration_path;
2037 unsigned success, is_latest_val;
2038 tarval *start_tar, *step_tar;
2041 /* RETURN if loop is not 'simple' */
2042 projres = is_simple_loop();
2043 if (projres == NULL)
2046 loop_condition = get_irn_n(projres, 0);
2048 success = get_invariant_pred(loop_condition, &loop_info.end_val, &iteration_path);
2052 DB((dbg, LEVEL_4, "Invariant End_val %N, other %N\n", loop_info.end_val, iteration_path));
2054 /* We may find the add or the phi first.
2055 * Until now we only have end_val. */
2056 if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2058 /* We test against the latest value of the iv. */
2061 loop_info.add = iteration_path;
2062 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
2064 /* Preds of the add should be step and the iteration_phi */
2065 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2069 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2071 if (! is_Phi(loop_info.iteration_phi))
2074 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2077 * Does necessary sanity check of add, if it is already set. */
2078 success = get_start_and_add(loop_info.iteration_phi, invariant);
2082 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2084 } else if (is_Phi(iteration_path)) {
2085 ir_node *new_iteration_phi;
2087 /* We compare with the value the iv had entering this run. */
2090 loop_info.iteration_phi = iteration_path;
2091 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2093 /* Find start_val and add-node.
2094 * Does necessary sanity check of add, if it is already set. */
2095 success = get_start_and_add(loop_info.iteration_phi, invariant);
2099 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2100 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2102 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2106 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2108 if (loop_info.iteration_phi != new_iteration_phi)
2115 mode = get_irn_mode(loop_info.end_val);
2117 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2118 loop_info.start_val, loop_info.end_val, loop_info.step));
2120 if (mode != mode_Is && mode != mode_Iu)
2123 /* TODO necessary? */
2124 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2127 DB((dbg, LEVEL_4, "mode integer\n"));
2129 step_tar = get_Const_tarval(loop_info.step);
2130 start_tar = get_Const_tarval(loop_info.start_val);
2132 if (tarval_is_null(step_tar)) {
2133 /* TODO Might be worth a warning. */
2137 DB((dbg, LEVEL_4, "step is not 0\n"));
2139 create_duffs_block();
2141 return loop_info.max_unroll;
2144 /* Returns unroll factor,
2145 * given maximum unroll factor and number of loop passes. */
2146 static unsigned get_preferred_factor_constant(tarval *count_tar)
2148 tarval *tar_6, *tar_5, *tar_4, *tar_3, *tar_2;
2150 ir_mode *mode = get_irn_mode(loop_info.end_val);
2152 tar_6 = new_tarval_from_long(6, mode);
2153 tar_5 = new_tarval_from_long(5, mode);
2154 tar_4 = new_tarval_from_long(4, mode);
2155 tar_3 = new_tarval_from_long(3, mode);
2156 tar_2 = new_tarval_from_long(2, mode);
2158 /* loop passes % {6, 5, 4, 3, 2} == 0 */
2159 if (tarval_is_null(tarval_mod(count_tar, tar_6)))
2161 else if (tarval_is_null(tarval_mod(count_tar, tar_5)))
2163 else if (tarval_is_null(tarval_mod(count_tar, tar_4)))
2165 else if (tarval_is_null(tarval_mod(count_tar, tar_3)))
2167 else if (tarval_is_null(tarval_mod(count_tar, tar_2)))
2170 /* gcd(max_unroll, count_tar) */
2171 int a = loop_info.max_unroll;
2172 int b = (int)get_tarval_long(count_tar);
2175 DB((dbg, LEVEL_4, "gcd of max_unroll %d and count_tar %d: ", a, b));
2182 DB((dbg, LEVEL_4, "%d\n", a));
2186 DB((dbg, LEVEL_4, "preferred unroll factor %d\n", prefer));
2189 * If our preference is greater than the allowed unroll factor
2190 * we either might reduce the preferred factor and prevent a duffs device block,
2191 * or create a duffs device block, from which in this case (constants only)
2192 * we know the startloop at compiletime.
2193 * The latter yields the following graphs.
2194 * but for code generation we would want to use graph A.
2195 * The graphs are equivalent. So, we can only reduce the preferred factor.
2205 if (prefer <= loop_info.max_unroll)
2210 if (loop_info.max_unroll >= 3)
2212 else if (loop_info.max_unroll >= 2)
2218 if (loop_info.max_unroll >= 2)
2229 /* Check if cur_loop is a simple counting loop.
2230 * Start, step and end are constants. */
2232 static unsigned get_unroll_decision_constant(void)
2234 ir_node *projres, *loop_condition, *iteration_path;
2235 unsigned success, is_latest_val;
2236 tarval *start_tar, *end_tar, *step_tar, *diff_tar, *count_tar, *stepped;
2237 pn_Cmp proj_proj, norm_proj;
2240 /* RETURN if loop is not 'simple' */
2241 projres = is_simple_loop();
2242 if (projres == NULL)
2245 /* One in of the loop condition needs to be loop invariant. => end_val
2246 * The other in is assigned by an add. => add
2247 * The add uses a loop invariant value => step
2248 * and a phi with a loop invariant start_val and the add node as ins.
2260 loop_condition = get_irn_n(projres, 0);
2262 success = get_const_pred(loop_condition, &loop_info.end_val, &iteration_path);
2266 DB((dbg, LEVEL_4, "End_val %N, other %N\n", loop_info.end_val, iteration_path));
2268 /* We may find the add or the phi first.
2269 * Until now we only have end_val. */
2270 if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2272 /* We test against the latest value of the iv. */
2275 loop_info.add = iteration_path;
2276 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
2278 /* Preds of the add should be step and the iteration_phi */
2279 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2283 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2285 if (! is_Phi(loop_info.iteration_phi))
2288 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2291 * Does necessary sanity check of add, if it is already set. */
2292 success = get_start_and_add(loop_info.iteration_phi, constant);
2296 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2298 } else if (is_Phi(iteration_path)) {
2299 ir_node *new_iteration_phi;
2301 /* We compare with the value the iv had entering this run. */
2304 loop_info.iteration_phi = iteration_path;
2305 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2307 /* Find start_val and add-node.
2308 * Does necessary sanity check of add, if it is already set. */
2309 success = get_start_and_add(loop_info.iteration_phi, constant);
2313 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2314 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2316 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2320 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2322 if (loop_info.iteration_phi != new_iteration_phi)
2330 mode = get_irn_mode(loop_info.end_val);
2332 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2333 loop_info.start_val, loop_info.end_val, loop_info.step));
2335 if (mode != mode_Is && mode != mode_Iu)
2338 /* TODO necessary? */
2339 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2342 DB((dbg, LEVEL_4, "mode integer\n"));
2344 end_tar = get_Const_tarval(loop_info.end_val);
2345 start_tar = get_Const_tarval(loop_info.start_val);
2346 step_tar = get_Const_tarval(loop_info.step);
2348 if (tarval_is_null(step_tar))
2349 /* TODO Might be worth a warning. */
2352 DB((dbg, LEVEL_4, "step is not 0\n"));
2354 if ((!tarval_is_negative(step_tar)) ^ (!is_Sub(loop_info.add)))
2355 loop_info.decreasing = 1;
2357 diff_tar = tarval_sub(end_tar, start_tar, mode);
2359 /* We need at least count_tar steps to be close to end_val, maybe more.
2360 * No way, that we have gone too many steps.
2361 * This represents the 'latest value'.
2362 * (If condition checks against latest value, is checked later) */
2363 count_tar = tarval_div(diff_tar, step_tar);
2365 /* Iv will not pass end_val (except overflows).
2366 * Nothing done, as it would yield to no advantage. */
2367 if (tarval_is_negative(count_tar)) {
2368 DB((dbg, LEVEL_1, "Loop is endless or never taken."));
2369 /* TODO Might be worth a warning. */
2373 count_stats(stats.u_simple_counting_loop);
2375 loop_info.latest_value = is_latest_val;
2378 if (! is_simple_counting_loop(&count_tar))
2382 /* stepped can be negative, if step < 0 */
2383 stepped = tarval_mul(count_tar, step_tar);
2385 /* step as close to end_val as possible, */
2386 /* |stepped| <= |end_tar|, and dist(stepped, end_tar) is smaller than a step. */
2387 if (is_Sub(loop_info.add))
2388 stepped = tarval_sub(start_tar, stepped, mode_Is);
2390 stepped = tarval_add(start_tar, stepped);
2392 DB((dbg, LEVEL_4, "stepped to %ld\n", get_tarval_long(stepped)));
2394 proj_proj = get_Proj_proj(projres);
2395 /* Assure that norm_proj is the stay-in-loop case. */
2396 if (loop_info.exit_cond == 1)
2397 norm_proj = get_math_inverted_case(proj_proj);
2399 norm_proj = proj_proj;
2401 DB((dbg, LEVEL_4, "normalized projection %s\n", get_pnc_string(norm_proj)));
2403 /* Executed at most once (stay in counting loop if a Eq b) */
2404 if (norm_proj == pn_Cmp_Eq)
2405 /* TODO Might be worth a warning. */
2408 /* calculates next values and increases count_tar according to it */
2409 success = simulate_next(&count_tar, stepped, step_tar, end_tar, norm_proj);
2413 /* We run loop once more, if we compare to the
2414 * not yet in-/decreased iv. */
2415 if (is_latest_val == 0) {
2416 DB((dbg, LEVEL_4, "condition uses not latest iv value\n"));
2417 count_tar = tarval_add(count_tar, get_tarval_one(mode));
2420 DB((dbg, LEVEL_4, "loop taken %ld times\n", get_tarval_long(count_tar)));
2422 /* Assure the loop is taken at least 1 time. */
2423 if (tarval_is_null(count_tar)) {
2424 /* TODO Might be worth a warning. */
2428 loop_info.count_tar = count_tar;
2429 return get_preferred_factor_constant(count_tar);
2435 static void unroll_loop(void)
2439 /* get_unroll_decision_constant and invariant are completely
2440 * independent for flexibility.
2441 * Some checks may be performed twice. */
2443 /* constant case? */
2444 if (opt_params.allow_const_unrolling)
2445 unroll_nr = get_unroll_decision_constant();
2446 if (unroll_nr > 1) {
2447 loop_info.unroll_kind = constant;
2450 /* invariant case? */
2451 if (opt_params.allow_invar_unrolling)
2452 unroll_nr = get_unroll_decision_invariant();
2454 loop_info.unroll_kind = invariant;
2457 DB((dbg, LEVEL_1, " *** Unrolling %d times ***\n", unroll_nr));
2459 if (unroll_nr > 1) {
2460 loop_entries = NEW_ARR_F(entry_edge, 0);
2463 irg_walk_graph(current_ir_graph, get_loop_entries, NULL, NULL);
2465 if ((int)get_tarval_long(loop_info.count_tar) == unroll_nr)
2466 loop_info.needs_backedge = 0;
2468 loop_info.needs_backedge = 1;
2470 /* Use phase to keep copy of nodes from the condition chain. */
2471 phase = new_phase(current_ir_graph, phase_irn_init_default);
2473 /* Copies the loop */
2474 copy_loop(loop_entries, unroll_nr - 1);
2476 /* Line up the floating copies. */
2477 place_copies(unroll_nr - 1);
2479 /* Remove phis with 1 in*/
2480 irg_walk_graph(current_ir_graph, correct_phis, NULL, NULL);
2482 /* dump_ir_block_graph(current_ir_graph, "-DONE"); */
2484 if (loop_info.unroll_kind == constant)
2485 count_stats(stats.constant_unroll);
2487 count_stats(stats.invariant_unroll);
2489 set_irg_doms_inconsistent(current_ir_graph);
2490 set_irg_loopinfo_inconsistent(current_ir_graph);
2492 set_irg_outs_inconsistent(current_ir_graph);
2494 DEL_ARR_F(loop_entries);
2499 /* Analyzes the loop, and checks if size is within allowed range.
2500 * Decides if loop will be processed. */
2501 static void init_analyze(ir_loop *loop)
2503 /* Expect no benefit of big loops. */
2504 /* TODO tuning/make parameter */
2506 unsigned max_loop_nodes = opt_params.max_loop_size;
2507 unsigned max_loop_nodes_adapted;
2508 int max_calls = opt_params.allowed_calls;
2509 int depth_adaption = opt_params.depth_adaption;
2514 loop_head_valid = 1;
2516 /* Reset loop info */
2517 memset(&loop_info, 0, sizeof(loop_info_t));
2519 DB((dbg, LEVEL_1, " >>>> current loop includes node %N <<<\n",
2520 get_loop_node(loop, 0)));
2522 /* Collect loop informations: head, node counts. */
2523 irg_walk_graph(current_ir_graph, get_loop_info, NULL, NULL);
2525 /* Depth of 0 is the procedure and 1 a topmost loop. */
2526 loop_depth = get_loop_depth(loop) - 1;
2528 /* Calculating in per mil. */
2529 max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
2531 DB((dbg, LEVEL_1, "max_nodes: %d\nmax_nodes_adapted %d at depth of %d (adaption %d)\n",
2532 max_loop_nodes, max_loop_nodes_adapted, loop_depth, depth_adaption));
2534 if (! (loop_info.nodes > 0))
2537 #if LOOP_IGNORE_NODE_LIMITS
2538 DB((dbg, LEVEL_1, "WARNING: Loop node limitations ignored."));
2540 if (loop_info.nodes > max_loop_nodes) {
2541 /* Only for stats */
2542 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes %d\n",
2543 loop_info.nodes, loop_depth, max_loop_nodes));
2544 count_stats(stats.too_large);
2546 /* Adaption might change it */
2549 /* Limit processing to loops smaller than given parameter. */
2550 if (loop_info.nodes > max_loop_nodes_adapted) {
2551 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes (depth %d adapted) %d\n",
2552 loop_info.nodes, loop_depth, max_loop_nodes_adapted));
2553 count_stats(stats.too_large_adapted);
2557 if (loop_info.calls > opt_params.allowed_calls) {
2558 DB((dbg, LEVEL_1, "Calls %d > allowed calls %d\n",
2559 loop_info.calls, max_calls));
2560 count_stats(stats.calls_limit);
2565 /* RETURN if there is no valid head */
2566 if (!loop_head || !loop_head_valid) {
2567 DB((dbg, LEVEL_1, "No valid loop head. Nothing done.\n"));
2570 DB((dbg, LEVEL_1, "Loophead: %N\n", loop_head));
2574 case loop_op_inversion:
2578 case loop_op_unrolling:
2583 panic("Loop optimization not implemented.");
2585 DB((dbg, LEVEL_1, " <<<< end of loop with node %N >>>>\n",
2586 get_loop_node(loop, 0)));
2589 /* Find innermost loops and add them to loops. */
2590 static void find_innermost_loop(ir_loop *loop)
2592 /* descend into sons */
2593 int sons = get_loop_n_sons(loop);
2596 ARR_APP1(ir_loop *, loops, loop);
2599 for (s=0; s<sons; s++) {
2600 find_innermost_loop(get_loop_son(loop, s));
2605 /* Assure preconditions are met and go through all loops. */
2606 void loop_optimization(ir_graph *irg)
2611 /* SPEC2000: Total time 98.9% with inversion only */
2612 opt_params.max_loop_size = 100;
2613 opt_params.depth_adaption = 400;
2614 opt_params.count_phi = 0;
2615 opt_params.count_proj = 0;
2616 opt_params.allowed_calls = 0;
2618 opt_params.max_cc_size = 100;
2620 /* Unrolling not yet tested */
2621 opt_params.allow_const_unrolling = 1;
2622 opt_params.allow_invar_unrolling = 1;
2624 /* Reset stats for this procedure */
2628 set_current_ir_graph(irg);
2631 assure_irg_outs(irg);
2633 /* NOTE: sets only the loop attribute of blocks, not nodes */
2634 /* NOTE: Kills links */
2635 assure_cf_loop(irg);
2637 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
2638 collect_phiprojs(irg);
2639 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2641 loop = get_irg_loop(irg);
2642 sons = get_loop_n_sons(loop);
2644 loops = NEW_ARR_F(ir_loop *, 0);
2645 /* List all inner loops */
2646 for (nr = 0; nr < sons; ++nr) {
2647 find_innermost_loop(get_loop_son(loop, nr));
2650 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2651 /* Set all links to NULL */
2652 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2654 for (i = 0; i < ARR_LEN(loops); ++i) {
2655 ir_loop *loop = loops[i];
2657 count_stats(stats.loops);
2659 /* Analyze and handle loop */
2662 /* Copied blocks do not have their phi list yet */
2663 collect_phiprojs(irg);
2665 /* Set links to NULL
2666 * TODO Still necessary? */
2667 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2673 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2674 ir_free_resources(irg, IR_RESOURCE_PHI_LIST);
2677 void do_loop_unrolling(ir_graph *irg)
2679 loop_op = loop_op_unrolling;
2681 DB((dbg, LEVEL_1, " >>> unrolling (Startnode %N) <<<\n",
2682 get_irg_start(irg)));
2684 loop_optimization(irg);
2686 DB((dbg, LEVEL_1, " >>> unrolling done (Startnode %N) <<<\n",
2687 get_irg_start(irg)));
2690 void do_loop_inversion(ir_graph *irg)
2692 loop_op = loop_op_inversion;
2694 DB((dbg, LEVEL_1, " >>> inversion (Startnode %N) <<<\n",
2695 get_irg_start(irg)));
2697 loop_optimization(irg);
2699 DB((dbg, LEVEL_1, " >>> inversion done (Startnode %N) <<<\n",
2700 get_irg_start(irg)));
2703 void do_loop_peeling(ir_graph *irg)
2705 loop_op = loop_op_peeling;
2707 DB((dbg, LEVEL_1, " >>> peeling (Startnode %N) <<<\n",
2708 get_irg_start(irg)));
2710 loop_optimization(irg);
2712 DB((dbg, LEVEL_1, " >>> peeling done (Startnode %N) <<<\n",
2713 get_irg_start(irg)));
2717 ir_graph_pass_t *loop_inversion_pass(const char *name)
2719 return def_graph_pass(name ? name : "loop_inversion", do_loop_inversion);
2722 ir_graph_pass_t *loop_unroll_pass(const char *name)
2724 return def_graph_pass(name ? name : "loop_unroll", do_loop_unrolling);
2727 ir_graph_pass_t *loop_peeling_pass(const char *name)
2729 return def_graph_pass(name ? name : "loop_peeling", do_loop_peeling);
2732 void firm_init_loop_opt(void)
2734 FIRM_DBG_REGISTER(dbg, "firm.opt.loop");