2016-09-25 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / gcc / loop-unroll.c
blob2d5fe48411b4d2801ecbdb594e9b78d455240259
1 /* Loop unrolling.
2 Copyright (C) 2002-2016 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "target.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "cfghooks.h"
28 #include "optabs.h"
29 #include "emit-rtl.h"
30 #include "recog.h"
31 #include "profile.h"
32 #include "cfgrtl.h"
33 #include "cfgloop.h"
34 #include "params.h"
35 #include "dojump.h"
36 #include "expr.h"
37 #include "dumpfile.h"
39 /* This pass performs loop unrolling. We only perform this
40 optimization on innermost loops (with single exception) because
41 the impact on performance is greatest here, and we want to avoid
42 unnecessary code size growth. The gain is caused by greater sequentiality
43 of code, better code to optimize for further passes and in some cases
44 by fewer testings of exit conditions. The main problem is code growth,
45 that impacts performance negatively due to effect of caches.
47 What we do:
49 -- unrolling of loops that roll constant times; this is almost always
50 win, as we get rid of exit condition tests.
51 -- unrolling of loops that roll number of times that we can compute
52 in runtime; we also get rid of exit condition tests here, but there
53 is the extra expense for calculating the number of iterations
54 -- simple unrolling of remaining loops; this is performed only if we
55 are asked to, as the gain is questionable in this case and often
56 it may even slow down the code
57 For more detailed descriptions of each of those, see comments at
58 appropriate function below.
60 There is a lot of parameters (defined and described in params.def) that
61 control how much we unroll.
63 ??? A great problem is that we don't have a good way how to determine
64 how many times we should unroll the loop; the experiments I have made
65 showed that this choice may affect performance in order of several %.
68 /* Information about induction variables to split. */
70 struct iv_to_split
72 rtx_insn *insn; /* The insn in that the induction variable occurs. */
73 rtx orig_var; /* The variable (register) for the IV before split. */
74 rtx base_var; /* The variable on that the values in the further
75 iterations are based. */
76 rtx step; /* Step of the induction variable. */
77 struct iv_to_split *next; /* Next entry in walking order. */
80 /* Information about accumulators to expand. */
82 struct var_to_expand
84 rtx_insn *insn; /* The insn in that the variable expansion occurs. */
85 rtx reg; /* The accumulator which is expanded. */
86 vec<rtx> var_expansions; /* The copies of the accumulator which is expanded. */
87 struct var_to_expand *next; /* Next entry in walking order. */
88 enum rtx_code op; /* The type of the accumulation - addition, subtraction
89 or multiplication. */
90 int expansion_count; /* Count the number of expansions generated so far. */
91 int reuse_expansion; /* The expansion we intend to reuse to expand
92 the accumulator. If REUSE_EXPANSION is 0 reuse
93 the original accumulator. Else use
94 var_expansions[REUSE_EXPANSION - 1]. */
97 /* Hashtable helper for iv_to_split. */
99 struct iv_split_hasher : free_ptr_hash <iv_to_split>
101 static inline hashval_t hash (const iv_to_split *);
102 static inline bool equal (const iv_to_split *, const iv_to_split *);
106 /* A hash function for information about insns to split. */
108 inline hashval_t
109 iv_split_hasher::hash (const iv_to_split *ivts)
111 return (hashval_t) INSN_UID (ivts->insn);
114 /* An equality functions for information about insns to split. */
116 inline bool
117 iv_split_hasher::equal (const iv_to_split *i1, const iv_to_split *i2)
119 return i1->insn == i2->insn;
122 /* Hashtable helper for iv_to_split. */
124 struct var_expand_hasher : free_ptr_hash <var_to_expand>
126 static inline hashval_t hash (const var_to_expand *);
127 static inline bool equal (const var_to_expand *, const var_to_expand *);
130 /* Return a hash for VES. */
132 inline hashval_t
133 var_expand_hasher::hash (const var_to_expand *ves)
135 return (hashval_t) INSN_UID (ves->insn);
138 /* Return true if I1 and I2 refer to the same instruction. */
140 inline bool
141 var_expand_hasher::equal (const var_to_expand *i1, const var_to_expand *i2)
143 return i1->insn == i2->insn;
146 /* Information about optimization applied in
147 the unrolled loop. */
149 struct opt_info
151 hash_table<iv_split_hasher> *insns_to_split; /* A hashtable of insns to
152 split. */
153 struct iv_to_split *iv_to_split_head; /* The first iv to split. */
154 struct iv_to_split **iv_to_split_tail; /* Pointer to the tail of the list. */
155 hash_table<var_expand_hasher> *insns_with_var_to_expand; /* A hashtable of
156 insns with accumulators to expand. */
157 struct var_to_expand *var_to_expand_head; /* The first var to expand. */
158 struct var_to_expand **var_to_expand_tail; /* Pointer to the tail of the list. */
159 unsigned first_new_block; /* The first basic block that was
160 duplicated. */
161 basic_block loop_exit; /* The loop exit basic block. */
162 basic_block loop_preheader; /* The loop preheader basic block. */
165 static void decide_unroll_stupid (struct loop *, int);
166 static void decide_unroll_constant_iterations (struct loop *, int);
167 static void decide_unroll_runtime_iterations (struct loop *, int);
168 static void unroll_loop_stupid (struct loop *);
169 static void decide_unrolling (int);
170 static void unroll_loop_constant_iterations (struct loop *);
171 static void unroll_loop_runtime_iterations (struct loop *);
172 static struct opt_info *analyze_insns_in_loop (struct loop *);
173 static void opt_info_start_duplication (struct opt_info *);
174 static void apply_opt_in_copies (struct opt_info *, unsigned, bool, bool);
175 static void free_opt_info (struct opt_info *);
176 static struct var_to_expand *analyze_insn_to_expand_var (struct loop*, rtx_insn *);
177 static bool referenced_in_one_insn_in_loop_p (struct loop *, rtx, int *);
178 static struct iv_to_split *analyze_iv_to_split_insn (rtx_insn *);
179 static void expand_var_during_unrolling (struct var_to_expand *, rtx_insn *);
180 static void insert_var_expansion_initialization (struct var_to_expand *,
181 basic_block);
182 static void combine_var_copies_in_loop_exit (struct var_to_expand *,
183 basic_block);
184 static rtx get_expansion (struct var_to_expand *);
186 /* Emit a message summarizing the unroll that will be
187 performed for LOOP, along with the loop's location LOCUS, if
188 appropriate given the dump or -fopt-info settings. */
190 static void
191 report_unroll (struct loop *loop, location_t locus)
193 int report_flags = MSG_OPTIMIZED_LOCATIONS | TDF_RTL | TDF_DETAILS;
195 if (loop->lpt_decision.decision == LPT_NONE)
196 return;
198 if (!dump_enabled_p ())
199 return;
201 dump_printf_loc (report_flags, locus,
202 "loop unrolled %d times",
203 loop->lpt_decision.times);
204 if (profile_info)
205 dump_printf (report_flags,
206 " (header execution count %d)",
207 (int)loop->header->count);
209 dump_printf (report_flags, "\n");
212 /* Decide whether unroll loops and how much. */
213 static void
214 decide_unrolling (int flags)
216 struct loop *loop;
218 /* Scan the loops, inner ones first. */
219 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
221 loop->lpt_decision.decision = LPT_NONE;
222 location_t locus = get_loop_location (loop);
224 if (dump_enabled_p ())
225 dump_printf_loc (TDF_RTL, locus,
226 ";; *** Considering loop %d at BB %d for "
227 "unrolling ***\n",
228 loop->num, loop->header->index);
230 /* Do not peel cold areas. */
231 if (optimize_loop_for_size_p (loop))
233 if (dump_file)
234 fprintf (dump_file, ";; Not considering loop, cold area\n");
235 continue;
238 /* Can the loop be manipulated? */
239 if (!can_duplicate_loop_p (loop))
241 if (dump_file)
242 fprintf (dump_file,
243 ";; Not considering loop, cannot duplicate\n");
244 continue;
247 /* Skip non-innermost loops. */
248 if (loop->inner)
250 if (dump_file)
251 fprintf (dump_file, ";; Not considering loop, is not innermost\n");
252 continue;
255 loop->ninsns = num_loop_insns (loop);
256 loop->av_ninsns = average_num_loop_insns (loop);
258 /* Try transformations one by one in decreasing order of
259 priority. */
261 decide_unroll_constant_iterations (loop, flags);
262 if (loop->lpt_decision.decision == LPT_NONE)
263 decide_unroll_runtime_iterations (loop, flags);
264 if (loop->lpt_decision.decision == LPT_NONE)
265 decide_unroll_stupid (loop, flags);
267 report_unroll (loop, locus);
271 /* Unroll LOOPS. */
272 void
273 unroll_loops (int flags)
275 struct loop *loop;
276 bool changed = false;
278 /* Now decide rest of unrolling. */
279 decide_unrolling (flags);
281 /* Scan the loops, inner ones first. */
282 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
284 /* And perform the appropriate transformations. */
285 switch (loop->lpt_decision.decision)
287 case LPT_UNROLL_CONSTANT:
288 unroll_loop_constant_iterations (loop);
289 changed = true;
290 break;
291 case LPT_UNROLL_RUNTIME:
292 unroll_loop_runtime_iterations (loop);
293 changed = true;
294 break;
295 case LPT_UNROLL_STUPID:
296 unroll_loop_stupid (loop);
297 changed = true;
298 break;
299 case LPT_NONE:
300 break;
301 default:
302 gcc_unreachable ();
306 if (changed)
308 calculate_dominance_info (CDI_DOMINATORS);
309 fix_loop_structure (NULL);
312 iv_analysis_done ();
315 /* Check whether exit of the LOOP is at the end of loop body. */
317 static bool
318 loop_exit_at_end_p (struct loop *loop)
320 struct niter_desc *desc = get_simple_loop_desc (loop);
321 rtx_insn *insn;
323 /* We should never have conditional in latch block. */
324 gcc_assert (desc->in_edge->dest != loop->header);
326 if (desc->in_edge->dest != loop->latch)
327 return false;
329 /* Check that the latch is empty. */
330 FOR_BB_INSNS (loop->latch, insn)
332 if (INSN_P (insn) && active_insn_p (insn))
333 return false;
336 return true;
339 /* Decide whether to unroll LOOP iterating constant number of times
340 and how much. */
342 static void
343 decide_unroll_constant_iterations (struct loop *loop, int flags)
345 unsigned nunroll, nunroll_by_av, best_copies, best_unroll = 0, n_copies, i;
346 struct niter_desc *desc;
347 widest_int iterations;
349 if (!(flags & UAP_UNROLL))
351 /* We were not asked to, just return back silently. */
352 return;
355 if (dump_file)
356 fprintf (dump_file,
357 "\n;; Considering unrolling loop with constant "
358 "number of iterations\n");
360 /* nunroll = total number of copies of the original loop body in
361 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
362 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
363 nunroll_by_av
364 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
365 if (nunroll > nunroll_by_av)
366 nunroll = nunroll_by_av;
367 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
368 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
370 if (targetm.loop_unroll_adjust)
371 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
373 /* Skip big loops. */
374 if (nunroll <= 1)
376 if (dump_file)
377 fprintf (dump_file, ";; Not considering loop, is too big\n");
378 return;
381 /* Check for simple loops. */
382 desc = get_simple_loop_desc (loop);
384 /* Check number of iterations. */
385 if (!desc->simple_p || !desc->const_iter || desc->assumptions)
387 if (dump_file)
388 fprintf (dump_file,
389 ";; Unable to prove that the loop iterates constant times\n");
390 return;
393 /* Check whether the loop rolls enough to consider.
394 Consult also loop bounds and profile; in the case the loop has more
395 than one exit it may well loop less than determined maximal number
396 of iterations. */
397 if (desc->niter < 2 * nunroll
398 || ((get_estimated_loop_iterations (loop, &iterations)
399 || get_likely_max_loop_iterations (loop, &iterations))
400 && wi::ltu_p (iterations, 2 * nunroll)))
402 if (dump_file)
403 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
404 return;
407 /* Success; now compute number of iterations to unroll. We alter
408 nunroll so that as few as possible copies of loop body are
409 necessary, while still not decreasing the number of unrollings
410 too much (at most by 1). */
411 best_copies = 2 * nunroll + 10;
413 i = 2 * nunroll + 2;
414 if (i - 1 >= desc->niter)
415 i = desc->niter - 2;
417 for (; i >= nunroll - 1; i--)
419 unsigned exit_mod = desc->niter % (i + 1);
421 if (!loop_exit_at_end_p (loop))
422 n_copies = exit_mod + i + 1;
423 else if (exit_mod != (unsigned) i
424 || desc->noloop_assumptions != NULL_RTX)
425 n_copies = exit_mod + i + 2;
426 else
427 n_copies = i + 1;
429 if (n_copies < best_copies)
431 best_copies = n_copies;
432 best_unroll = i;
436 loop->lpt_decision.decision = LPT_UNROLL_CONSTANT;
437 loop->lpt_decision.times = best_unroll;
440 /* Unroll LOOP with constant number of iterations LOOP->LPT_DECISION.TIMES times.
441 The transformation does this:
443 for (i = 0; i < 102; i++)
444 body;
446 ==> (LOOP->LPT_DECISION.TIMES == 3)
448 i = 0;
449 body; i++;
450 body; i++;
451 while (i < 102)
453 body; i++;
454 body; i++;
455 body; i++;
456 body; i++;
459 static void
460 unroll_loop_constant_iterations (struct loop *loop)
462 unsigned HOST_WIDE_INT niter;
463 unsigned exit_mod;
464 unsigned i;
465 edge e;
466 unsigned max_unroll = loop->lpt_decision.times;
467 struct niter_desc *desc = get_simple_loop_desc (loop);
468 bool exit_at_end = loop_exit_at_end_p (loop);
469 struct opt_info *opt_info = NULL;
470 bool ok;
472 niter = desc->niter;
474 /* Should not get here (such loop should be peeled instead). */
475 gcc_assert (niter > max_unroll + 1);
477 exit_mod = niter % (max_unroll + 1);
479 auto_sbitmap wont_exit (max_unroll + 1);
480 bitmap_ones (wont_exit);
482 auto_vec<edge> remove_edges;
483 if (flag_split_ivs_in_unroller
484 || flag_variable_expansion_in_unroller)
485 opt_info = analyze_insns_in_loop (loop);
487 if (!exit_at_end)
489 /* The exit is not at the end of the loop; leave exit test
490 in the first copy, so that the loops that start with test
491 of exit condition have continuous body after unrolling. */
493 if (dump_file)
494 fprintf (dump_file, ";; Condition at beginning of loop.\n");
496 /* Peel exit_mod iterations. */
497 bitmap_clear_bit (wont_exit, 0);
498 if (desc->noloop_assumptions)
499 bitmap_clear_bit (wont_exit, 1);
501 if (exit_mod)
503 opt_info_start_duplication (opt_info);
504 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
505 exit_mod,
506 wont_exit, desc->out_edge,
507 &remove_edges,
508 DLTHE_FLAG_UPDATE_FREQ
509 | (opt_info && exit_mod > 1
510 ? DLTHE_RECORD_COPY_NUMBER
511 : 0));
512 gcc_assert (ok);
514 if (opt_info && exit_mod > 1)
515 apply_opt_in_copies (opt_info, exit_mod, false, false);
517 desc->noloop_assumptions = NULL_RTX;
518 desc->niter -= exit_mod;
519 loop->nb_iterations_upper_bound -= exit_mod;
520 if (loop->any_estimate
521 && wi::leu_p (exit_mod, loop->nb_iterations_estimate))
522 loop->nb_iterations_estimate -= exit_mod;
523 else
524 loop->any_estimate = false;
525 if (loop->any_likely_upper_bound
526 && wi::leu_p (exit_mod, loop->nb_iterations_likely_upper_bound))
527 loop->nb_iterations_likely_upper_bound -= exit_mod;
528 else
529 loop->any_likely_upper_bound = false;
532 bitmap_set_bit (wont_exit, 1);
534 else
536 /* Leave exit test in last copy, for the same reason as above if
537 the loop tests the condition at the end of loop body. */
539 if (dump_file)
540 fprintf (dump_file, ";; Condition at end of loop.\n");
542 /* We know that niter >= max_unroll + 2; so we do not need to care of
543 case when we would exit before reaching the loop. So just peel
544 exit_mod + 1 iterations. */
545 if (exit_mod != max_unroll
546 || desc->noloop_assumptions)
548 bitmap_clear_bit (wont_exit, 0);
549 if (desc->noloop_assumptions)
550 bitmap_clear_bit (wont_exit, 1);
552 opt_info_start_duplication (opt_info);
553 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
554 exit_mod + 1,
555 wont_exit, desc->out_edge,
556 &remove_edges,
557 DLTHE_FLAG_UPDATE_FREQ
558 | (opt_info && exit_mod > 0
559 ? DLTHE_RECORD_COPY_NUMBER
560 : 0));
561 gcc_assert (ok);
563 if (opt_info && exit_mod > 0)
564 apply_opt_in_copies (opt_info, exit_mod + 1, false, false);
566 desc->niter -= exit_mod + 1;
567 loop->nb_iterations_upper_bound -= exit_mod + 1;
568 if (loop->any_estimate
569 && wi::leu_p (exit_mod + 1, loop->nb_iterations_estimate))
570 loop->nb_iterations_estimate -= exit_mod + 1;
571 else
572 loop->any_estimate = false;
573 if (loop->any_likely_upper_bound
574 && wi::leu_p (exit_mod + 1, loop->nb_iterations_likely_upper_bound))
575 loop->nb_iterations_likely_upper_bound -= exit_mod + 1;
576 else
577 loop->any_likely_upper_bound = false;
578 desc->noloop_assumptions = NULL_RTX;
580 bitmap_set_bit (wont_exit, 0);
581 bitmap_set_bit (wont_exit, 1);
584 bitmap_clear_bit (wont_exit, max_unroll);
587 /* Now unroll the loop. */
589 opt_info_start_duplication (opt_info);
590 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
591 max_unroll,
592 wont_exit, desc->out_edge,
593 &remove_edges,
594 DLTHE_FLAG_UPDATE_FREQ
595 | (opt_info
596 ? DLTHE_RECORD_COPY_NUMBER
597 : 0));
598 gcc_assert (ok);
600 if (opt_info)
602 apply_opt_in_copies (opt_info, max_unroll, true, true);
603 free_opt_info (opt_info);
606 if (exit_at_end)
608 basic_block exit_block = get_bb_copy (desc->in_edge->src);
609 /* Find a new in and out edge; they are in the last copy we have made. */
611 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
613 desc->out_edge = EDGE_SUCC (exit_block, 0);
614 desc->in_edge = EDGE_SUCC (exit_block, 1);
616 else
618 desc->out_edge = EDGE_SUCC (exit_block, 1);
619 desc->in_edge = EDGE_SUCC (exit_block, 0);
623 desc->niter /= max_unroll + 1;
624 loop->nb_iterations_upper_bound
625 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
626 if (loop->any_estimate)
627 loop->nb_iterations_estimate
628 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
629 if (loop->any_likely_upper_bound)
630 loop->nb_iterations_likely_upper_bound
631 = wi::udiv_trunc (loop->nb_iterations_likely_upper_bound, max_unroll + 1);
632 desc->niter_expr = GEN_INT (desc->niter);
634 /* Remove the edges. */
635 FOR_EACH_VEC_ELT (remove_edges, i, e)
636 remove_path (e);
638 if (dump_file)
639 fprintf (dump_file,
640 ";; Unrolled loop %d times, constant # of iterations %i insns\n",
641 max_unroll, num_loop_insns (loop));
644 /* Decide whether to unroll LOOP iterating runtime computable number of times
645 and how much. */
646 static void
647 decide_unroll_runtime_iterations (struct loop *loop, int flags)
649 unsigned nunroll, nunroll_by_av, i;
650 struct niter_desc *desc;
651 widest_int iterations;
653 if (!(flags & UAP_UNROLL))
655 /* We were not asked to, just return back silently. */
656 return;
659 if (dump_file)
660 fprintf (dump_file,
661 "\n;; Considering unrolling loop with runtime "
662 "computable number of iterations\n");
664 /* nunroll = total number of copies of the original loop body in
665 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
666 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
667 nunroll_by_av = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
668 if (nunroll > nunroll_by_av)
669 nunroll = nunroll_by_av;
670 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
671 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
673 if (targetm.loop_unroll_adjust)
674 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
676 /* Skip big loops. */
677 if (nunroll <= 1)
679 if (dump_file)
680 fprintf (dump_file, ";; Not considering loop, is too big\n");
681 return;
684 /* Check for simple loops. */
685 desc = get_simple_loop_desc (loop);
687 /* Check simpleness. */
688 if (!desc->simple_p || desc->assumptions)
690 if (dump_file)
691 fprintf (dump_file,
692 ";; Unable to prove that the number of iterations "
693 "can be counted in runtime\n");
694 return;
697 if (desc->const_iter)
699 if (dump_file)
700 fprintf (dump_file, ";; Loop iterates constant times\n");
701 return;
704 /* Check whether the loop rolls. */
705 if ((get_estimated_loop_iterations (loop, &iterations)
706 || get_likely_max_loop_iterations (loop, &iterations))
707 && wi::ltu_p (iterations, 2 * nunroll))
709 if (dump_file)
710 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
711 return;
714 /* Success; now force nunroll to be power of 2, as we are unable to
715 cope with overflows in computation of number of iterations. */
716 for (i = 1; 2 * i <= nunroll; i *= 2)
717 continue;
719 loop->lpt_decision.decision = LPT_UNROLL_RUNTIME;
720 loop->lpt_decision.times = i - 1;
723 /* Splits edge E and inserts the sequence of instructions INSNS on it, and
724 returns the newly created block. If INSNS is NULL_RTX, nothing is changed
725 and NULL is returned instead. */
727 basic_block
728 split_edge_and_insert (edge e, rtx_insn *insns)
730 basic_block bb;
732 if (!insns)
733 return NULL;
734 bb = split_edge (e);
735 emit_insn_after (insns, BB_END (bb));
737 /* ??? We used to assume that INSNS can contain control flow insns, and
738 that we had to try to find sub basic blocks in BB to maintain a valid
739 CFG. For this purpose we used to set the BB_SUPERBLOCK flag on BB
740 and call break_superblocks when going out of cfglayout mode. But it
741 turns out that this never happens; and that if it does ever happen,
742 the verify_flow_info at the end of the RTL loop passes would fail.
744 There are two reasons why we expected we could have control flow insns
745 in INSNS. The first is when a comparison has to be done in parts, and
746 the second is when the number of iterations is computed for loops with
747 the number of iterations known at runtime. In both cases, test cases
748 to get control flow in INSNS appear to be impossible to construct:
750 * If do_compare_rtx_and_jump needs several branches to do comparison
751 in a mode that needs comparison by parts, we cannot analyze the
752 number of iterations of the loop, and we never get to unrolling it.
754 * The code in expand_divmod that was suspected to cause creation of
755 branching code seems to be only accessed for signed division. The
756 divisions used by # of iterations analysis are always unsigned.
757 Problems might arise on architectures that emits branching code
758 for some operations that may appear in the unroller (especially
759 for division), but we have no such architectures.
761 Considering all this, it was decided that we should for now assume
762 that INSNS can in theory contain control flow insns, but in practice
763 it never does. So we don't handle the theoretical case, and should
764 a real failure ever show up, we have a pretty good clue for how to
765 fix it. */
767 return bb;
770 /* Prepare a sequence comparing OP0 with OP1 using COMP and jumping to LABEL if
771 true, with probability PROB. If CINSN is not NULL, it is the insn to copy
772 in order to create a jump. */
774 static rtx_insn *
775 compare_and_jump_seq (rtx op0, rtx op1, enum rtx_code comp,
776 rtx_code_label *label, int prob, rtx_insn *cinsn)
778 rtx_insn *seq;
779 rtx_jump_insn *jump;
780 rtx cond;
781 machine_mode mode;
783 mode = GET_MODE (op0);
784 if (mode == VOIDmode)
785 mode = GET_MODE (op1);
787 start_sequence ();
788 if (GET_MODE_CLASS (mode) == MODE_CC)
790 /* A hack -- there seems to be no easy generic way how to make a
791 conditional jump from a ccmode comparison. */
792 gcc_assert (cinsn);
793 cond = XEXP (SET_SRC (pc_set (cinsn)), 0);
794 gcc_assert (GET_CODE (cond) == comp);
795 gcc_assert (rtx_equal_p (op0, XEXP (cond, 0)));
796 gcc_assert (rtx_equal_p (op1, XEXP (cond, 1)));
797 emit_jump_insn (copy_insn (PATTERN (cinsn)));
798 jump = as_a <rtx_jump_insn *> (get_last_insn ());
799 JUMP_LABEL (jump) = JUMP_LABEL (cinsn);
800 LABEL_NUSES (JUMP_LABEL (jump))++;
801 redirect_jump (jump, label, 0);
803 else
805 gcc_assert (!cinsn);
807 op0 = force_operand (op0, NULL_RTX);
808 op1 = force_operand (op1, NULL_RTX);
809 do_compare_rtx_and_jump (op0, op1, comp, 0,
810 mode, NULL_RTX, NULL, label, -1);
811 jump = as_a <rtx_jump_insn *> (get_last_insn ());
812 jump->set_jump_target (label);
813 LABEL_NUSES (label)++;
815 add_int_reg_note (jump, REG_BR_PROB, prob);
817 seq = get_insns ();
818 end_sequence ();
820 return seq;
823 /* Unroll LOOP for which we are able to count number of iterations in runtime
824 LOOP->LPT_DECISION.TIMES times. The transformation does this (with some
825 extra care for case n < 0):
827 for (i = 0; i < n; i++)
828 body;
830 ==> (LOOP->LPT_DECISION.TIMES == 3)
832 i = 0;
833 mod = n % 4;
835 switch (mod)
837 case 3:
838 body; i++;
839 case 2:
840 body; i++;
841 case 1:
842 body; i++;
843 case 0: ;
846 while (i < n)
848 body; i++;
849 body; i++;
850 body; i++;
851 body; i++;
854 static void
855 unroll_loop_runtime_iterations (struct loop *loop)
857 rtx old_niter, niter, tmp;
858 rtx_insn *init_code, *branch_code;
859 unsigned i, j, p;
860 basic_block preheader, *body, swtch, ezc_swtch;
861 int may_exit_copy;
862 unsigned n_peel;
863 edge e;
864 bool extra_zero_check, last_may_exit;
865 unsigned max_unroll = loop->lpt_decision.times;
866 struct niter_desc *desc = get_simple_loop_desc (loop);
867 bool exit_at_end = loop_exit_at_end_p (loop);
868 struct opt_info *opt_info = NULL;
869 bool ok;
871 if (flag_split_ivs_in_unroller
872 || flag_variable_expansion_in_unroller)
873 opt_info = analyze_insns_in_loop (loop);
875 /* Remember blocks whose dominators will have to be updated. */
876 auto_vec<basic_block> dom_bbs;
878 body = get_loop_body (loop);
879 for (i = 0; i < loop->num_nodes; i++)
881 vec<basic_block> ldom;
882 basic_block bb;
884 ldom = get_dominated_by (CDI_DOMINATORS, body[i]);
885 FOR_EACH_VEC_ELT (ldom, j, bb)
886 if (!flow_bb_inside_loop_p (loop, bb))
887 dom_bbs.safe_push (bb);
889 ldom.release ();
891 free (body);
893 if (!exit_at_end)
895 /* Leave exit in first copy (for explanation why see comment in
896 unroll_loop_constant_iterations). */
897 may_exit_copy = 0;
898 n_peel = max_unroll - 1;
899 extra_zero_check = true;
900 last_may_exit = false;
902 else
904 /* Leave exit in last copy (for explanation why see comment in
905 unroll_loop_constant_iterations). */
906 may_exit_copy = max_unroll;
907 n_peel = max_unroll;
908 extra_zero_check = false;
909 last_may_exit = true;
912 /* Get expression for number of iterations. */
913 start_sequence ();
914 old_niter = niter = gen_reg_rtx (desc->mode);
915 tmp = force_operand (copy_rtx (desc->niter_expr), niter);
916 if (tmp != niter)
917 emit_move_insn (niter, tmp);
919 /* Count modulo by ANDing it with max_unroll; we use the fact that
920 the number of unrollings is a power of two, and thus this is correct
921 even if there is overflow in the computation. */
922 niter = expand_simple_binop (desc->mode, AND,
923 niter, gen_int_mode (max_unroll, desc->mode),
924 NULL_RTX, 0, OPTAB_LIB_WIDEN);
926 init_code = get_insns ();
927 end_sequence ();
928 unshare_all_rtl_in_chain (init_code);
930 /* Precondition the loop. */
931 split_edge_and_insert (loop_preheader_edge (loop), init_code);
933 auto_vec<edge> remove_edges;
935 auto_sbitmap wont_exit (max_unroll + 2);
937 /* Peel the first copy of loop body (almost always we must leave exit test
938 here; the only exception is when we have extra zero check and the number
939 of iterations is reliable. Also record the place of (possible) extra
940 zero check. */
941 bitmap_clear (wont_exit);
942 if (extra_zero_check
943 && !desc->noloop_assumptions)
944 bitmap_set_bit (wont_exit, 1);
945 ezc_swtch = loop_preheader_edge (loop)->src;
946 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
947 1, wont_exit, desc->out_edge,
948 &remove_edges,
949 DLTHE_FLAG_UPDATE_FREQ);
950 gcc_assert (ok);
952 /* Record the place where switch will be built for preconditioning. */
953 swtch = split_edge (loop_preheader_edge (loop));
955 for (i = 0; i < n_peel; i++)
957 /* Peel the copy. */
958 bitmap_clear (wont_exit);
959 if (i != n_peel - 1 || !last_may_exit)
960 bitmap_set_bit (wont_exit, 1);
961 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
962 1, wont_exit, desc->out_edge,
963 &remove_edges,
964 DLTHE_FLAG_UPDATE_FREQ);
965 gcc_assert (ok);
967 /* Create item for switch. */
968 j = n_peel - i - (extra_zero_check ? 0 : 1);
969 p = REG_BR_PROB_BASE / (i + 2);
971 preheader = split_edge (loop_preheader_edge (loop));
972 branch_code = compare_and_jump_seq (copy_rtx (niter), GEN_INT (j), EQ,
973 block_label (preheader), p,
974 NULL);
976 /* We rely on the fact that the compare and jump cannot be optimized out,
977 and hence the cfg we create is correct. */
978 gcc_assert (branch_code != NULL_RTX);
980 swtch = split_edge_and_insert (single_pred_edge (swtch), branch_code);
981 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
982 single_succ_edge (swtch)->probability = REG_BR_PROB_BASE - p;
983 e = make_edge (swtch, preheader,
984 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
985 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
986 e->probability = p;
989 if (extra_zero_check)
991 /* Add branch for zero iterations. */
992 p = REG_BR_PROB_BASE / (max_unroll + 1);
993 swtch = ezc_swtch;
994 preheader = split_edge (loop_preheader_edge (loop));
995 branch_code = compare_and_jump_seq (copy_rtx (niter), const0_rtx, EQ,
996 block_label (preheader), p,
997 NULL);
998 gcc_assert (branch_code != NULL_RTX);
1000 swtch = split_edge_and_insert (single_succ_edge (swtch), branch_code);
1001 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
1002 single_succ_edge (swtch)->probability = REG_BR_PROB_BASE - p;
1003 e = make_edge (swtch, preheader,
1004 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
1005 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
1006 e->probability = p;
1009 /* Recount dominators for outer blocks. */
1010 iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, false);
1012 /* And unroll loop. */
1014 bitmap_ones (wont_exit);
1015 bitmap_clear_bit (wont_exit, may_exit_copy);
1016 opt_info_start_duplication (opt_info);
1018 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1019 max_unroll,
1020 wont_exit, desc->out_edge,
1021 &remove_edges,
1022 DLTHE_FLAG_UPDATE_FREQ
1023 | (opt_info
1024 ? DLTHE_RECORD_COPY_NUMBER
1025 : 0));
1026 gcc_assert (ok);
1028 if (opt_info)
1030 apply_opt_in_copies (opt_info, max_unroll, true, true);
1031 free_opt_info (opt_info);
1034 if (exit_at_end)
1036 basic_block exit_block = get_bb_copy (desc->in_edge->src);
1037 /* Find a new in and out edge; they are in the last copy we have
1038 made. */
1040 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
1042 desc->out_edge = EDGE_SUCC (exit_block, 0);
1043 desc->in_edge = EDGE_SUCC (exit_block, 1);
1045 else
1047 desc->out_edge = EDGE_SUCC (exit_block, 1);
1048 desc->in_edge = EDGE_SUCC (exit_block, 0);
1052 /* Remove the edges. */
1053 FOR_EACH_VEC_ELT (remove_edges, i, e)
1054 remove_path (e);
1056 /* We must be careful when updating the number of iterations due to
1057 preconditioning and the fact that the value must be valid at entry
1058 of the loop. After passing through the above code, we see that
1059 the correct new number of iterations is this: */
1060 gcc_assert (!desc->const_iter);
1061 desc->niter_expr =
1062 simplify_gen_binary (UDIV, desc->mode, old_niter,
1063 gen_int_mode (max_unroll + 1, desc->mode));
1064 loop->nb_iterations_upper_bound
1065 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
1066 if (loop->any_estimate)
1067 loop->nb_iterations_estimate
1068 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
1069 if (loop->any_likely_upper_bound)
1070 loop->nb_iterations_likely_upper_bound
1071 = wi::udiv_trunc (loop->nb_iterations_likely_upper_bound, max_unroll + 1);
1072 if (exit_at_end)
1074 desc->niter_expr =
1075 simplify_gen_binary (MINUS, desc->mode, desc->niter_expr, const1_rtx);
1076 desc->noloop_assumptions = NULL_RTX;
1077 --loop->nb_iterations_upper_bound;
1078 if (loop->any_estimate
1079 && loop->nb_iterations_estimate != 0)
1080 --loop->nb_iterations_estimate;
1081 else
1082 loop->any_estimate = false;
1083 if (loop->any_likely_upper_bound
1084 && loop->nb_iterations_likely_upper_bound != 0)
1085 --loop->nb_iterations_likely_upper_bound;
1086 else
1087 loop->any_likely_upper_bound = false;
1090 if (dump_file)
1091 fprintf (dump_file,
1092 ";; Unrolled loop %d times, counting # of iterations "
1093 "in runtime, %i insns\n",
1094 max_unroll, num_loop_insns (loop));
1097 /* Decide whether to unroll LOOP stupidly and how much. */
1098 static void
1099 decide_unroll_stupid (struct loop *loop, int flags)
1101 unsigned nunroll, nunroll_by_av, i;
1102 struct niter_desc *desc;
1103 widest_int iterations;
1105 if (!(flags & UAP_UNROLL_ALL))
1107 /* We were not asked to, just return back silently. */
1108 return;
1111 if (dump_file)
1112 fprintf (dump_file, "\n;; Considering unrolling loop stupidly\n");
1114 /* nunroll = total number of copies of the original loop body in
1115 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
1116 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
1117 nunroll_by_av
1118 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
1119 if (nunroll > nunroll_by_av)
1120 nunroll = nunroll_by_av;
1121 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
1122 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1124 if (targetm.loop_unroll_adjust)
1125 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
1127 /* Skip big loops. */
1128 if (nunroll <= 1)
1130 if (dump_file)
1131 fprintf (dump_file, ";; Not considering loop, is too big\n");
1132 return;
1135 /* Check for simple loops. */
1136 desc = get_simple_loop_desc (loop);
1138 /* Check simpleness. */
1139 if (desc->simple_p && !desc->assumptions)
1141 if (dump_file)
1142 fprintf (dump_file, ";; The loop is simple\n");
1143 return;
1146 /* Do not unroll loops with branches inside -- it increases number
1147 of mispredicts.
1148 TODO: this heuristic needs tunning; call inside the loop body
1149 is also relatively good reason to not unroll. */
1150 if (num_loop_branches (loop) > 1)
1152 if (dump_file)
1153 fprintf (dump_file, ";; Not unrolling, contains branches\n");
1154 return;
1157 /* Check whether the loop rolls. */
1158 if ((get_estimated_loop_iterations (loop, &iterations)
1159 || get_likely_max_loop_iterations (loop, &iterations))
1160 && wi::ltu_p (iterations, 2 * nunroll))
1162 if (dump_file)
1163 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
1164 return;
1167 /* Success. Now force nunroll to be power of 2, as it seems that this
1168 improves results (partially because of better alignments, partially
1169 because of some dark magic). */
1170 for (i = 1; 2 * i <= nunroll; i *= 2)
1171 continue;
1173 loop->lpt_decision.decision = LPT_UNROLL_STUPID;
1174 loop->lpt_decision.times = i - 1;
1177 /* Unroll a LOOP LOOP->LPT_DECISION.TIMES times. The transformation does this:
1179 while (cond)
1180 body;
1182 ==> (LOOP->LPT_DECISION.TIMES == 3)
1184 while (cond)
1186 body;
1187 if (!cond) break;
1188 body;
1189 if (!cond) break;
1190 body;
1191 if (!cond) break;
1192 body;
1195 static void
1196 unroll_loop_stupid (struct loop *loop)
1198 unsigned nunroll = loop->lpt_decision.times;
1199 struct niter_desc *desc = get_simple_loop_desc (loop);
1200 struct opt_info *opt_info = NULL;
1201 bool ok;
1203 if (flag_split_ivs_in_unroller
1204 || flag_variable_expansion_in_unroller)
1205 opt_info = analyze_insns_in_loop (loop);
1207 auto_sbitmap wont_exit (nunroll + 1);
1208 bitmap_clear (wont_exit);
1209 opt_info_start_duplication (opt_info);
1211 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1212 nunroll, wont_exit,
1213 NULL, NULL,
1214 DLTHE_FLAG_UPDATE_FREQ
1215 | (opt_info
1216 ? DLTHE_RECORD_COPY_NUMBER
1217 : 0));
1218 gcc_assert (ok);
1220 if (opt_info)
1222 apply_opt_in_copies (opt_info, nunroll, true, true);
1223 free_opt_info (opt_info);
1226 if (desc->simple_p)
1228 /* We indeed may get here provided that there are nontrivial assumptions
1229 for a loop to be really simple. We could update the counts, but the
1230 problem is that we are unable to decide which exit will be taken
1231 (not really true in case the number of iterations is constant,
1232 but no one will do anything with this information, so we do not
1233 worry about it). */
1234 desc->simple_p = false;
1237 if (dump_file)
1238 fprintf (dump_file, ";; Unrolled loop %d times, %i insns\n",
1239 nunroll, num_loop_insns (loop));
1242 /* Returns true if REG is referenced in one nondebug insn in LOOP.
1243 Set *DEBUG_USES to the number of debug insns that reference the
1244 variable. */
1246 static bool
1247 referenced_in_one_insn_in_loop_p (struct loop *loop, rtx reg,
1248 int *debug_uses)
1250 basic_block *body, bb;
1251 unsigned i;
1252 int count_ref = 0;
1253 rtx_insn *insn;
1255 body = get_loop_body (loop);
1256 for (i = 0; i < loop->num_nodes; i++)
1258 bb = body[i];
1260 FOR_BB_INSNS (bb, insn)
1261 if (!rtx_referenced_p (reg, insn))
1262 continue;
1263 else if (DEBUG_INSN_P (insn))
1264 ++*debug_uses;
1265 else if (++count_ref > 1)
1266 break;
1268 free (body);
1269 return (count_ref == 1);
1272 /* Reset the DEBUG_USES debug insns in LOOP that reference REG. */
1274 static void
1275 reset_debug_uses_in_loop (struct loop *loop, rtx reg, int debug_uses)
1277 basic_block *body, bb;
1278 unsigned i;
1279 rtx_insn *insn;
1281 body = get_loop_body (loop);
1282 for (i = 0; debug_uses && i < loop->num_nodes; i++)
1284 bb = body[i];
1286 FOR_BB_INSNS (bb, insn)
1287 if (!DEBUG_INSN_P (insn) || !rtx_referenced_p (reg, insn))
1288 continue;
1289 else
1291 validate_change (insn, &INSN_VAR_LOCATION_LOC (insn),
1292 gen_rtx_UNKNOWN_VAR_LOC (), 0);
1293 if (!--debug_uses)
1294 break;
1297 free (body);
1300 /* Determine whether INSN contains an accumulator
1301 which can be expanded into separate copies,
1302 one for each copy of the LOOP body.
1304 for (i = 0 ; i < n; i++)
1305 sum += a[i];
1309 sum += a[i]
1310 ....
1311 i = i+1;
1312 sum1 += a[i]
1313 ....
1314 i = i+1
1315 sum2 += a[i];
1316 ....
1318 Return NULL if INSN contains no opportunity for expansion of accumulator.
1319 Otherwise, allocate a VAR_TO_EXPAND structure, fill it with the relevant
1320 information and return a pointer to it.
1323 static struct var_to_expand *
1324 analyze_insn_to_expand_var (struct loop *loop, rtx_insn *insn)
1326 rtx set, dest, src;
1327 struct var_to_expand *ves;
1328 unsigned accum_pos;
1329 enum rtx_code code;
1330 int debug_uses = 0;
1332 set = single_set (insn);
1333 if (!set)
1334 return NULL;
1336 dest = SET_DEST (set);
1337 src = SET_SRC (set);
1338 code = GET_CODE (src);
1340 if (code != PLUS && code != MINUS && code != MULT && code != FMA)
1341 return NULL;
1343 if (FLOAT_MODE_P (GET_MODE (dest)))
1345 if (!flag_associative_math)
1346 return NULL;
1347 /* In the case of FMA, we're also changing the rounding. */
1348 if (code == FMA && !flag_unsafe_math_optimizations)
1349 return NULL;
1352 /* Hmm, this is a bit paradoxical. We know that INSN is a valid insn
1353 in MD. But if there is no optab to generate the insn, we can not
1354 perform the variable expansion. This can happen if an MD provides
1355 an insn but not a named pattern to generate it, for example to avoid
1356 producing code that needs additional mode switches like for x87/mmx.
1358 So we check have_insn_for which looks for an optab for the operation
1359 in SRC. If it doesn't exist, we can't perform the expansion even
1360 though INSN is valid. */
1361 if (!have_insn_for (code, GET_MODE (src)))
1362 return NULL;
1364 if (!REG_P (dest)
1365 && !(GET_CODE (dest) == SUBREG
1366 && REG_P (SUBREG_REG (dest))))
1367 return NULL;
1369 /* Find the accumulator use within the operation. */
1370 if (code == FMA)
1372 /* We only support accumulation via FMA in the ADD position. */
1373 if (!rtx_equal_p (dest, XEXP (src, 2)))
1374 return NULL;
1375 accum_pos = 2;
1377 else if (rtx_equal_p (dest, XEXP (src, 0)))
1378 accum_pos = 0;
1379 else if (rtx_equal_p (dest, XEXP (src, 1)))
1381 /* The method of expansion that we are using; which includes the
1382 initialization of the expansions with zero and the summation of
1383 the expansions at the end of the computation will yield wrong
1384 results for (x = something - x) thus avoid using it in that case. */
1385 if (code == MINUS)
1386 return NULL;
1387 accum_pos = 1;
1389 else
1390 return NULL;
1392 /* It must not otherwise be used. */
1393 if (code == FMA)
1395 if (rtx_referenced_p (dest, XEXP (src, 0))
1396 || rtx_referenced_p (dest, XEXP (src, 1)))
1397 return NULL;
1399 else if (rtx_referenced_p (dest, XEXP (src, 1 - accum_pos)))
1400 return NULL;
1402 /* It must be used in exactly one insn. */
1403 if (!referenced_in_one_insn_in_loop_p (loop, dest, &debug_uses))
1404 return NULL;
1406 if (dump_file)
1408 fprintf (dump_file, "\n;; Expanding Accumulator ");
1409 print_rtl (dump_file, dest);
1410 fprintf (dump_file, "\n");
1413 if (debug_uses)
1414 /* Instead of resetting the debug insns, we could replace each
1415 debug use in the loop with the sum or product of all expanded
1416 accummulators. Since we'll only know of all expansions at the
1417 end, we'd have to keep track of which vars_to_expand a debug
1418 insn in the loop references, take note of each copy of the
1419 debug insn during unrolling, and when it's all done, compute
1420 the sum or product of each variable and adjust the original
1421 debug insn and each copy thereof. What a pain! */
1422 reset_debug_uses_in_loop (loop, dest, debug_uses);
1424 /* Record the accumulator to expand. */
1425 ves = XNEW (struct var_to_expand);
1426 ves->insn = insn;
1427 ves->reg = copy_rtx (dest);
1428 ves->var_expansions.create (1);
1429 ves->next = NULL;
1430 ves->op = GET_CODE (src);
1431 ves->expansion_count = 0;
1432 ves->reuse_expansion = 0;
1433 return ves;
1436 /* Determine whether there is an induction variable in INSN that
1437 we would like to split during unrolling.
1439 I.e. replace
1441 i = i + 1;
1443 i = i + 1;
1445 i = i + 1;
1448 type chains by
1450 i0 = i + 1
1452 i = i0 + 1
1454 i = i0 + 2
1457 Return NULL if INSN contains no interesting IVs. Otherwise, allocate
1458 an IV_TO_SPLIT structure, fill it with the relevant information and return a
1459 pointer to it. */
1461 static struct iv_to_split *
1462 analyze_iv_to_split_insn (rtx_insn *insn)
1464 rtx set, dest;
1465 struct rtx_iv iv;
1466 struct iv_to_split *ivts;
1467 bool ok;
1469 /* For now we just split the basic induction variables. Later this may be
1470 extended for example by selecting also addresses of memory references. */
1471 set = single_set (insn);
1472 if (!set)
1473 return NULL;
1475 dest = SET_DEST (set);
1476 if (!REG_P (dest))
1477 return NULL;
1479 if (!biv_p (insn, dest))
1480 return NULL;
1482 ok = iv_analyze_result (insn, dest, &iv);
1484 /* This used to be an assert under the assumption that if biv_p returns
1485 true that iv_analyze_result must also return true. However, that
1486 assumption is not strictly correct as evidenced by pr25569.
1488 Returning NULL when iv_analyze_result returns false is safe and
1489 avoids the problems in pr25569 until the iv_analyze_* routines
1490 can be fixed, which is apparently hard and time consuming
1491 according to their author. */
1492 if (! ok)
1493 return NULL;
1495 if (iv.step == const0_rtx
1496 || iv.mode != iv.extend_mode)
1497 return NULL;
1499 /* Record the insn to split. */
1500 ivts = XNEW (struct iv_to_split);
1501 ivts->insn = insn;
1502 ivts->orig_var = dest;
1503 ivts->base_var = NULL_RTX;
1504 ivts->step = iv.step;
1505 ivts->next = NULL;
1507 return ivts;
1510 /* Determines which of insns in LOOP can be optimized.
1511 Return a OPT_INFO struct with the relevant hash tables filled
1512 with all insns to be optimized. The FIRST_NEW_BLOCK field
1513 is undefined for the return value. */
1515 static struct opt_info *
1516 analyze_insns_in_loop (struct loop *loop)
1518 basic_block *body, bb;
1519 unsigned i;
1520 struct opt_info *opt_info = XCNEW (struct opt_info);
1521 rtx_insn *insn;
1522 struct iv_to_split *ivts = NULL;
1523 struct var_to_expand *ves = NULL;
1524 iv_to_split **slot1;
1525 var_to_expand **slot2;
1526 vec<edge> edges = get_loop_exit_edges (loop);
1527 edge exit;
1528 bool can_apply = false;
1530 iv_analysis_loop_init (loop);
1532 body = get_loop_body (loop);
1534 if (flag_split_ivs_in_unroller)
1536 opt_info->insns_to_split
1537 = new hash_table<iv_split_hasher> (5 * loop->num_nodes);
1538 opt_info->iv_to_split_head = NULL;
1539 opt_info->iv_to_split_tail = &opt_info->iv_to_split_head;
1542 /* Record the loop exit bb and loop preheader before the unrolling. */
1543 opt_info->loop_preheader = loop_preheader_edge (loop)->src;
1545 if (edges.length () == 1)
1547 exit = edges[0];
1548 if (!(exit->flags & EDGE_COMPLEX))
1550 opt_info->loop_exit = split_edge (exit);
1551 can_apply = true;
1555 if (flag_variable_expansion_in_unroller
1556 && can_apply)
1558 opt_info->insns_with_var_to_expand
1559 = new hash_table<var_expand_hasher> (5 * loop->num_nodes);
1560 opt_info->var_to_expand_head = NULL;
1561 opt_info->var_to_expand_tail = &opt_info->var_to_expand_head;
1564 for (i = 0; i < loop->num_nodes; i++)
1566 bb = body[i];
1567 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1568 continue;
1570 FOR_BB_INSNS (bb, insn)
1572 if (!INSN_P (insn))
1573 continue;
1575 if (opt_info->insns_to_split)
1576 ivts = analyze_iv_to_split_insn (insn);
1578 if (ivts)
1580 slot1 = opt_info->insns_to_split->find_slot (ivts, INSERT);
1581 gcc_assert (*slot1 == NULL);
1582 *slot1 = ivts;
1583 *opt_info->iv_to_split_tail = ivts;
1584 opt_info->iv_to_split_tail = &ivts->next;
1585 continue;
1588 if (opt_info->insns_with_var_to_expand)
1589 ves = analyze_insn_to_expand_var (loop, insn);
1591 if (ves)
1593 slot2 = opt_info->insns_with_var_to_expand->find_slot (ves, INSERT);
1594 gcc_assert (*slot2 == NULL);
1595 *slot2 = ves;
1596 *opt_info->var_to_expand_tail = ves;
1597 opt_info->var_to_expand_tail = &ves->next;
1602 edges.release ();
1603 free (body);
1604 return opt_info;
1607 /* Called just before loop duplication. Records start of duplicated area
1608 to OPT_INFO. */
1610 static void
1611 opt_info_start_duplication (struct opt_info *opt_info)
1613 if (opt_info)
1614 opt_info->first_new_block = last_basic_block_for_fn (cfun);
1617 /* Determine the number of iterations between initialization of the base
1618 variable and the current copy (N_COPY). N_COPIES is the total number
1619 of newly created copies. UNROLLING is true if we are unrolling
1620 (not peeling) the loop. */
1622 static unsigned
1623 determine_split_iv_delta (unsigned n_copy, unsigned n_copies, bool unrolling)
1625 if (unrolling)
1627 /* If we are unrolling, initialization is done in the original loop
1628 body (number 0). */
1629 return n_copy;
1631 else
1633 /* If we are peeling, the copy in that the initialization occurs has
1634 number 1. The original loop (number 0) is the last. */
1635 if (n_copy)
1636 return n_copy - 1;
1637 else
1638 return n_copies;
1642 /* Allocate basic variable for the induction variable chain. */
1644 static void
1645 allocate_basic_variable (struct iv_to_split *ivts)
1647 rtx expr = SET_SRC (single_set (ivts->insn));
1649 ivts->base_var = gen_reg_rtx (GET_MODE (expr));
1652 /* Insert initialization of basic variable of IVTS before INSN, taking
1653 the initial value from INSN. */
1655 static void
1656 insert_base_initialization (struct iv_to_split *ivts, rtx_insn *insn)
1658 rtx expr = copy_rtx (SET_SRC (single_set (insn)));
1659 rtx_insn *seq;
1661 start_sequence ();
1662 expr = force_operand (expr, ivts->base_var);
1663 if (expr != ivts->base_var)
1664 emit_move_insn (ivts->base_var, expr);
1665 seq = get_insns ();
1666 end_sequence ();
1668 emit_insn_before (seq, insn);
1671 /* Replace the use of induction variable described in IVTS in INSN
1672 by base variable + DELTA * step. */
1674 static void
1675 split_iv (struct iv_to_split *ivts, rtx_insn *insn, unsigned delta)
1677 rtx expr, *loc, incr, var;
1678 rtx_insn *seq;
1679 machine_mode mode = GET_MODE (ivts->base_var);
1680 rtx src, dest, set;
1682 /* Construct base + DELTA * step. */
1683 if (!delta)
1684 expr = ivts->base_var;
1685 else
1687 incr = simplify_gen_binary (MULT, mode,
1688 ivts->step, gen_int_mode (delta, mode));
1689 expr = simplify_gen_binary (PLUS, GET_MODE (ivts->base_var),
1690 ivts->base_var, incr);
1693 /* Figure out where to do the replacement. */
1694 loc = &SET_SRC (single_set (insn));
1696 /* If we can make the replacement right away, we're done. */
1697 if (validate_change (insn, loc, expr, 0))
1698 return;
1700 /* Otherwise, force EXPR into a register and try again. */
1701 start_sequence ();
1702 var = gen_reg_rtx (mode);
1703 expr = force_operand (expr, var);
1704 if (expr != var)
1705 emit_move_insn (var, expr);
1706 seq = get_insns ();
1707 end_sequence ();
1708 emit_insn_before (seq, insn);
1710 if (validate_change (insn, loc, var, 0))
1711 return;
1713 /* The last chance. Try recreating the assignment in insn
1714 completely from scratch. */
1715 set = single_set (insn);
1716 gcc_assert (set);
1718 start_sequence ();
1719 *loc = var;
1720 src = copy_rtx (SET_SRC (set));
1721 dest = copy_rtx (SET_DEST (set));
1722 src = force_operand (src, dest);
1723 if (src != dest)
1724 emit_move_insn (dest, src);
1725 seq = get_insns ();
1726 end_sequence ();
1728 emit_insn_before (seq, insn);
1729 delete_insn (insn);
1733 /* Return one expansion of the accumulator recorded in struct VE. */
1735 static rtx
1736 get_expansion (struct var_to_expand *ve)
1738 rtx reg;
1740 if (ve->reuse_expansion == 0)
1741 reg = ve->reg;
1742 else
1743 reg = ve->var_expansions[ve->reuse_expansion - 1];
1745 if (ve->var_expansions.length () == (unsigned) ve->reuse_expansion)
1746 ve->reuse_expansion = 0;
1747 else
1748 ve->reuse_expansion++;
1750 return reg;
1754 /* Given INSN replace the uses of the accumulator recorded in VE
1755 with a new register. */
1757 static void
1758 expand_var_during_unrolling (struct var_to_expand *ve, rtx_insn *insn)
1760 rtx new_reg, set;
1761 bool really_new_expansion = false;
1763 set = single_set (insn);
1764 gcc_assert (set);
1766 /* Generate a new register only if the expansion limit has not been
1767 reached. Else reuse an already existing expansion. */
1768 if (PARAM_VALUE (PARAM_MAX_VARIABLE_EXPANSIONS) > ve->expansion_count)
1770 really_new_expansion = true;
1771 new_reg = gen_reg_rtx (GET_MODE (ve->reg));
1773 else
1774 new_reg = get_expansion (ve);
1776 validate_replace_rtx_group (SET_DEST (set), new_reg, insn);
1777 if (apply_change_group ())
1778 if (really_new_expansion)
1780 ve->var_expansions.safe_push (new_reg);
1781 ve->expansion_count++;
1785 /* Initialize the variable expansions in loop preheader. PLACE is the
1786 loop-preheader basic block where the initialization of the
1787 expansions should take place. The expansions are initialized with
1788 (-0) when the operation is plus or minus to honor sign zero. This
1789 way we can prevent cases where the sign of the final result is
1790 effected by the sign of the expansion. Here is an example to
1791 demonstrate this:
1793 for (i = 0 ; i < n; i++)
1794 sum += something;
1798 sum += something
1799 ....
1800 i = i+1;
1801 sum1 += something
1802 ....
1803 i = i+1
1804 sum2 += something;
1805 ....
1807 When SUM is initialized with -zero and SOMETHING is also -zero; the
1808 final result of sum should be -zero thus the expansions sum1 and sum2
1809 should be initialized with -zero as well (otherwise we will get +zero
1810 as the final result). */
1812 static void
1813 insert_var_expansion_initialization (struct var_to_expand *ve,
1814 basic_block place)
1816 rtx_insn *seq;
1817 rtx var, zero_init;
1818 unsigned i;
1819 machine_mode mode = GET_MODE (ve->reg);
1820 bool honor_signed_zero_p = HONOR_SIGNED_ZEROS (mode);
1822 if (ve->var_expansions.length () == 0)
1823 return;
1825 start_sequence ();
1826 switch (ve->op)
1828 case FMA:
1829 /* Note that we only accumulate FMA via the ADD operand. */
1830 case PLUS:
1831 case MINUS:
1832 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1834 if (honor_signed_zero_p)
1835 zero_init = simplify_gen_unary (NEG, mode, CONST0_RTX (mode), mode);
1836 else
1837 zero_init = CONST0_RTX (mode);
1838 emit_move_insn (var, zero_init);
1840 break;
1842 case MULT:
1843 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1845 zero_init = CONST1_RTX (GET_MODE (var));
1846 emit_move_insn (var, zero_init);
1848 break;
1850 default:
1851 gcc_unreachable ();
1854 seq = get_insns ();
1855 end_sequence ();
1857 emit_insn_after (seq, BB_END (place));
1860 /* Combine the variable expansions at the loop exit. PLACE is the
1861 loop exit basic block where the summation of the expansions should
1862 take place. */
1864 static void
1865 combine_var_copies_in_loop_exit (struct var_to_expand *ve, basic_block place)
1867 rtx sum = ve->reg;
1868 rtx expr, var;
1869 rtx_insn *seq, *insn;
1870 unsigned i;
1872 if (ve->var_expansions.length () == 0)
1873 return;
1875 start_sequence ();
1876 switch (ve->op)
1878 case FMA:
1879 /* Note that we only accumulate FMA via the ADD operand. */
1880 case PLUS:
1881 case MINUS:
1882 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1883 sum = simplify_gen_binary (PLUS, GET_MODE (ve->reg), var, sum);
1884 break;
1886 case MULT:
1887 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1888 sum = simplify_gen_binary (MULT, GET_MODE (ve->reg), var, sum);
1889 break;
1891 default:
1892 gcc_unreachable ();
1895 expr = force_operand (sum, ve->reg);
1896 if (expr != ve->reg)
1897 emit_move_insn (ve->reg, expr);
1898 seq = get_insns ();
1899 end_sequence ();
1901 insn = BB_HEAD (place);
1902 while (!NOTE_INSN_BASIC_BLOCK_P (insn))
1903 insn = NEXT_INSN (insn);
1905 emit_insn_after (seq, insn);
1908 /* Strip away REG_EQUAL notes for IVs we're splitting.
1910 Updating REG_EQUAL notes for IVs we split is tricky: We
1911 cannot tell until after unrolling, DF-rescanning, and liveness
1912 updating, whether an EQ_USE is reached by the split IV while
1913 the IV reg is still live. See PR55006.
1915 ??? We cannot use remove_reg_equal_equiv_notes_for_regno,
1916 because RTL loop-iv requires us to defer rescanning insns and
1917 any notes attached to them. So resort to old techniques... */
1919 static void
1920 maybe_strip_eq_note_for_split_iv (struct opt_info *opt_info, rtx_insn *insn)
1922 struct iv_to_split *ivts;
1923 rtx note = find_reg_equal_equiv_note (insn);
1924 if (! note)
1925 return;
1926 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1927 if (reg_mentioned_p (ivts->orig_var, note))
1929 remove_note (insn, note);
1930 return;
1934 /* Apply loop optimizations in loop copies using the
1935 data which gathered during the unrolling. Structure
1936 OPT_INFO record that data.
1938 UNROLLING is true if we unrolled (not peeled) the loop.
1939 REWRITE_ORIGINAL_BODY is true if we should also rewrite the original body of
1940 the loop (as it should happen in complete unrolling, but not in ordinary
1941 peeling of the loop). */
1943 static void
1944 apply_opt_in_copies (struct opt_info *opt_info,
1945 unsigned n_copies, bool unrolling,
1946 bool rewrite_original_loop)
1948 unsigned i, delta;
1949 basic_block bb, orig_bb;
1950 rtx_insn *insn, *orig_insn, *next;
1951 struct iv_to_split ivts_templ, *ivts;
1952 struct var_to_expand ve_templ, *ves;
1954 /* Sanity check -- we need to put initialization in the original loop
1955 body. */
1956 gcc_assert (!unrolling || rewrite_original_loop);
1958 /* Allocate the basic variables (i0). */
1959 if (opt_info->insns_to_split)
1960 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1961 allocate_basic_variable (ivts);
1963 for (i = opt_info->first_new_block;
1964 i < (unsigned) last_basic_block_for_fn (cfun);
1965 i++)
1967 bb = BASIC_BLOCK_FOR_FN (cfun, i);
1968 orig_bb = get_bb_original (bb);
1970 /* bb->aux holds position in copy sequence initialized by
1971 duplicate_loop_to_header_edge. */
1972 delta = determine_split_iv_delta ((size_t)bb->aux, n_copies,
1973 unrolling);
1974 bb->aux = 0;
1975 orig_insn = BB_HEAD (orig_bb);
1976 FOR_BB_INSNS_SAFE (bb, insn, next)
1978 if (!INSN_P (insn)
1979 || (DEBUG_INSN_P (insn)
1980 && TREE_CODE (INSN_VAR_LOCATION_DECL (insn)) == LABEL_DECL))
1981 continue;
1983 while (!INSN_P (orig_insn)
1984 || (DEBUG_INSN_P (orig_insn)
1985 && (TREE_CODE (INSN_VAR_LOCATION_DECL (orig_insn))
1986 == LABEL_DECL)))
1987 orig_insn = NEXT_INSN (orig_insn);
1989 ivts_templ.insn = orig_insn;
1990 ve_templ.insn = orig_insn;
1992 /* Apply splitting iv optimization. */
1993 if (opt_info->insns_to_split)
1995 maybe_strip_eq_note_for_split_iv (opt_info, insn);
1997 ivts = opt_info->insns_to_split->find (&ivts_templ);
1999 if (ivts)
2001 gcc_assert (GET_CODE (PATTERN (insn))
2002 == GET_CODE (PATTERN (orig_insn)));
2004 if (!delta)
2005 insert_base_initialization (ivts, insn);
2006 split_iv (ivts, insn, delta);
2009 /* Apply variable expansion optimization. */
2010 if (unrolling && opt_info->insns_with_var_to_expand)
2012 ves = (struct var_to_expand *)
2013 opt_info->insns_with_var_to_expand->find (&ve_templ);
2014 if (ves)
2016 gcc_assert (GET_CODE (PATTERN (insn))
2017 == GET_CODE (PATTERN (orig_insn)));
2018 expand_var_during_unrolling (ves, insn);
2021 orig_insn = NEXT_INSN (orig_insn);
2025 if (!rewrite_original_loop)
2026 return;
2028 /* Initialize the variable expansions in the loop preheader
2029 and take care of combining them at the loop exit. */
2030 if (opt_info->insns_with_var_to_expand)
2032 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2033 insert_var_expansion_initialization (ves, opt_info->loop_preheader);
2034 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2035 combine_var_copies_in_loop_exit (ves, opt_info->loop_exit);
2038 /* Rewrite also the original loop body. Find them as originals of the blocks
2039 in the last copied iteration, i.e. those that have
2040 get_bb_copy (get_bb_original (bb)) == bb. */
2041 for (i = opt_info->first_new_block;
2042 i < (unsigned) last_basic_block_for_fn (cfun);
2043 i++)
2045 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2046 orig_bb = get_bb_original (bb);
2047 if (get_bb_copy (orig_bb) != bb)
2048 continue;
2050 delta = determine_split_iv_delta (0, n_copies, unrolling);
2051 for (orig_insn = BB_HEAD (orig_bb);
2052 orig_insn != NEXT_INSN (BB_END (bb));
2053 orig_insn = next)
2055 next = NEXT_INSN (orig_insn);
2057 if (!INSN_P (orig_insn))
2058 continue;
2060 ivts_templ.insn = orig_insn;
2061 if (opt_info->insns_to_split)
2063 maybe_strip_eq_note_for_split_iv (opt_info, orig_insn);
2065 ivts = (struct iv_to_split *)
2066 opt_info->insns_to_split->find (&ivts_templ);
2067 if (ivts)
2069 if (!delta)
2070 insert_base_initialization (ivts, orig_insn);
2071 split_iv (ivts, orig_insn, delta);
2072 continue;
2080 /* Release OPT_INFO. */
2082 static void
2083 free_opt_info (struct opt_info *opt_info)
2085 delete opt_info->insns_to_split;
2086 opt_info->insns_to_split = NULL;
2087 if (opt_info->insns_with_var_to_expand)
2089 struct var_to_expand *ves;
2091 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2092 ves->var_expansions.release ();
2093 delete opt_info->insns_with_var_to_expand;
2094 opt_info->insns_with_var_to_expand = NULL;
2096 free (opt_info);