gcc/ChangeLog:
[official-gcc.git] / gcc / loop-unroll.c
blob91bf5dddeeda8d8649a4e154ee1d6a1ffa3a25fd
1 /* Loop unrolling.
2 Copyright (C) 2002-2017 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 "memmodel.h"
29 #include "optabs.h"
30 #include "emit-rtl.h"
31 #include "recog.h"
32 #include "profile.h"
33 #include "cfgrtl.h"
34 #include "cfgloop.h"
35 #include "params.h"
36 #include "dojump.h"
37 #include "expr.h"
38 #include "dumpfile.h"
40 /* This pass performs loop unrolling. We only perform this
41 optimization on innermost loops (with single exception) because
42 the impact on performance is greatest here, and we want to avoid
43 unnecessary code size growth. The gain is caused by greater sequentiality
44 of code, better code to optimize for further passes and in some cases
45 by fewer testings of exit conditions. The main problem is code growth,
46 that impacts performance negatively due to effect of caches.
48 What we do:
50 -- unrolling of loops that roll constant times; this is almost always
51 win, as we get rid of exit condition tests.
52 -- unrolling of loops that roll number of times that we can compute
53 in runtime; we also get rid of exit condition tests here, but there
54 is the extra expense for calculating the number of iterations
55 -- simple unrolling of remaining loops; this is performed only if we
56 are asked to, as the gain is questionable in this case and often
57 it may even slow down the code
58 For more detailed descriptions of each of those, see comments at
59 appropriate function below.
61 There is a lot of parameters (defined and described in params.def) that
62 control how much we unroll.
64 ??? A great problem is that we don't have a good way how to determine
65 how many times we should unroll the loop; the experiments I have made
66 showed that this choice may affect performance in order of several %.
69 /* Information about induction variables to split. */
71 struct iv_to_split
73 rtx_insn *insn; /* The insn in that the induction variable occurs. */
74 rtx orig_var; /* The variable (register) for the IV before split. */
75 rtx base_var; /* The variable on that the values in the further
76 iterations are based. */
77 rtx step; /* Step of the induction variable. */
78 struct iv_to_split *next; /* Next entry in walking order. */
81 /* Information about accumulators to expand. */
83 struct var_to_expand
85 rtx_insn *insn; /* The insn in that the variable expansion occurs. */
86 rtx reg; /* The accumulator which is expanded. */
87 vec<rtx> var_expansions; /* The copies of the accumulator which is expanded. */
88 struct var_to_expand *next; /* Next entry in walking order. */
89 enum rtx_code op; /* The type of the accumulation - addition, subtraction
90 or multiplication. */
91 int expansion_count; /* Count the number of expansions generated so far. */
92 int reuse_expansion; /* The expansion we intend to reuse to expand
93 the accumulator. If REUSE_EXPANSION is 0 reuse
94 the original accumulator. Else use
95 var_expansions[REUSE_EXPANSION - 1]. */
98 /* Hashtable helper for iv_to_split. */
100 struct iv_split_hasher : free_ptr_hash <iv_to_split>
102 static inline hashval_t hash (const iv_to_split *);
103 static inline bool equal (const iv_to_split *, const iv_to_split *);
107 /* A hash function for information about insns to split. */
109 inline hashval_t
110 iv_split_hasher::hash (const iv_to_split *ivts)
112 return (hashval_t) INSN_UID (ivts->insn);
115 /* An equality functions for information about insns to split. */
117 inline bool
118 iv_split_hasher::equal (const iv_to_split *i1, const iv_to_split *i2)
120 return i1->insn == i2->insn;
123 /* Hashtable helper for iv_to_split. */
125 struct var_expand_hasher : free_ptr_hash <var_to_expand>
127 static inline hashval_t hash (const var_to_expand *);
128 static inline bool equal (const var_to_expand *, const var_to_expand *);
131 /* Return a hash for VES. */
133 inline hashval_t
134 var_expand_hasher::hash (const var_to_expand *ves)
136 return (hashval_t) INSN_UID (ves->insn);
139 /* Return true if I1 and I2 refer to the same instruction. */
141 inline bool
142 var_expand_hasher::equal (const var_to_expand *i1, const var_to_expand *i2)
144 return i1->insn == i2->insn;
147 /* Information about optimization applied in
148 the unrolled loop. */
150 struct opt_info
152 hash_table<iv_split_hasher> *insns_to_split; /* A hashtable of insns to
153 split. */
154 struct iv_to_split *iv_to_split_head; /* The first iv to split. */
155 struct iv_to_split **iv_to_split_tail; /* Pointer to the tail of the list. */
156 hash_table<var_expand_hasher> *insns_with_var_to_expand; /* A hashtable of
157 insns with accumulators to expand. */
158 struct var_to_expand *var_to_expand_head; /* The first var to expand. */
159 struct var_to_expand **var_to_expand_tail; /* Pointer to the tail of the list. */
160 unsigned first_new_block; /* The first basic block that was
161 duplicated. */
162 basic_block loop_exit; /* The loop exit basic block. */
163 basic_block loop_preheader; /* The loop preheader basic block. */
166 static void decide_unroll_stupid (struct loop *, int);
167 static void decide_unroll_constant_iterations (struct loop *, int);
168 static void decide_unroll_runtime_iterations (struct loop *, int);
169 static void unroll_loop_stupid (struct loop *);
170 static void decide_unrolling (int);
171 static void unroll_loop_constant_iterations (struct loop *);
172 static void unroll_loop_runtime_iterations (struct loop *);
173 static struct opt_info *analyze_insns_in_loop (struct loop *);
174 static void opt_info_start_duplication (struct opt_info *);
175 static void apply_opt_in_copies (struct opt_info *, unsigned, bool, bool);
176 static void free_opt_info (struct opt_info *);
177 static struct var_to_expand *analyze_insn_to_expand_var (struct loop*, rtx_insn *);
178 static bool referenced_in_one_insn_in_loop_p (struct loop *, rtx, int *);
179 static struct iv_to_split *analyze_iv_to_split_insn (rtx_insn *);
180 static void expand_var_during_unrolling (struct var_to_expand *, rtx_insn *);
181 static void insert_var_expansion_initialization (struct var_to_expand *,
182 basic_block);
183 static void combine_var_copies_in_loop_exit (struct var_to_expand *,
184 basic_block);
185 static rtx get_expansion (struct var_to_expand *);
187 /* Emit a message summarizing the unroll that will be
188 performed for LOOP, along with the loop's location LOCUS, if
189 appropriate given the dump or -fopt-info settings. */
191 static void
192 report_unroll (struct loop *loop, location_t locus)
194 dump_flags_t report_flags = MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS;
196 if (loop->lpt_decision.decision == LPT_NONE)
197 return;
199 if (!dump_enabled_p ())
200 return;
202 dump_printf_loc (report_flags, locus,
203 "loop unrolled %d times",
204 loop->lpt_decision.times);
205 if (profile_info && loop->header->count.initialized_p ())
206 dump_printf (report_flags,
207 " (header execution count %d)",
208 (int)loop->header->count.to_gcov_type ());
210 dump_printf (report_flags, "\n");
213 /* Decide whether unroll loops and how much. */
214 static void
215 decide_unrolling (int flags)
217 struct loop *loop;
219 /* Scan the loops, inner ones first. */
220 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
222 loop->lpt_decision.decision = LPT_NONE;
223 location_t locus = get_loop_location (loop);
225 if (dump_enabled_p ())
226 dump_printf_loc (MSG_NOTE, locus,
227 ";; *** Considering loop %d at BB %d for "
228 "unrolling ***\n",
229 loop->num, loop->header->index);
231 /* Do not peel cold areas. */
232 if (optimize_loop_for_size_p (loop))
234 if (dump_file)
235 fprintf (dump_file, ";; Not considering loop, cold area\n");
236 continue;
239 /* Can the loop be manipulated? */
240 if (!can_duplicate_loop_p (loop))
242 if (dump_file)
243 fprintf (dump_file,
244 ";; Not considering loop, cannot duplicate\n");
245 continue;
248 /* Skip non-innermost loops. */
249 if (loop->inner)
251 if (dump_file)
252 fprintf (dump_file, ";; Not considering loop, is not innermost\n");
253 continue;
256 loop->ninsns = num_loop_insns (loop);
257 loop->av_ninsns = average_num_loop_insns (loop);
259 /* Try transformations one by one in decreasing order of
260 priority. */
262 decide_unroll_constant_iterations (loop, flags);
263 if (loop->lpt_decision.decision == LPT_NONE)
264 decide_unroll_runtime_iterations (loop, flags);
265 if (loop->lpt_decision.decision == LPT_NONE)
266 decide_unroll_stupid (loop, flags);
268 report_unroll (loop, locus);
272 /* Unroll LOOPS. */
273 void
274 unroll_loops (int flags)
276 struct loop *loop;
277 bool changed = false;
279 /* Now decide rest of unrolling. */
280 decide_unrolling (flags);
282 /* Scan the loops, inner ones first. */
283 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
285 /* And perform the appropriate transformations. */
286 switch (loop->lpt_decision.decision)
288 case LPT_UNROLL_CONSTANT:
289 unroll_loop_constant_iterations (loop);
290 changed = true;
291 break;
292 case LPT_UNROLL_RUNTIME:
293 unroll_loop_runtime_iterations (loop);
294 changed = true;
295 break;
296 case LPT_UNROLL_STUPID:
297 unroll_loop_stupid (loop);
298 changed = true;
299 break;
300 case LPT_NONE:
301 break;
302 default:
303 gcc_unreachable ();
307 if (changed)
309 calculate_dominance_info (CDI_DOMINATORS);
310 fix_loop_structure (NULL);
313 iv_analysis_done ();
316 /* Check whether exit of the LOOP is at the end of loop body. */
318 static bool
319 loop_exit_at_end_p (struct loop *loop)
321 struct niter_desc *desc = get_simple_loop_desc (loop);
322 rtx_insn *insn;
324 /* We should never have conditional in latch block. */
325 gcc_assert (desc->in_edge->dest != loop->header);
327 if (desc->in_edge->dest != loop->latch)
328 return false;
330 /* Check that the latch is empty. */
331 FOR_BB_INSNS (loop->latch, insn)
333 if (INSN_P (insn) && active_insn_p (insn))
334 return false;
337 return true;
340 /* Decide whether to unroll LOOP iterating constant number of times
341 and how much. */
343 static void
344 decide_unroll_constant_iterations (struct loop *loop, int flags)
346 unsigned nunroll, nunroll_by_av, best_copies, best_unroll = 0, n_copies, i;
347 struct niter_desc *desc;
348 widest_int iterations;
350 if (!(flags & UAP_UNROLL))
352 /* We were not asked to, just return back silently. */
353 return;
356 if (dump_file)
357 fprintf (dump_file,
358 "\n;; Considering unrolling loop with constant "
359 "number of iterations\n");
361 /* nunroll = total number of copies of the original loop body in
362 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
363 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
364 nunroll_by_av
365 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
366 if (nunroll > nunroll_by_av)
367 nunroll = nunroll_by_av;
368 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
369 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
371 if (targetm.loop_unroll_adjust)
372 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
374 /* Skip big loops. */
375 if (nunroll <= 1)
377 if (dump_file)
378 fprintf (dump_file, ";; Not considering loop, is too big\n");
379 return;
382 /* Check for simple loops. */
383 desc = get_simple_loop_desc (loop);
385 /* Check number of iterations. */
386 if (!desc->simple_p || !desc->const_iter || desc->assumptions)
388 if (dump_file)
389 fprintf (dump_file,
390 ";; Unable to prove that the loop iterates constant times\n");
391 return;
394 /* Check whether the loop rolls enough to consider.
395 Consult also loop bounds and profile; in the case the loop has more
396 than one exit it may well loop less than determined maximal number
397 of iterations. */
398 if (desc->niter < 2 * nunroll
399 || ((get_estimated_loop_iterations (loop, &iterations)
400 || get_likely_max_loop_iterations (loop, &iterations))
401 && wi::ltu_p (iterations, 2 * nunroll)))
403 if (dump_file)
404 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
405 return;
408 /* Success; now compute number of iterations to unroll. We alter
409 nunroll so that as few as possible copies of loop body are
410 necessary, while still not decreasing the number of unrollings
411 too much (at most by 1). */
412 best_copies = 2 * nunroll + 10;
414 i = 2 * nunroll + 2;
415 if (i - 1 >= desc->niter)
416 i = desc->niter - 2;
418 for (; i >= nunroll - 1; i--)
420 unsigned exit_mod = desc->niter % (i + 1);
422 if (!loop_exit_at_end_p (loop))
423 n_copies = exit_mod + i + 1;
424 else if (exit_mod != (unsigned) i
425 || desc->noloop_assumptions != NULL_RTX)
426 n_copies = exit_mod + i + 2;
427 else
428 n_copies = i + 1;
430 if (n_copies < best_copies)
432 best_copies = n_copies;
433 best_unroll = i;
437 loop->lpt_decision.decision = LPT_UNROLL_CONSTANT;
438 loop->lpt_decision.times = best_unroll;
441 /* Unroll LOOP with constant number of iterations LOOP->LPT_DECISION.TIMES times.
442 The transformation does this:
444 for (i = 0; i < 102; i++)
445 body;
447 ==> (LOOP->LPT_DECISION.TIMES == 3)
449 i = 0;
450 body; i++;
451 body; i++;
452 while (i < 102)
454 body; i++;
455 body; i++;
456 body; i++;
457 body; i++;
460 static void
461 unroll_loop_constant_iterations (struct loop *loop)
463 unsigned HOST_WIDE_INT niter;
464 unsigned exit_mod;
465 unsigned i;
466 edge e;
467 unsigned max_unroll = loop->lpt_decision.times;
468 struct niter_desc *desc = get_simple_loop_desc (loop);
469 bool exit_at_end = loop_exit_at_end_p (loop);
470 struct opt_info *opt_info = NULL;
471 bool ok;
473 niter = desc->niter;
475 /* Should not get here (such loop should be peeled instead). */
476 gcc_assert (niter > max_unroll + 1);
478 exit_mod = niter % (max_unroll + 1);
480 auto_sbitmap wont_exit (max_unroll + 1);
481 bitmap_ones (wont_exit);
483 auto_vec<edge> remove_edges;
484 if (flag_split_ivs_in_unroller
485 || flag_variable_expansion_in_unroller)
486 opt_info = analyze_insns_in_loop (loop);
488 if (!exit_at_end)
490 /* The exit is not at the end of the loop; leave exit test
491 in the first copy, so that the loops that start with test
492 of exit condition have continuous body after unrolling. */
494 if (dump_file)
495 fprintf (dump_file, ";; Condition at beginning of loop.\n");
497 /* Peel exit_mod iterations. */
498 bitmap_clear_bit (wont_exit, 0);
499 if (desc->noloop_assumptions)
500 bitmap_clear_bit (wont_exit, 1);
502 if (exit_mod)
504 opt_info_start_duplication (opt_info);
505 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
506 exit_mod,
507 wont_exit, desc->out_edge,
508 &remove_edges,
509 DLTHE_FLAG_UPDATE_FREQ
510 | (opt_info && exit_mod > 1
511 ? DLTHE_RECORD_COPY_NUMBER
512 : 0));
513 gcc_assert (ok);
515 if (opt_info && exit_mod > 1)
516 apply_opt_in_copies (opt_info, exit_mod, false, false);
518 desc->noloop_assumptions = NULL_RTX;
519 desc->niter -= exit_mod;
520 loop->nb_iterations_upper_bound -= exit_mod;
521 if (loop->any_estimate
522 && wi::leu_p (exit_mod, loop->nb_iterations_estimate))
523 loop->nb_iterations_estimate -= exit_mod;
524 else
525 loop->any_estimate = false;
526 if (loop->any_likely_upper_bound
527 && wi::leu_p (exit_mod, loop->nb_iterations_likely_upper_bound))
528 loop->nb_iterations_likely_upper_bound -= exit_mod;
529 else
530 loop->any_likely_upper_bound = false;
533 bitmap_set_bit (wont_exit, 1);
535 else
537 /* Leave exit test in last copy, for the same reason as above if
538 the loop tests the condition at the end of loop body. */
540 if (dump_file)
541 fprintf (dump_file, ";; Condition at end of loop.\n");
543 /* We know that niter >= max_unroll + 2; so we do not need to care of
544 case when we would exit before reaching the loop. So just peel
545 exit_mod + 1 iterations. */
546 if (exit_mod != max_unroll
547 || desc->noloop_assumptions)
549 bitmap_clear_bit (wont_exit, 0);
550 if (desc->noloop_assumptions)
551 bitmap_clear_bit (wont_exit, 1);
553 opt_info_start_duplication (opt_info);
554 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
555 exit_mod + 1,
556 wont_exit, desc->out_edge,
557 &remove_edges,
558 DLTHE_FLAG_UPDATE_FREQ
559 | (opt_info && exit_mod > 0
560 ? DLTHE_RECORD_COPY_NUMBER
561 : 0));
562 gcc_assert (ok);
564 if (opt_info && exit_mod > 0)
565 apply_opt_in_copies (opt_info, exit_mod + 1, false, false);
567 desc->niter -= exit_mod + 1;
568 loop->nb_iterations_upper_bound -= exit_mod + 1;
569 if (loop->any_estimate
570 && wi::leu_p (exit_mod + 1, loop->nb_iterations_estimate))
571 loop->nb_iterations_estimate -= exit_mod + 1;
572 else
573 loop->any_estimate = false;
574 if (loop->any_likely_upper_bound
575 && wi::leu_p (exit_mod + 1, loop->nb_iterations_likely_upper_bound))
576 loop->nb_iterations_likely_upper_bound -= exit_mod + 1;
577 else
578 loop->any_likely_upper_bound = false;
579 desc->noloop_assumptions = NULL_RTX;
581 bitmap_set_bit (wont_exit, 0);
582 bitmap_set_bit (wont_exit, 1);
585 bitmap_clear_bit (wont_exit, max_unroll);
588 /* Now unroll the loop. */
590 opt_info_start_duplication (opt_info);
591 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
592 max_unroll,
593 wont_exit, desc->out_edge,
594 &remove_edges,
595 DLTHE_FLAG_UPDATE_FREQ
596 | (opt_info
597 ? DLTHE_RECORD_COPY_NUMBER
598 : 0));
599 gcc_assert (ok);
601 if (opt_info)
603 apply_opt_in_copies (opt_info, max_unroll, true, true);
604 free_opt_info (opt_info);
607 if (exit_at_end)
609 basic_block exit_block = get_bb_copy (desc->in_edge->src);
610 /* Find a new in and out edge; they are in the last copy we have made. */
612 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
614 desc->out_edge = EDGE_SUCC (exit_block, 0);
615 desc->in_edge = EDGE_SUCC (exit_block, 1);
617 else
619 desc->out_edge = EDGE_SUCC (exit_block, 1);
620 desc->in_edge = EDGE_SUCC (exit_block, 0);
624 desc->niter /= max_unroll + 1;
625 loop->nb_iterations_upper_bound
626 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
627 if (loop->any_estimate)
628 loop->nb_iterations_estimate
629 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
630 if (loop->any_likely_upper_bound)
631 loop->nb_iterations_likely_upper_bound
632 = wi::udiv_trunc (loop->nb_iterations_likely_upper_bound, max_unroll + 1);
633 desc->niter_expr = GEN_INT (desc->niter);
635 /* Remove the edges. */
636 FOR_EACH_VEC_ELT (remove_edges, i, e)
637 remove_path (e);
639 if (dump_file)
640 fprintf (dump_file,
641 ";; Unrolled loop %d times, constant # of iterations %i insns\n",
642 max_unroll, num_loop_insns (loop));
645 /* Decide whether to unroll LOOP iterating runtime computable number of times
646 and how much. */
647 static void
648 decide_unroll_runtime_iterations (struct loop *loop, int flags)
650 unsigned nunroll, nunroll_by_av, i;
651 struct niter_desc *desc;
652 widest_int iterations;
654 if (!(flags & UAP_UNROLL))
656 /* We were not asked to, just return back silently. */
657 return;
660 if (dump_file)
661 fprintf (dump_file,
662 "\n;; Considering unrolling loop with runtime "
663 "computable number of iterations\n");
665 /* nunroll = total number of copies of the original loop body in
666 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
667 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
668 nunroll_by_av = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
669 if (nunroll > nunroll_by_av)
670 nunroll = nunroll_by_av;
671 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
672 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
674 if (targetm.loop_unroll_adjust)
675 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
677 /* Skip big loops. */
678 if (nunroll <= 1)
680 if (dump_file)
681 fprintf (dump_file, ";; Not considering loop, is too big\n");
682 return;
685 /* Check for simple loops. */
686 desc = get_simple_loop_desc (loop);
688 /* Check simpleness. */
689 if (!desc->simple_p || desc->assumptions)
691 if (dump_file)
692 fprintf (dump_file,
693 ";; Unable to prove that the number of iterations "
694 "can be counted in runtime\n");
695 return;
698 if (desc->const_iter)
700 if (dump_file)
701 fprintf (dump_file, ";; Loop iterates constant times\n");
702 return;
705 /* Check whether the loop rolls. */
706 if ((get_estimated_loop_iterations (loop, &iterations)
707 || get_likely_max_loop_iterations (loop, &iterations))
708 && wi::ltu_p (iterations, 2 * nunroll))
710 if (dump_file)
711 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
712 return;
715 /* Success; now force nunroll to be power of 2, as we are unable to
716 cope with overflows in computation of number of iterations. */
717 for (i = 1; 2 * i <= nunroll; i *= 2)
718 continue;
720 loop->lpt_decision.decision = LPT_UNROLL_RUNTIME;
721 loop->lpt_decision.times = i - 1;
724 /* Splits edge E and inserts the sequence of instructions INSNS on it, and
725 returns the newly created block. If INSNS is NULL_RTX, nothing is changed
726 and NULL is returned instead. */
728 basic_block
729 split_edge_and_insert (edge e, rtx_insn *insns)
731 basic_block bb;
733 if (!insns)
734 return NULL;
735 bb = split_edge (e);
736 emit_insn_after (insns, BB_END (bb));
738 /* ??? We used to assume that INSNS can contain control flow insns, and
739 that we had to try to find sub basic blocks in BB to maintain a valid
740 CFG. For this purpose we used to set the BB_SUPERBLOCK flag on BB
741 and call break_superblocks when going out of cfglayout mode. But it
742 turns out that this never happens; and that if it does ever happen,
743 the verify_flow_info at the end of the RTL loop passes would fail.
745 There are two reasons why we expected we could have control flow insns
746 in INSNS. The first is when a comparison has to be done in parts, and
747 the second is when the number of iterations is computed for loops with
748 the number of iterations known at runtime. In both cases, test cases
749 to get control flow in INSNS appear to be impossible to construct:
751 * If do_compare_rtx_and_jump needs several branches to do comparison
752 in a mode that needs comparison by parts, we cannot analyze the
753 number of iterations of the loop, and we never get to unrolling it.
755 * The code in expand_divmod that was suspected to cause creation of
756 branching code seems to be only accessed for signed division. The
757 divisions used by # of iterations analysis are always unsigned.
758 Problems might arise on architectures that emits branching code
759 for some operations that may appear in the unroller (especially
760 for division), but we have no such architectures.
762 Considering all this, it was decided that we should for now assume
763 that INSNS can in theory contain control flow insns, but in practice
764 it never does. So we don't handle the theoretical case, and should
765 a real failure ever show up, we have a pretty good clue for how to
766 fix it. */
768 return bb;
771 /* Prepare a sequence comparing OP0 with OP1 using COMP and jumping to LABEL if
772 true, with probability PROB. If CINSN is not NULL, it is the insn to copy
773 in order to create a jump. */
775 static rtx_insn *
776 compare_and_jump_seq (rtx op0, rtx op1, enum rtx_code comp,
777 rtx_code_label *label, profile_probability prob,
778 rtx_insn *cinsn)
780 rtx_insn *seq;
781 rtx_jump_insn *jump;
782 rtx cond;
783 machine_mode mode;
785 mode = GET_MODE (op0);
786 if (mode == VOIDmode)
787 mode = GET_MODE (op1);
789 start_sequence ();
790 if (GET_MODE_CLASS (mode) == MODE_CC)
792 /* A hack -- there seems to be no easy generic way how to make a
793 conditional jump from a ccmode comparison. */
794 gcc_assert (cinsn);
795 cond = XEXP (SET_SRC (pc_set (cinsn)), 0);
796 gcc_assert (GET_CODE (cond) == comp);
797 gcc_assert (rtx_equal_p (op0, XEXP (cond, 0)));
798 gcc_assert (rtx_equal_p (op1, XEXP (cond, 1)));
799 emit_jump_insn (copy_insn (PATTERN (cinsn)));
800 jump = as_a <rtx_jump_insn *> (get_last_insn ());
801 JUMP_LABEL (jump) = JUMP_LABEL (cinsn);
802 LABEL_NUSES (JUMP_LABEL (jump))++;
803 redirect_jump (jump, label, 0);
805 else
807 gcc_assert (!cinsn);
809 op0 = force_operand (op0, NULL_RTX);
810 op1 = force_operand (op1, NULL_RTX);
811 do_compare_rtx_and_jump (op0, op1, comp, 0,
812 mode, NULL_RTX, NULL, label,
813 profile_probability::uninitialized ());
814 jump = as_a <rtx_jump_insn *> (get_last_insn ());
815 jump->set_jump_target (label);
816 LABEL_NUSES (label)++;
818 if (prob.initialized_p ())
819 add_reg_br_prob_note (jump, prob);
821 seq = get_insns ();
822 end_sequence ();
824 return seq;
827 /* Unroll LOOP for which we are able to count number of iterations in runtime
828 LOOP->LPT_DECISION.TIMES times. The transformation does this (with some
829 extra care for case n < 0):
831 for (i = 0; i < n; i++)
832 body;
834 ==> (LOOP->LPT_DECISION.TIMES == 3)
836 i = 0;
837 mod = n % 4;
839 switch (mod)
841 case 3:
842 body; i++;
843 case 2:
844 body; i++;
845 case 1:
846 body; i++;
847 case 0: ;
850 while (i < n)
852 body; i++;
853 body; i++;
854 body; i++;
855 body; i++;
858 static void
859 unroll_loop_runtime_iterations (struct loop *loop)
861 rtx old_niter, niter, tmp;
862 rtx_insn *init_code, *branch_code;
863 unsigned i, j;
864 profile_probability p;
865 basic_block preheader, *body, swtch, ezc_swtch = NULL;
866 int may_exit_copy;
867 profile_count iter_count, new_count;
868 unsigned n_peel;
869 edge e;
870 bool extra_zero_check, last_may_exit;
871 unsigned max_unroll = loop->lpt_decision.times;
872 struct niter_desc *desc = get_simple_loop_desc (loop);
873 bool exit_at_end = loop_exit_at_end_p (loop);
874 struct opt_info *opt_info = NULL;
875 bool ok;
877 if (flag_split_ivs_in_unroller
878 || flag_variable_expansion_in_unroller)
879 opt_info = analyze_insns_in_loop (loop);
881 /* Remember blocks whose dominators will have to be updated. */
882 auto_vec<basic_block> dom_bbs;
884 body = get_loop_body (loop);
885 for (i = 0; i < loop->num_nodes; i++)
887 vec<basic_block> ldom;
888 basic_block bb;
890 ldom = get_dominated_by (CDI_DOMINATORS, body[i]);
891 FOR_EACH_VEC_ELT (ldom, j, bb)
892 if (!flow_bb_inside_loop_p (loop, bb))
893 dom_bbs.safe_push (bb);
895 ldom.release ();
897 free (body);
899 if (!exit_at_end)
901 /* Leave exit in first copy (for explanation why see comment in
902 unroll_loop_constant_iterations). */
903 may_exit_copy = 0;
904 n_peel = max_unroll - 1;
905 extra_zero_check = true;
906 last_may_exit = false;
908 else
910 /* Leave exit in last copy (for explanation why see comment in
911 unroll_loop_constant_iterations). */
912 may_exit_copy = max_unroll;
913 n_peel = max_unroll;
914 extra_zero_check = false;
915 last_may_exit = true;
918 /* Get expression for number of iterations. */
919 start_sequence ();
920 old_niter = niter = gen_reg_rtx (desc->mode);
921 tmp = force_operand (copy_rtx (desc->niter_expr), niter);
922 if (tmp != niter)
923 emit_move_insn (niter, tmp);
925 /* For loops that exit at end and whose number of iterations is reliable,
926 add one to niter to account for first pass through loop body before
927 reaching exit test. */
928 if (exit_at_end && !desc->noloop_assumptions)
930 niter = expand_simple_binop (desc->mode, PLUS,
931 niter, const1_rtx,
932 NULL_RTX, 0, OPTAB_LIB_WIDEN);
933 old_niter = niter;
936 /* Count modulo by ANDing it with max_unroll; we use the fact that
937 the number of unrollings is a power of two, and thus this is correct
938 even if there is overflow in the computation. */
939 niter = expand_simple_binop (desc->mode, AND,
940 niter, gen_int_mode (max_unroll, desc->mode),
941 NULL_RTX, 0, OPTAB_LIB_WIDEN);
943 init_code = get_insns ();
944 end_sequence ();
945 unshare_all_rtl_in_chain (init_code);
947 /* Precondition the loop. */
948 split_edge_and_insert (loop_preheader_edge (loop), init_code);
950 auto_vec<edge> remove_edges;
952 auto_sbitmap wont_exit (max_unroll + 2);
954 if (extra_zero_check || desc->noloop_assumptions)
956 /* Peel the first copy of loop body. Leave the exit test if the number
957 of iterations is not reliable. Also record the place of the extra zero
958 check. */
959 bitmap_clear (wont_exit);
960 if (!desc->noloop_assumptions)
961 bitmap_set_bit (wont_exit, 1);
962 ezc_swtch = loop_preheader_edge (loop)->src;
963 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
964 1, wont_exit, desc->out_edge,
965 &remove_edges,
966 DLTHE_FLAG_UPDATE_FREQ);
967 gcc_assert (ok);
970 /* Record the place where switch will be built for preconditioning. */
971 swtch = split_edge (loop_preheader_edge (loop));
973 /* Compute count increments for each switch block and initialize
974 innermost switch block. Switch blocks and peeled loop copies are built
975 from innermost outward. */
976 iter_count = new_count = swtch->count.apply_scale (1, max_unroll + 1);
977 swtch->count = new_count;
979 for (i = 0; i < n_peel; i++)
981 /* Peel the copy. */
982 bitmap_clear (wont_exit);
983 if (i != n_peel - 1 || !last_may_exit)
984 bitmap_set_bit (wont_exit, 1);
985 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
986 1, wont_exit, desc->out_edge,
987 &remove_edges,
988 DLTHE_FLAG_UPDATE_FREQ);
989 gcc_assert (ok);
991 /* Create item for switch. */
992 j = n_peel - i - (extra_zero_check ? 0 : 1);
993 p = profile_probability::always ().apply_scale (1, i + 2);
995 preheader = split_edge (loop_preheader_edge (loop));
996 /* Add in count of edge from switch block. */
997 preheader->count += iter_count;
998 branch_code = compare_and_jump_seq (copy_rtx (niter), GEN_INT (j), EQ,
999 block_label (preheader), p,
1000 NULL);
1002 /* We rely on the fact that the compare and jump cannot be optimized out,
1003 and hence the cfg we create is correct. */
1004 gcc_assert (branch_code != NULL_RTX);
1006 swtch = split_edge_and_insert (single_pred_edge (swtch), branch_code);
1007 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
1008 single_succ_edge (swtch)->probability = p.invert ();
1009 new_count += iter_count;
1010 swtch->count = new_count;
1011 e = make_edge (swtch, preheader,
1012 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
1013 e->probability = p;
1016 if (extra_zero_check)
1018 /* Add branch for zero iterations. */
1019 p = profile_probability::always ().apply_scale (1, max_unroll + 1);
1020 swtch = ezc_swtch;
1021 preheader = split_edge (loop_preheader_edge (loop));
1022 /* Recompute count adjustments since initial peel copy may
1023 have exited and reduced those values that were computed above. */
1024 iter_count = swtch->count.apply_scale (1, max_unroll + 1);
1025 /* Add in count of edge from switch block. */
1026 preheader->count += iter_count;
1027 branch_code = compare_and_jump_seq (copy_rtx (niter), const0_rtx, EQ,
1028 block_label (preheader), p,
1029 NULL);
1030 gcc_assert (branch_code != NULL_RTX);
1032 swtch = split_edge_and_insert (single_succ_edge (swtch), branch_code);
1033 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
1034 single_succ_edge (swtch)->probability = p.invert ();
1035 e = make_edge (swtch, preheader,
1036 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
1037 e->probability = p;
1040 /* Recount dominators for outer blocks. */
1041 iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, false);
1043 /* And unroll loop. */
1045 bitmap_ones (wont_exit);
1046 bitmap_clear_bit (wont_exit, may_exit_copy);
1047 opt_info_start_duplication (opt_info);
1049 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1050 max_unroll,
1051 wont_exit, desc->out_edge,
1052 &remove_edges,
1053 DLTHE_FLAG_UPDATE_FREQ
1054 | (opt_info
1055 ? DLTHE_RECORD_COPY_NUMBER
1056 : 0));
1057 gcc_assert (ok);
1059 if (opt_info)
1061 apply_opt_in_copies (opt_info, max_unroll, true, true);
1062 free_opt_info (opt_info);
1065 if (exit_at_end)
1067 basic_block exit_block = get_bb_copy (desc->in_edge->src);
1068 /* Find a new in and out edge; they are in the last copy we have
1069 made. */
1071 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
1073 desc->out_edge = EDGE_SUCC (exit_block, 0);
1074 desc->in_edge = EDGE_SUCC (exit_block, 1);
1076 else
1078 desc->out_edge = EDGE_SUCC (exit_block, 1);
1079 desc->in_edge = EDGE_SUCC (exit_block, 0);
1083 /* Remove the edges. */
1084 FOR_EACH_VEC_ELT (remove_edges, i, e)
1085 remove_path (e);
1087 /* We must be careful when updating the number of iterations due to
1088 preconditioning and the fact that the value must be valid at entry
1089 of the loop. After passing through the above code, we see that
1090 the correct new number of iterations is this: */
1091 gcc_assert (!desc->const_iter);
1092 desc->niter_expr =
1093 simplify_gen_binary (UDIV, desc->mode, old_niter,
1094 gen_int_mode (max_unroll + 1, desc->mode));
1095 loop->nb_iterations_upper_bound
1096 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
1097 if (loop->any_estimate)
1098 loop->nb_iterations_estimate
1099 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
1100 if (loop->any_likely_upper_bound)
1101 loop->nb_iterations_likely_upper_bound
1102 = wi::udiv_trunc (loop->nb_iterations_likely_upper_bound, max_unroll + 1);
1103 if (exit_at_end)
1105 desc->niter_expr =
1106 simplify_gen_binary (MINUS, desc->mode, desc->niter_expr, const1_rtx);
1107 desc->noloop_assumptions = NULL_RTX;
1108 --loop->nb_iterations_upper_bound;
1109 if (loop->any_estimate
1110 && loop->nb_iterations_estimate != 0)
1111 --loop->nb_iterations_estimate;
1112 else
1113 loop->any_estimate = false;
1114 if (loop->any_likely_upper_bound
1115 && loop->nb_iterations_likely_upper_bound != 0)
1116 --loop->nb_iterations_likely_upper_bound;
1117 else
1118 loop->any_likely_upper_bound = false;
1121 if (dump_file)
1122 fprintf (dump_file,
1123 ";; Unrolled loop %d times, counting # of iterations "
1124 "in runtime, %i insns\n",
1125 max_unroll, num_loop_insns (loop));
1128 /* Decide whether to unroll LOOP stupidly and how much. */
1129 static void
1130 decide_unroll_stupid (struct loop *loop, int flags)
1132 unsigned nunroll, nunroll_by_av, i;
1133 struct niter_desc *desc;
1134 widest_int iterations;
1136 if (!(flags & UAP_UNROLL_ALL))
1138 /* We were not asked to, just return back silently. */
1139 return;
1142 if (dump_file)
1143 fprintf (dump_file, "\n;; Considering unrolling loop stupidly\n");
1145 /* nunroll = total number of copies of the original loop body in
1146 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
1147 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
1148 nunroll_by_av
1149 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
1150 if (nunroll > nunroll_by_av)
1151 nunroll = nunroll_by_av;
1152 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
1153 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1155 if (targetm.loop_unroll_adjust)
1156 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
1158 /* Skip big loops. */
1159 if (nunroll <= 1)
1161 if (dump_file)
1162 fprintf (dump_file, ";; Not considering loop, is too big\n");
1163 return;
1166 /* Check for simple loops. */
1167 desc = get_simple_loop_desc (loop);
1169 /* Check simpleness. */
1170 if (desc->simple_p && !desc->assumptions)
1172 if (dump_file)
1173 fprintf (dump_file, ";; The loop is simple\n");
1174 return;
1177 /* Do not unroll loops with branches inside -- it increases number
1178 of mispredicts.
1179 TODO: this heuristic needs tunning; call inside the loop body
1180 is also relatively good reason to not unroll. */
1181 if (num_loop_branches (loop) > 1)
1183 if (dump_file)
1184 fprintf (dump_file, ";; Not unrolling, contains branches\n");
1185 return;
1188 /* Check whether the loop rolls. */
1189 if ((get_estimated_loop_iterations (loop, &iterations)
1190 || get_likely_max_loop_iterations (loop, &iterations))
1191 && wi::ltu_p (iterations, 2 * nunroll))
1193 if (dump_file)
1194 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
1195 return;
1198 /* Success. Now force nunroll to be power of 2, as it seems that this
1199 improves results (partially because of better alignments, partially
1200 because of some dark magic). */
1201 for (i = 1; 2 * i <= nunroll; i *= 2)
1202 continue;
1204 loop->lpt_decision.decision = LPT_UNROLL_STUPID;
1205 loop->lpt_decision.times = i - 1;
1208 /* Unroll a LOOP LOOP->LPT_DECISION.TIMES times. The transformation does this:
1210 while (cond)
1211 body;
1213 ==> (LOOP->LPT_DECISION.TIMES == 3)
1215 while (cond)
1217 body;
1218 if (!cond) break;
1219 body;
1220 if (!cond) break;
1221 body;
1222 if (!cond) break;
1223 body;
1226 static void
1227 unroll_loop_stupid (struct loop *loop)
1229 unsigned nunroll = loop->lpt_decision.times;
1230 struct niter_desc *desc = get_simple_loop_desc (loop);
1231 struct opt_info *opt_info = NULL;
1232 bool ok;
1234 if (flag_split_ivs_in_unroller
1235 || flag_variable_expansion_in_unroller)
1236 opt_info = analyze_insns_in_loop (loop);
1238 auto_sbitmap wont_exit (nunroll + 1);
1239 bitmap_clear (wont_exit);
1240 opt_info_start_duplication (opt_info);
1242 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
1243 nunroll, wont_exit,
1244 NULL, NULL,
1245 DLTHE_FLAG_UPDATE_FREQ
1246 | (opt_info
1247 ? DLTHE_RECORD_COPY_NUMBER
1248 : 0));
1249 gcc_assert (ok);
1251 if (opt_info)
1253 apply_opt_in_copies (opt_info, nunroll, true, true);
1254 free_opt_info (opt_info);
1257 if (desc->simple_p)
1259 /* We indeed may get here provided that there are nontrivial assumptions
1260 for a loop to be really simple. We could update the counts, but the
1261 problem is that we are unable to decide which exit will be taken
1262 (not really true in case the number of iterations is constant,
1263 but no one will do anything with this information, so we do not
1264 worry about it). */
1265 desc->simple_p = false;
1268 if (dump_file)
1269 fprintf (dump_file, ";; Unrolled loop %d times, %i insns\n",
1270 nunroll, num_loop_insns (loop));
1273 /* Returns true if REG is referenced in one nondebug insn in LOOP.
1274 Set *DEBUG_USES to the number of debug insns that reference the
1275 variable. */
1277 static bool
1278 referenced_in_one_insn_in_loop_p (struct loop *loop, rtx reg,
1279 int *debug_uses)
1281 basic_block *body, bb;
1282 unsigned i;
1283 int count_ref = 0;
1284 rtx_insn *insn;
1286 body = get_loop_body (loop);
1287 for (i = 0; i < loop->num_nodes; i++)
1289 bb = body[i];
1291 FOR_BB_INSNS (bb, insn)
1292 if (!rtx_referenced_p (reg, insn))
1293 continue;
1294 else if (DEBUG_INSN_P (insn))
1295 ++*debug_uses;
1296 else if (++count_ref > 1)
1297 break;
1299 free (body);
1300 return (count_ref == 1);
1303 /* Reset the DEBUG_USES debug insns in LOOP that reference REG. */
1305 static void
1306 reset_debug_uses_in_loop (struct loop *loop, rtx reg, int debug_uses)
1308 basic_block *body, bb;
1309 unsigned i;
1310 rtx_insn *insn;
1312 body = get_loop_body (loop);
1313 for (i = 0; debug_uses && i < loop->num_nodes; i++)
1315 bb = body[i];
1317 FOR_BB_INSNS (bb, insn)
1318 if (!DEBUG_INSN_P (insn) || !rtx_referenced_p (reg, insn))
1319 continue;
1320 else
1322 validate_change (insn, &INSN_VAR_LOCATION_LOC (insn),
1323 gen_rtx_UNKNOWN_VAR_LOC (), 0);
1324 if (!--debug_uses)
1325 break;
1328 free (body);
1331 /* Determine whether INSN contains an accumulator
1332 which can be expanded into separate copies,
1333 one for each copy of the LOOP body.
1335 for (i = 0 ; i < n; i++)
1336 sum += a[i];
1340 sum += a[i]
1341 ....
1342 i = i+1;
1343 sum1 += a[i]
1344 ....
1345 i = i+1
1346 sum2 += a[i];
1347 ....
1349 Return NULL if INSN contains no opportunity for expansion of accumulator.
1350 Otherwise, allocate a VAR_TO_EXPAND structure, fill it with the relevant
1351 information and return a pointer to it.
1354 static struct var_to_expand *
1355 analyze_insn_to_expand_var (struct loop *loop, rtx_insn *insn)
1357 rtx set, dest, src;
1358 struct var_to_expand *ves;
1359 unsigned accum_pos;
1360 enum rtx_code code;
1361 int debug_uses = 0;
1363 set = single_set (insn);
1364 if (!set)
1365 return NULL;
1367 dest = SET_DEST (set);
1368 src = SET_SRC (set);
1369 code = GET_CODE (src);
1371 if (code != PLUS && code != MINUS && code != MULT && code != FMA)
1372 return NULL;
1374 if (FLOAT_MODE_P (GET_MODE (dest)))
1376 if (!flag_associative_math)
1377 return NULL;
1378 /* In the case of FMA, we're also changing the rounding. */
1379 if (code == FMA && !flag_unsafe_math_optimizations)
1380 return NULL;
1383 /* Hmm, this is a bit paradoxical. We know that INSN is a valid insn
1384 in MD. But if there is no optab to generate the insn, we can not
1385 perform the variable expansion. This can happen if an MD provides
1386 an insn but not a named pattern to generate it, for example to avoid
1387 producing code that needs additional mode switches like for x87/mmx.
1389 So we check have_insn_for which looks for an optab for the operation
1390 in SRC. If it doesn't exist, we can't perform the expansion even
1391 though INSN is valid. */
1392 if (!have_insn_for (code, GET_MODE (src)))
1393 return NULL;
1395 if (!REG_P (dest)
1396 && !(GET_CODE (dest) == SUBREG
1397 && REG_P (SUBREG_REG (dest))))
1398 return NULL;
1400 /* Find the accumulator use within the operation. */
1401 if (code == FMA)
1403 /* We only support accumulation via FMA in the ADD position. */
1404 if (!rtx_equal_p (dest, XEXP (src, 2)))
1405 return NULL;
1406 accum_pos = 2;
1408 else if (rtx_equal_p (dest, XEXP (src, 0)))
1409 accum_pos = 0;
1410 else if (rtx_equal_p (dest, XEXP (src, 1)))
1412 /* The method of expansion that we are using; which includes the
1413 initialization of the expansions with zero and the summation of
1414 the expansions at the end of the computation will yield wrong
1415 results for (x = something - x) thus avoid using it in that case. */
1416 if (code == MINUS)
1417 return NULL;
1418 accum_pos = 1;
1420 else
1421 return NULL;
1423 /* It must not otherwise be used. */
1424 if (code == FMA)
1426 if (rtx_referenced_p (dest, XEXP (src, 0))
1427 || rtx_referenced_p (dest, XEXP (src, 1)))
1428 return NULL;
1430 else if (rtx_referenced_p (dest, XEXP (src, 1 - accum_pos)))
1431 return NULL;
1433 /* It must be used in exactly one insn. */
1434 if (!referenced_in_one_insn_in_loop_p (loop, dest, &debug_uses))
1435 return NULL;
1437 if (dump_file)
1439 fprintf (dump_file, "\n;; Expanding Accumulator ");
1440 print_rtl (dump_file, dest);
1441 fprintf (dump_file, "\n");
1444 if (debug_uses)
1445 /* Instead of resetting the debug insns, we could replace each
1446 debug use in the loop with the sum or product of all expanded
1447 accumulators. Since we'll only know of all expansions at the
1448 end, we'd have to keep track of which vars_to_expand a debug
1449 insn in the loop references, take note of each copy of the
1450 debug insn during unrolling, and when it's all done, compute
1451 the sum or product of each variable and adjust the original
1452 debug insn and each copy thereof. What a pain! */
1453 reset_debug_uses_in_loop (loop, dest, debug_uses);
1455 /* Record the accumulator to expand. */
1456 ves = XNEW (struct var_to_expand);
1457 ves->insn = insn;
1458 ves->reg = copy_rtx (dest);
1459 ves->var_expansions.create (1);
1460 ves->next = NULL;
1461 ves->op = GET_CODE (src);
1462 ves->expansion_count = 0;
1463 ves->reuse_expansion = 0;
1464 return ves;
1467 /* Determine whether there is an induction variable in INSN that
1468 we would like to split during unrolling.
1470 I.e. replace
1472 i = i + 1;
1474 i = i + 1;
1476 i = i + 1;
1479 type chains by
1481 i0 = i + 1
1483 i = i0 + 1
1485 i = i0 + 2
1488 Return NULL if INSN contains no interesting IVs. Otherwise, allocate
1489 an IV_TO_SPLIT structure, fill it with the relevant information and return a
1490 pointer to it. */
1492 static struct iv_to_split *
1493 analyze_iv_to_split_insn (rtx_insn *insn)
1495 rtx set, dest;
1496 struct rtx_iv iv;
1497 struct iv_to_split *ivts;
1498 scalar_int_mode mode;
1499 bool ok;
1501 /* For now we just split the basic induction variables. Later this may be
1502 extended for example by selecting also addresses of memory references. */
1503 set = single_set (insn);
1504 if (!set)
1505 return NULL;
1507 dest = SET_DEST (set);
1508 if (!REG_P (dest) || !is_a <scalar_int_mode> (GET_MODE (dest), &mode))
1509 return NULL;
1511 if (!biv_p (insn, mode, dest))
1512 return NULL;
1514 ok = iv_analyze_result (insn, dest, &iv);
1516 /* This used to be an assert under the assumption that if biv_p returns
1517 true that iv_analyze_result must also return true. However, that
1518 assumption is not strictly correct as evidenced by pr25569.
1520 Returning NULL when iv_analyze_result returns false is safe and
1521 avoids the problems in pr25569 until the iv_analyze_* routines
1522 can be fixed, which is apparently hard and time consuming
1523 according to their author. */
1524 if (! ok)
1525 return NULL;
1527 if (iv.step == const0_rtx
1528 || iv.mode != iv.extend_mode)
1529 return NULL;
1531 /* Record the insn to split. */
1532 ivts = XNEW (struct iv_to_split);
1533 ivts->insn = insn;
1534 ivts->orig_var = dest;
1535 ivts->base_var = NULL_RTX;
1536 ivts->step = iv.step;
1537 ivts->next = NULL;
1539 return ivts;
1542 /* Determines which of insns in LOOP can be optimized.
1543 Return a OPT_INFO struct with the relevant hash tables filled
1544 with all insns to be optimized. The FIRST_NEW_BLOCK field
1545 is undefined for the return value. */
1547 static struct opt_info *
1548 analyze_insns_in_loop (struct loop *loop)
1550 basic_block *body, bb;
1551 unsigned i;
1552 struct opt_info *opt_info = XCNEW (struct opt_info);
1553 rtx_insn *insn;
1554 struct iv_to_split *ivts = NULL;
1555 struct var_to_expand *ves = NULL;
1556 iv_to_split **slot1;
1557 var_to_expand **slot2;
1558 vec<edge> edges = get_loop_exit_edges (loop);
1559 edge exit;
1560 bool can_apply = false;
1562 iv_analysis_loop_init (loop);
1564 body = get_loop_body (loop);
1566 if (flag_split_ivs_in_unroller)
1568 opt_info->insns_to_split
1569 = new hash_table<iv_split_hasher> (5 * loop->num_nodes);
1570 opt_info->iv_to_split_head = NULL;
1571 opt_info->iv_to_split_tail = &opt_info->iv_to_split_head;
1574 /* Record the loop exit bb and loop preheader before the unrolling. */
1575 opt_info->loop_preheader = loop_preheader_edge (loop)->src;
1577 if (edges.length () == 1)
1579 exit = edges[0];
1580 if (!(exit->flags & EDGE_COMPLEX))
1582 opt_info->loop_exit = split_edge (exit);
1583 can_apply = true;
1587 if (flag_variable_expansion_in_unroller
1588 && can_apply)
1590 opt_info->insns_with_var_to_expand
1591 = new hash_table<var_expand_hasher> (5 * loop->num_nodes);
1592 opt_info->var_to_expand_head = NULL;
1593 opt_info->var_to_expand_tail = &opt_info->var_to_expand_head;
1596 for (i = 0; i < loop->num_nodes; i++)
1598 bb = body[i];
1599 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1600 continue;
1602 FOR_BB_INSNS (bb, insn)
1604 if (!INSN_P (insn))
1605 continue;
1607 if (opt_info->insns_to_split)
1608 ivts = analyze_iv_to_split_insn (insn);
1610 if (ivts)
1612 slot1 = opt_info->insns_to_split->find_slot (ivts, INSERT);
1613 gcc_assert (*slot1 == NULL);
1614 *slot1 = ivts;
1615 *opt_info->iv_to_split_tail = ivts;
1616 opt_info->iv_to_split_tail = &ivts->next;
1617 continue;
1620 if (opt_info->insns_with_var_to_expand)
1621 ves = analyze_insn_to_expand_var (loop, insn);
1623 if (ves)
1625 slot2 = opt_info->insns_with_var_to_expand->find_slot (ves, INSERT);
1626 gcc_assert (*slot2 == NULL);
1627 *slot2 = ves;
1628 *opt_info->var_to_expand_tail = ves;
1629 opt_info->var_to_expand_tail = &ves->next;
1634 edges.release ();
1635 free (body);
1636 return opt_info;
1639 /* Called just before loop duplication. Records start of duplicated area
1640 to OPT_INFO. */
1642 static void
1643 opt_info_start_duplication (struct opt_info *opt_info)
1645 if (opt_info)
1646 opt_info->first_new_block = last_basic_block_for_fn (cfun);
1649 /* Determine the number of iterations between initialization of the base
1650 variable and the current copy (N_COPY). N_COPIES is the total number
1651 of newly created copies. UNROLLING is true if we are unrolling
1652 (not peeling) the loop. */
1654 static unsigned
1655 determine_split_iv_delta (unsigned n_copy, unsigned n_copies, bool unrolling)
1657 if (unrolling)
1659 /* If we are unrolling, initialization is done in the original loop
1660 body (number 0). */
1661 return n_copy;
1663 else
1665 /* If we are peeling, the copy in that the initialization occurs has
1666 number 1. The original loop (number 0) is the last. */
1667 if (n_copy)
1668 return n_copy - 1;
1669 else
1670 return n_copies;
1674 /* Allocate basic variable for the induction variable chain. */
1676 static void
1677 allocate_basic_variable (struct iv_to_split *ivts)
1679 rtx expr = SET_SRC (single_set (ivts->insn));
1681 ivts->base_var = gen_reg_rtx (GET_MODE (expr));
1684 /* Insert initialization of basic variable of IVTS before INSN, taking
1685 the initial value from INSN. */
1687 static void
1688 insert_base_initialization (struct iv_to_split *ivts, rtx_insn *insn)
1690 rtx expr = copy_rtx (SET_SRC (single_set (insn)));
1691 rtx_insn *seq;
1693 start_sequence ();
1694 expr = force_operand (expr, ivts->base_var);
1695 if (expr != ivts->base_var)
1696 emit_move_insn (ivts->base_var, expr);
1697 seq = get_insns ();
1698 end_sequence ();
1700 emit_insn_before (seq, insn);
1703 /* Replace the use of induction variable described in IVTS in INSN
1704 by base variable + DELTA * step. */
1706 static void
1707 split_iv (struct iv_to_split *ivts, rtx_insn *insn, unsigned delta)
1709 rtx expr, *loc, incr, var;
1710 rtx_insn *seq;
1711 machine_mode mode = GET_MODE (ivts->base_var);
1712 rtx src, dest, set;
1714 /* Construct base + DELTA * step. */
1715 if (!delta)
1716 expr = ivts->base_var;
1717 else
1719 incr = simplify_gen_binary (MULT, mode,
1720 copy_rtx (ivts->step),
1721 gen_int_mode (delta, mode));
1722 expr = simplify_gen_binary (PLUS, GET_MODE (ivts->base_var),
1723 ivts->base_var, incr);
1726 /* Figure out where to do the replacement. */
1727 loc = &SET_SRC (single_set (insn));
1729 /* If we can make the replacement right away, we're done. */
1730 if (validate_change (insn, loc, expr, 0))
1731 return;
1733 /* Otherwise, force EXPR into a register and try again. */
1734 start_sequence ();
1735 var = gen_reg_rtx (mode);
1736 expr = force_operand (expr, var);
1737 if (expr != var)
1738 emit_move_insn (var, expr);
1739 seq = get_insns ();
1740 end_sequence ();
1741 emit_insn_before (seq, insn);
1743 if (validate_change (insn, loc, var, 0))
1744 return;
1746 /* The last chance. Try recreating the assignment in insn
1747 completely from scratch. */
1748 set = single_set (insn);
1749 gcc_assert (set);
1751 start_sequence ();
1752 *loc = var;
1753 src = copy_rtx (SET_SRC (set));
1754 dest = copy_rtx (SET_DEST (set));
1755 src = force_operand (src, dest);
1756 if (src != dest)
1757 emit_move_insn (dest, src);
1758 seq = get_insns ();
1759 end_sequence ();
1761 emit_insn_before (seq, insn);
1762 delete_insn (insn);
1766 /* Return one expansion of the accumulator recorded in struct VE. */
1768 static rtx
1769 get_expansion (struct var_to_expand *ve)
1771 rtx reg;
1773 if (ve->reuse_expansion == 0)
1774 reg = ve->reg;
1775 else
1776 reg = ve->var_expansions[ve->reuse_expansion - 1];
1778 if (ve->var_expansions.length () == (unsigned) ve->reuse_expansion)
1779 ve->reuse_expansion = 0;
1780 else
1781 ve->reuse_expansion++;
1783 return reg;
1787 /* Given INSN replace the uses of the accumulator recorded in VE
1788 with a new register. */
1790 static void
1791 expand_var_during_unrolling (struct var_to_expand *ve, rtx_insn *insn)
1793 rtx new_reg, set;
1794 bool really_new_expansion = false;
1796 set = single_set (insn);
1797 gcc_assert (set);
1799 /* Generate a new register only if the expansion limit has not been
1800 reached. Else reuse an already existing expansion. */
1801 if (PARAM_VALUE (PARAM_MAX_VARIABLE_EXPANSIONS) > ve->expansion_count)
1803 really_new_expansion = true;
1804 new_reg = gen_reg_rtx (GET_MODE (ve->reg));
1806 else
1807 new_reg = get_expansion (ve);
1809 validate_replace_rtx_group (SET_DEST (set), new_reg, insn);
1810 if (apply_change_group ())
1811 if (really_new_expansion)
1813 ve->var_expansions.safe_push (new_reg);
1814 ve->expansion_count++;
1818 /* Initialize the variable expansions in loop preheader. PLACE is the
1819 loop-preheader basic block where the initialization of the
1820 expansions should take place. The expansions are initialized with
1821 (-0) when the operation is plus or minus to honor sign zero. This
1822 way we can prevent cases where the sign of the final result is
1823 effected by the sign of the expansion. Here is an example to
1824 demonstrate this:
1826 for (i = 0 ; i < n; i++)
1827 sum += something;
1831 sum += something
1832 ....
1833 i = i+1;
1834 sum1 += something
1835 ....
1836 i = i+1
1837 sum2 += something;
1838 ....
1840 When SUM is initialized with -zero and SOMETHING is also -zero; the
1841 final result of sum should be -zero thus the expansions sum1 and sum2
1842 should be initialized with -zero as well (otherwise we will get +zero
1843 as the final result). */
1845 static void
1846 insert_var_expansion_initialization (struct var_to_expand *ve,
1847 basic_block place)
1849 rtx_insn *seq;
1850 rtx var, zero_init;
1851 unsigned i;
1852 machine_mode mode = GET_MODE (ve->reg);
1853 bool honor_signed_zero_p = HONOR_SIGNED_ZEROS (mode);
1855 if (ve->var_expansions.length () == 0)
1856 return;
1858 start_sequence ();
1859 switch (ve->op)
1861 case FMA:
1862 /* Note that we only accumulate FMA via the ADD operand. */
1863 case PLUS:
1864 case MINUS:
1865 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1867 if (honor_signed_zero_p)
1868 zero_init = simplify_gen_unary (NEG, mode, CONST0_RTX (mode), mode);
1869 else
1870 zero_init = CONST0_RTX (mode);
1871 emit_move_insn (var, zero_init);
1873 break;
1875 case MULT:
1876 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1878 zero_init = CONST1_RTX (GET_MODE (var));
1879 emit_move_insn (var, zero_init);
1881 break;
1883 default:
1884 gcc_unreachable ();
1887 seq = get_insns ();
1888 end_sequence ();
1890 emit_insn_after (seq, BB_END (place));
1893 /* Combine the variable expansions at the loop exit. PLACE is the
1894 loop exit basic block where the summation of the expansions should
1895 take place. */
1897 static void
1898 combine_var_copies_in_loop_exit (struct var_to_expand *ve, basic_block place)
1900 rtx sum = ve->reg;
1901 rtx expr, var;
1902 rtx_insn *seq, *insn;
1903 unsigned i;
1905 if (ve->var_expansions.length () == 0)
1906 return;
1908 /* ve->reg might be SUBREG or some other non-shareable RTL, and we use
1909 it both here and as the destination of the assignment. */
1910 sum = copy_rtx (sum);
1911 start_sequence ();
1912 switch (ve->op)
1914 case FMA:
1915 /* Note that we only accumulate FMA via the ADD operand. */
1916 case PLUS:
1917 case MINUS:
1918 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1919 sum = simplify_gen_binary (PLUS, GET_MODE (ve->reg), var, sum);
1920 break;
1922 case MULT:
1923 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
1924 sum = simplify_gen_binary (MULT, GET_MODE (ve->reg), var, sum);
1925 break;
1927 default:
1928 gcc_unreachable ();
1931 expr = force_operand (sum, ve->reg);
1932 if (expr != ve->reg)
1933 emit_move_insn (ve->reg, expr);
1934 seq = get_insns ();
1935 end_sequence ();
1937 insn = BB_HEAD (place);
1938 while (!NOTE_INSN_BASIC_BLOCK_P (insn))
1939 insn = NEXT_INSN (insn);
1941 emit_insn_after (seq, insn);
1944 /* Strip away REG_EQUAL notes for IVs we're splitting.
1946 Updating REG_EQUAL notes for IVs we split is tricky: We
1947 cannot tell until after unrolling, DF-rescanning, and liveness
1948 updating, whether an EQ_USE is reached by the split IV while
1949 the IV reg is still live. See PR55006.
1951 ??? We cannot use remove_reg_equal_equiv_notes_for_regno,
1952 because RTL loop-iv requires us to defer rescanning insns and
1953 any notes attached to them. So resort to old techniques... */
1955 static void
1956 maybe_strip_eq_note_for_split_iv (struct opt_info *opt_info, rtx_insn *insn)
1958 struct iv_to_split *ivts;
1959 rtx note = find_reg_equal_equiv_note (insn);
1960 if (! note)
1961 return;
1962 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1963 if (reg_mentioned_p (ivts->orig_var, note))
1965 remove_note (insn, note);
1966 return;
1970 /* Apply loop optimizations in loop copies using the
1971 data which gathered during the unrolling. Structure
1972 OPT_INFO record that data.
1974 UNROLLING is true if we unrolled (not peeled) the loop.
1975 REWRITE_ORIGINAL_BODY is true if we should also rewrite the original body of
1976 the loop (as it should happen in complete unrolling, but not in ordinary
1977 peeling of the loop). */
1979 static void
1980 apply_opt_in_copies (struct opt_info *opt_info,
1981 unsigned n_copies, bool unrolling,
1982 bool rewrite_original_loop)
1984 unsigned i, delta;
1985 basic_block bb, orig_bb;
1986 rtx_insn *insn, *orig_insn, *next;
1987 struct iv_to_split ivts_templ, *ivts;
1988 struct var_to_expand ve_templ, *ves;
1990 /* Sanity check -- we need to put initialization in the original loop
1991 body. */
1992 gcc_assert (!unrolling || rewrite_original_loop);
1994 /* Allocate the basic variables (i0). */
1995 if (opt_info->insns_to_split)
1996 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1997 allocate_basic_variable (ivts);
1999 for (i = opt_info->first_new_block;
2000 i < (unsigned) last_basic_block_for_fn (cfun);
2001 i++)
2003 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2004 orig_bb = get_bb_original (bb);
2006 /* bb->aux holds position in copy sequence initialized by
2007 duplicate_loop_to_header_edge. */
2008 delta = determine_split_iv_delta ((size_t)bb->aux, n_copies,
2009 unrolling);
2010 bb->aux = 0;
2011 orig_insn = BB_HEAD (orig_bb);
2012 FOR_BB_INSNS_SAFE (bb, insn, next)
2014 if (!INSN_P (insn)
2015 || (DEBUG_INSN_P (insn)
2016 && TREE_CODE (INSN_VAR_LOCATION_DECL (insn)) == LABEL_DECL))
2017 continue;
2019 while (!INSN_P (orig_insn)
2020 || (DEBUG_INSN_P (orig_insn)
2021 && (TREE_CODE (INSN_VAR_LOCATION_DECL (orig_insn))
2022 == LABEL_DECL)))
2023 orig_insn = NEXT_INSN (orig_insn);
2025 ivts_templ.insn = orig_insn;
2026 ve_templ.insn = orig_insn;
2028 /* Apply splitting iv optimization. */
2029 if (opt_info->insns_to_split)
2031 maybe_strip_eq_note_for_split_iv (opt_info, insn);
2033 ivts = opt_info->insns_to_split->find (&ivts_templ);
2035 if (ivts)
2037 gcc_assert (GET_CODE (PATTERN (insn))
2038 == GET_CODE (PATTERN (orig_insn)));
2040 if (!delta)
2041 insert_base_initialization (ivts, insn);
2042 split_iv (ivts, insn, delta);
2045 /* Apply variable expansion optimization. */
2046 if (unrolling && opt_info->insns_with_var_to_expand)
2048 ves = (struct var_to_expand *)
2049 opt_info->insns_with_var_to_expand->find (&ve_templ);
2050 if (ves)
2052 gcc_assert (GET_CODE (PATTERN (insn))
2053 == GET_CODE (PATTERN (orig_insn)));
2054 expand_var_during_unrolling (ves, insn);
2057 orig_insn = NEXT_INSN (orig_insn);
2061 if (!rewrite_original_loop)
2062 return;
2064 /* Initialize the variable expansions in the loop preheader
2065 and take care of combining them at the loop exit. */
2066 if (opt_info->insns_with_var_to_expand)
2068 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2069 insert_var_expansion_initialization (ves, opt_info->loop_preheader);
2070 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2071 combine_var_copies_in_loop_exit (ves, opt_info->loop_exit);
2074 /* Rewrite also the original loop body. Find them as originals of the blocks
2075 in the last copied iteration, i.e. those that have
2076 get_bb_copy (get_bb_original (bb)) == bb. */
2077 for (i = opt_info->first_new_block;
2078 i < (unsigned) last_basic_block_for_fn (cfun);
2079 i++)
2081 bb = BASIC_BLOCK_FOR_FN (cfun, i);
2082 orig_bb = get_bb_original (bb);
2083 if (get_bb_copy (orig_bb) != bb)
2084 continue;
2086 delta = determine_split_iv_delta (0, n_copies, unrolling);
2087 for (orig_insn = BB_HEAD (orig_bb);
2088 orig_insn != NEXT_INSN (BB_END (bb));
2089 orig_insn = next)
2091 next = NEXT_INSN (orig_insn);
2093 if (!INSN_P (orig_insn))
2094 continue;
2096 ivts_templ.insn = orig_insn;
2097 if (opt_info->insns_to_split)
2099 maybe_strip_eq_note_for_split_iv (opt_info, orig_insn);
2101 ivts = (struct iv_to_split *)
2102 opt_info->insns_to_split->find (&ivts_templ);
2103 if (ivts)
2105 if (!delta)
2106 insert_base_initialization (ivts, orig_insn);
2107 split_iv (ivts, orig_insn, delta);
2108 continue;
2116 /* Release OPT_INFO. */
2118 static void
2119 free_opt_info (struct opt_info *opt_info)
2121 delete opt_info->insns_to_split;
2122 opt_info->insns_to_split = NULL;
2123 if (opt_info->insns_with_var_to_expand)
2125 struct var_to_expand *ves;
2127 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2128 ves->var_expansions.release ();
2129 delete opt_info->insns_with_var_to_expand;
2130 opt_info->insns_with_var_to_expand = NULL;
2132 free (opt_info);