]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/loop-unroll.c
Move MEMMODEL_* from coretypes.h to memmodel.h
[thirdparty/gcc.git] / gcc / loop-unroll.c
CommitLineData
f8934be7 1/* Loop unrolling.
818ab71a 2 Copyright (C) 2002-2016 Free Software Foundation, Inc.
a29c7ea6
ZD
3
4This file is part of GCC.
5
6GCC is free software; you can redistribute it and/or modify it under
7the terms of the GNU General Public License as published by the Free
9dcd6f09 8Software Foundation; either version 3, or (at your option) any later
a29c7ea6
ZD
9version.
10
11GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12WARRANTY; without even the implied warranty of MERCHANTABILITY or
13FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14for more details.
15
16You should have received a copy of the GNU General Public License
9dcd6f09
NC
17along with GCC; see the file COPYING3. If not see
18<http://www.gnu.org/licenses/>. */
a29c7ea6
ZD
19
20#include "config.h"
21#include "system.h"
22#include "coretypes.h"
c7131fb2 23#include "backend.h"
957060b5 24#include "target.h"
a29c7ea6 25#include "rtl.h"
4d648807 26#include "tree.h"
957060b5 27#include "cfghooks.h"
4d0cdd0c 28#include "memmodel.h"
957060b5
AM
29#include "optabs.h"
30#include "emit-rtl.h"
31#include "recog.h"
59f2e9d8 32#include "profile.h"
60393bbc 33#include "cfgrtl.h"
a29c7ea6 34#include "cfgloop.h"
a29c7ea6 35#include "params.h"
36566b39 36#include "dojump.h"
a29c7ea6 37#include "expr.h"
7ee2468b 38#include "dumpfile.h"
a29c7ea6 39
f8934be7
JH
40/* This pass performs loop unrolling. We only perform this
41 optimization on innermost loops (with single exception) because
a29c7ea6
ZD
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
4d6922ee 44 of code, better code to optimize for further passes and in some cases
a29c7ea6
ZD
45 by fewer testings of exit conditions. The main problem is code growth,
46 that impacts performance negatively due to effect of caches.
47
48 What we do:
49
a29c7ea6
ZD
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.
60
61 There is a lot of parameters (defined and described in params.def) that
f8934be7 62 control how much we unroll.
a29c7ea6
ZD
63
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 %.
67 */
68
113d659a
ZD
69/* Information about induction variables to split. */
70
71struct iv_to_split
72{
95ecfb26 73 rtx_insn *insn; /* The insn in that the induction variable occurs. */
4a0c3fde 74 rtx orig_var; /* The variable (register) for the IV before split. */
113d659a
ZD
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. */
a9f6ecee 78 struct iv_to_split *next; /* Next entry in walking order. */
113d659a
ZD
79};
80
f37a4f14
RE
81/* Information about accumulators to expand. */
82
83struct var_to_expand
84{
95ecfb26 85 rtx_insn *insn; /* The insn in that the variable expansion occurs. */
471854f8 86 rtx reg; /* The accumulator which is expanded. */
9771b263 87 vec<rtx> var_expansions; /* The copies of the accumulator which is expanded. */
a9f6ecee 88 struct var_to_expand *next; /* Next entry in walking order. */
b8698a0f 89 enum rtx_code op; /* The type of the accumulation - addition, subtraction
f37a4f14
RE
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
b8698a0f
L
93 the accumulator. If REUSE_EXPANSION is 0 reuse
94 the original accumulator. Else use
f37a4f14
RE
95 var_expansions[REUSE_EXPANSION - 1]. */
96};
97
4a8fb1a1
LC
98/* Hashtable helper for iv_to_split. */
99
95fbe13e 100struct iv_split_hasher : free_ptr_hash <iv_to_split>
4a8fb1a1 101{
67f58944
TS
102 static inline hashval_t hash (const iv_to_split *);
103 static inline bool equal (const iv_to_split *, const iv_to_split *);
4a8fb1a1
LC
104};
105
106
107/* A hash function for information about insns to split. */
108
109inline hashval_t
67f58944 110iv_split_hasher::hash (const iv_to_split *ivts)
4a8fb1a1
LC
111{
112 return (hashval_t) INSN_UID (ivts->insn);
113}
114
115/* An equality functions for information about insns to split. */
116
117inline bool
67f58944 118iv_split_hasher::equal (const iv_to_split *i1, const iv_to_split *i2)
4a8fb1a1
LC
119{
120 return i1->insn == i2->insn;
121}
122
123/* Hashtable helper for iv_to_split. */
124
95fbe13e 125struct var_expand_hasher : free_ptr_hash <var_to_expand>
4a8fb1a1 126{
67f58944
TS
127 static inline hashval_t hash (const var_to_expand *);
128 static inline bool equal (const var_to_expand *, const var_to_expand *);
4a8fb1a1
LC
129};
130
131/* Return a hash for VES. */
132
133inline hashval_t
67f58944 134var_expand_hasher::hash (const var_to_expand *ves)
4a8fb1a1
LC
135{
136 return (hashval_t) INSN_UID (ves->insn);
137}
138
139/* Return true if I1 and I2 refer to the same instruction. */
140
141inline bool
67f58944 142var_expand_hasher::equal (const var_to_expand *i1, const var_to_expand *i2)
4a8fb1a1
LC
143{
144 return i1->insn == i2->insn;
145}
146
f37a4f14
RE
147/* Information about optimization applied in
148 the unrolled loop. */
149
150struct opt_info
113d659a 151{
c203e8a7 152 hash_table<iv_split_hasher> *insns_to_split; /* A hashtable of insns to
4a8fb1a1 153 split. */
a9f6ecee
AO
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. */
c203e8a7 156 hash_table<var_expand_hasher> *insns_with_var_to_expand; /* A hashtable of
4a8fb1a1 157 insns with accumulators to expand. */
a9f6ecee
AO
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. */
f37a4f14
RE
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. */
113d659a
ZD
164};
165
d47cc544
SB
166static void decide_unroll_stupid (struct loop *, int);
167static void decide_unroll_constant_iterations (struct loop *, int);
168static void decide_unroll_runtime_iterations (struct loop *, int);
d73be268 169static void unroll_loop_stupid (struct loop *);
f8934be7 170static void decide_unrolling (int);
d73be268
ZD
171static void unroll_loop_constant_iterations (struct loop *);
172static void unroll_loop_runtime_iterations (struct loop *);
f37a4f14
RE
173static struct opt_info *analyze_insns_in_loop (struct loop *);
174static void opt_info_start_duplication (struct opt_info *);
175static void apply_opt_in_copies (struct opt_info *, unsigned, bool, bool);
176static void free_opt_info (struct opt_info *);
95ecfb26 177static struct var_to_expand *analyze_insn_to_expand_var (struct loop*, rtx_insn *);
60c48e4c 178static bool referenced_in_one_insn_in_loop_p (struct loop *, rtx, int *);
1b20d55a 179static struct iv_to_split *analyze_iv_to_split_insn (rtx_insn *);
95ecfb26 180static void expand_var_during_unrolling (struct var_to_expand *, rtx_insn *);
a9f6ecee
AO
181static void insert_var_expansion_initialization (struct var_to_expand *,
182 basic_block);
183static void combine_var_copies_in_loop_exit (struct var_to_expand *,
184 basic_block);
f37a4f14 185static rtx get_expansion (struct var_to_expand *);
a29c7ea6 186
f8934be7 187/* Emit a message summarizing the unroll that will be
e25a6711
TJ
188 performed for LOOP, along with the loop's location LOCUS, if
189 appropriate given the dump or -fopt-info settings. */
190
191static void
f8934be7 192report_unroll (struct loop *loop, location_t locus)
e25a6711 193{
e25a6711
TJ
194 int report_flags = MSG_OPTIMIZED_LOCATIONS | TDF_RTL | TDF_DETAILS;
195
ad4db775
TJ
196 if (loop->lpt_decision.decision == LPT_NONE)
197 return;
198
e25a6711
TJ
199 if (!dump_enabled_p ())
200 return;
201
f8934be7
JH
202 dump_printf_loc (report_flags, locus,
203 "loop unrolled %d times",
204 loop->lpt_decision.times);
e25a6711
TJ
205 if (profile_info)
206 dump_printf (report_flags,
f8934be7 207 " (header execution count %d)",
e25a6711 208 (int)loop->header->count);
e25a6711
TJ
209
210 dump_printf (report_flags, "\n");
211}
212
f8934be7 213/* Decide whether unroll loops and how much. */
a29c7ea6 214static void
f8934be7 215decide_unrolling (int flags)
a29c7ea6 216{
42fd6772 217 struct loop *loop;
a29c7ea6
ZD
218
219 /* Scan the loops, inner ones first. */
f0bd40b1 220 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
a29c7ea6 221 {
a29c7ea6 222 loop->lpt_decision.decision = LPT_NONE;
e25a6711 223 location_t locus = get_loop_location (loop);
a29c7ea6 224
e25a6711
TJ
225 if (dump_enabled_p ())
226 dump_printf_loc (TDF_RTL, locus,
227 ";; *** Considering loop %d at BB %d for "
f8934be7 228 "unrolling ***\n",
e25a6711 229 loop->num, loop->header->index);
a29c7ea6
ZD
230
231 /* Do not peel cold areas. */
efd8f750 232 if (optimize_loop_for_size_p (loop))
a29c7ea6 233 {
c263766c
RH
234 if (dump_file)
235 fprintf (dump_file, ";; Not considering loop, cold area\n");
a29c7ea6
ZD
236 continue;
237 }
238
239 /* Can the loop be manipulated? */
240 if (!can_duplicate_loop_p (loop))
241 {
c263766c
RH
242 if (dump_file)
243 fprintf (dump_file,
a29c7ea6 244 ";; Not considering loop, cannot duplicate\n");
a29c7ea6
ZD
245 continue;
246 }
247
248 /* Skip non-innermost loops. */
249 if (loop->inner)
250 {
c263766c
RH
251 if (dump_file)
252 fprintf (dump_file, ";; Not considering loop, is not innermost\n");
a29c7ea6
ZD
253 continue;
254 }
255
256 loop->ninsns = num_loop_insns (loop);
257 loop->av_ninsns = average_num_loop_insns (loop);
258
259 /* Try transformations one by one in decreasing order of
260 priority. */
261
d47cc544 262 decide_unroll_constant_iterations (loop, flags);
a29c7ea6 263 if (loop->lpt_decision.decision == LPT_NONE)
d47cc544 264 decide_unroll_runtime_iterations (loop, flags);
a29c7ea6 265 if (loop->lpt_decision.decision == LPT_NONE)
d47cc544 266 decide_unroll_stupid (loop, flags);
a29c7ea6 267
f8934be7 268 report_unroll (loop, locus);
a29c7ea6 269 }
a29c7ea6
ZD
270}
271
f8934be7
JH
272/* Unroll LOOPS. */
273void
274unroll_loops (int flags)
a29c7ea6 275{
f8934be7
JH
276 struct loop *loop;
277 bool changed = false;
a29c7ea6 278
f8934be7
JH
279 /* Now decide rest of unrolling. */
280 decide_unrolling (flags);
a29c7ea6 281
f8934be7
JH
282 /* Scan the loops, inner ones first. */
283 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
a29c7ea6 284 {
f8934be7
JH
285 /* And perform the appropriate transformations. */
286 switch (loop->lpt_decision.decision)
0c20a65f 287 {
f8934be7
JH
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 ();
a29c7ea6 304 }
a29c7ea6
ZD
305 }
306
f8934be7
JH
307 if (changed)
308 {
309 calculate_dominance_info (CDI_DOMINATORS);
310 fix_loop_structure (NULL);
311 }
0c20a65f 312
f8934be7
JH
313 iv_analysis_done ();
314}
a29c7ea6 315
f8934be7 316/* Check whether exit of the LOOP is at the end of loop body. */
0c20a65f 317
f8934be7
JH
318static bool
319loop_exit_at_end_p (struct loop *loop)
a29c7ea6 320{
50654f6c 321 struct niter_desc *desc = get_simple_loop_desc (loop);
f8934be7 322 rtx_insn *insn;
35b07080 323
f8934be7
JH
324 /* We should never have conditional in latch block. */
325 gcc_assert (desc->in_edge->dest != loop->header);
b8698a0f 326
f8934be7
JH
327 if (desc->in_edge->dest != loop->latch)
328 return false;
113d659a 329
f8934be7
JH
330 /* Check that the latch is empty. */
331 FOR_BB_INSNS (loop->latch, insn)
332 {
333 if (INSN_P (insn) && active_insn_p (insn))
334 return false;
35b07080 335 }
a29c7ea6 336
f8934be7 337 return true;
a29c7ea6
ZD
338}
339
c263766c
RH
340/* Decide whether to unroll LOOP iterating constant number of times
341 and how much. */
50654f6c 342
a29c7ea6 343static void
d47cc544 344decide_unroll_constant_iterations (struct loop *loop, int flags)
a29c7ea6 345{
50654f6c
ZD
346 unsigned nunroll, nunroll_by_av, best_copies, best_unroll = 0, n_copies, i;
347 struct niter_desc *desc;
807e902e 348 widest_int iterations;
a29c7ea6
ZD
349
350 if (!(flags & UAP_UNROLL))
351 {
352 /* We were not asked to, just return back silently. */
353 return;
354 }
355
c263766c
RH
356 if (dump_file)
357 fprintf (dump_file,
358 "\n;; Considering unrolling loop with constant "
359 "number of iterations\n");
a29c7ea6
ZD
360
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;
c263766c
RH
364 nunroll_by_av
365 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
a29c7ea6
ZD
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);
370
df0f3392
GG
371 if (targetm.loop_unroll_adjust)
372 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
373
a29c7ea6
ZD
374 /* Skip big loops. */
375 if (nunroll <= 1)
376 {
c263766c
RH
377 if (dump_file)
378 fprintf (dump_file, ";; Not considering loop, is too big\n");
a29c7ea6
ZD
379 return;
380 }
381
382 /* Check for simple loops. */
50654f6c 383 desc = get_simple_loop_desc (loop);
a29c7ea6
ZD
384
385 /* Check number of iterations. */
50654f6c 386 if (!desc->simple_p || !desc->const_iter || desc->assumptions)
a29c7ea6 387 {
c263766c
RH
388 if (dump_file)
389 fprintf (dump_file,
390 ";; Unable to prove that the loop iterates constant times\n");
a29c7ea6
ZD
391 return;
392 }
393
e598c332
JH
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
71343877 399 || ((get_estimated_loop_iterations (loop, &iterations)
8c383600 400 || get_likely_max_loop_iterations (loop, &iterations))
807e902e 401 && wi::ltu_p (iterations, 2 * nunroll)))
a29c7ea6 402 {
c263766c
RH
403 if (dump_file)
404 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
a29c7ea6
ZD
405 return;
406 }
407
408 /* Success; now compute number of iterations to unroll. We alter
409 nunroll so that as few as possible copies of loop body are
e0bb17a8 410 necessary, while still not decreasing the number of unrollings
a29c7ea6
ZD
411 too much (at most by 1). */
412 best_copies = 2 * nunroll + 10;
413
414 i = 2 * nunroll + 2;
50654f6c
ZD
415 if (i - 1 >= desc->niter)
416 i = desc->niter - 2;
a29c7ea6
ZD
417
418 for (; i >= nunroll - 1; i--)
419 {
50654f6c 420 unsigned exit_mod = desc->niter % (i + 1);
a29c7ea6 421
50654f6c 422 if (!loop_exit_at_end_p (loop))
a29c7ea6 423 n_copies = exit_mod + i + 1;
50654f6c
ZD
424 else if (exit_mod != (unsigned) i
425 || desc->noloop_assumptions != NULL_RTX)
a29c7ea6
ZD
426 n_copies = exit_mod + i + 2;
427 else
428 n_copies = i + 1;
429
430 if (n_copies < best_copies)
431 {
432 best_copies = n_copies;
433 best_unroll = i;
434 }
435 }
436
a29c7ea6
ZD
437 loop->lpt_decision.decision = LPT_UNROLL_CONSTANT;
438 loop->lpt_decision.times = best_unroll;
439}
440
4fc2e37d
EB
441/* Unroll LOOP with constant number of iterations LOOP->LPT_DECISION.TIMES times.
442 The transformation does this:
0c20a65f 443
a29c7ea6
ZD
444 for (i = 0; i < 102; i++)
445 body;
0c20a65f 446
4fc2e37d 447 ==> (LOOP->LPT_DECISION.TIMES == 3)
0c20a65f 448
a29c7ea6
ZD
449 i = 0;
450 body; i++;
451 body; i++;
452 while (i < 102)
453 {
454 body; i++;
455 body; i++;
456 body; i++;
457 body; i++;
458 }
459 */
460static void
d73be268 461unroll_loop_constant_iterations (struct loop *loop)
a29c7ea6
ZD
462{
463 unsigned HOST_WIDE_INT niter;
464 unsigned exit_mod;
ee8c1b05 465 unsigned i;
ee8c1b05 466 edge e;
a29c7ea6 467 unsigned max_unroll = loop->lpt_decision.times;
50654f6c
ZD
468 struct niter_desc *desc = get_simple_loop_desc (loop);
469 bool exit_at_end = loop_exit_at_end_p (loop);
f37a4f14 470 struct opt_info *opt_info = NULL;
41806d92 471 bool ok;
b8698a0f 472
a29c7ea6
ZD
473 niter = desc->niter;
474
113d659a
ZD
475 /* Should not get here (such loop should be peeled instead). */
476 gcc_assert (niter > max_unroll + 1);
a29c7ea6
ZD
477
478 exit_mod = niter % (max_unroll + 1);
479
7ba9e72d 480 auto_sbitmap wont_exit (max_unroll + 1);
f61e445a 481 bitmap_ones (wont_exit);
a29c7ea6 482
ef062b13 483 auto_vec<edge> remove_edges;
b8698a0f 484 if (flag_split_ivs_in_unroller
f37a4f14
RE
485 || flag_variable_expansion_in_unroller)
486 opt_info = analyze_insns_in_loop (loop);
b8698a0f 487
50654f6c 488 if (!exit_at_end)
a29c7ea6 489 {
50654f6c 490 /* The exit is not at the end of the loop; leave exit test
a29c7ea6
ZD
491 in the first copy, so that the loops that start with test
492 of exit condition have continuous body after unrolling. */
493
c263766c 494 if (dump_file)
4fc2e37d 495 fprintf (dump_file, ";; Condition at beginning of loop.\n");
a29c7ea6
ZD
496
497 /* Peel exit_mod iterations. */
d7c028c0 498 bitmap_clear_bit (wont_exit, 0);
50654f6c 499 if (desc->noloop_assumptions)
d7c028c0 500 bitmap_clear_bit (wont_exit, 1);
a29c7ea6 501
50654f6c
ZD
502 if (exit_mod)
503 {
f37a4f14 504 opt_info_start_duplication (opt_info);
41806d92 505 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
d73be268 506 exit_mod,
50654f6c 507 wont_exit, desc->out_edge,
ee8c1b05 508 &remove_edges,
7f7b1718
JH
509 DLTHE_FLAG_UPDATE_FREQ
510 | (opt_info && exit_mod > 1
511 ? DLTHE_RECORD_COPY_NUMBER
512 : 0));
41806d92 513 gcc_assert (ok);
50654f6c 514
f37a4f14 515 if (opt_info && exit_mod > 1)
b8698a0f
L
516 apply_opt_in_copies (opt_info, exit_mod, false, false);
517
50654f6c
ZD
518 desc->noloop_assumptions = NULL_RTX;
519 desc->niter -= exit_mod;
807e902e 520 loop->nb_iterations_upper_bound -= exit_mod;
e3a8f1fa 521 if (loop->any_estimate
807e902e
KZ
522 && wi::leu_p (exit_mod, loop->nb_iterations_estimate))
523 loop->nb_iterations_estimate -= exit_mod;
e3a8f1fa
JH
524 else
525 loop->any_estimate = false;
105e29c5
JH
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;
50654f6c 531 }
a29c7ea6 532
d7c028c0 533 bitmap_set_bit (wont_exit, 1);
a29c7ea6
ZD
534 }
535 else
536 {
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. */
539
c263766c 540 if (dump_file)
4fc2e37d 541 fprintf (dump_file, ";; Condition at end of loop.\n");
a29c7ea6
ZD
542
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
50654f6c
ZD
545 exit_mod + 1 iterations. */
546 if (exit_mod != max_unroll
547 || desc->noloop_assumptions)
a29c7ea6 548 {
d7c028c0 549 bitmap_clear_bit (wont_exit, 0);
50654f6c 550 if (desc->noloop_assumptions)
d7c028c0 551 bitmap_clear_bit (wont_exit, 1);
b8698a0f 552
f37a4f14 553 opt_info_start_duplication (opt_info);
41806d92 554 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
d73be268 555 exit_mod + 1,
41806d92 556 wont_exit, desc->out_edge,
ee8c1b05 557 &remove_edges,
7f7b1718
JH
558 DLTHE_FLAG_UPDATE_FREQ
559 | (opt_info && exit_mod > 0
560 ? DLTHE_RECORD_COPY_NUMBER
561 : 0));
41806d92 562 gcc_assert (ok);
b8698a0f 563
f37a4f14
RE
564 if (opt_info && exit_mod > 0)
565 apply_opt_in_copies (opt_info, exit_mod + 1, false, false);
113d659a 566
50654f6c 567 desc->niter -= exit_mod + 1;
807e902e 568 loop->nb_iterations_upper_bound -= exit_mod + 1;
e3a8f1fa 569 if (loop->any_estimate
807e902e
KZ
570 && wi::leu_p (exit_mod + 1, loop->nb_iterations_estimate))
571 loop->nb_iterations_estimate -= exit_mod + 1;
e3a8f1fa
JH
572 else
573 loop->any_estimate = false;
105e29c5
JH
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;
50654f6c
ZD
579 desc->noloop_assumptions = NULL_RTX;
580
d7c028c0
LC
581 bitmap_set_bit (wont_exit, 0);
582 bitmap_set_bit (wont_exit, 1);
a29c7ea6
ZD
583 }
584
d7c028c0 585 bitmap_clear_bit (wont_exit, max_unroll);
a29c7ea6
ZD
586 }
587
588 /* Now unroll the loop. */
b8698a0f 589
f37a4f14 590 opt_info_start_duplication (opt_info);
41806d92 591 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
d73be268 592 max_unroll,
41806d92 593 wont_exit, desc->out_edge,
ee8c1b05 594 &remove_edges,
7f7b1718
JH
595 DLTHE_FLAG_UPDATE_FREQ
596 | (opt_info
597 ? DLTHE_RECORD_COPY_NUMBER
598 : 0));
41806d92 599 gcc_assert (ok);
a29c7ea6 600
f37a4f14 601 if (opt_info)
113d659a 602 {
f37a4f14
RE
603 apply_opt_in_copies (opt_info, max_unroll, true, true);
604 free_opt_info (opt_info);
113d659a
ZD
605 }
606
50654f6c
ZD
607 if (exit_at_end)
608 {
6580ee77 609 basic_block exit_block = get_bb_copy (desc->in_edge->src);
50654f6c 610 /* Find a new in and out edge; they are in the last copy we have made. */
b8698a0f 611
628f6a4e 612 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
50654f6c 613 {
628f6a4e
BE
614 desc->out_edge = EDGE_SUCC (exit_block, 0);
615 desc->in_edge = EDGE_SUCC (exit_block, 1);
50654f6c
ZD
616 }
617 else
618 {
628f6a4e
BE
619 desc->out_edge = EDGE_SUCC (exit_block, 1);
620 desc->in_edge = EDGE_SUCC (exit_block, 0);
50654f6c
ZD
621 }
622 }
623
624 desc->niter /= max_unroll + 1;
e3a8f1fa 625 loop->nb_iterations_upper_bound
807e902e 626 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
e3a8f1fa
JH
627 if (loop->any_estimate)
628 loop->nb_iterations_estimate
807e902e 629 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
105e29c5
JH
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);
50654f6c
ZD
633 desc->niter_expr = GEN_INT (desc->niter);
634
a29c7ea6 635 /* Remove the edges. */
9771b263 636 FOR_EACH_VEC_ELT (remove_edges, i, e)
ee8c1b05 637 remove_path (e);
a29c7ea6 638
c263766c
RH
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));
a29c7ea6
ZD
643}
644
645/* Decide whether to unroll LOOP iterating runtime computable number of times
646 and how much. */
647static void
d47cc544 648decide_unroll_runtime_iterations (struct loop *loop, int flags)
a29c7ea6
ZD
649{
650 unsigned nunroll, nunroll_by_av, i;
50654f6c 651 struct niter_desc *desc;
807e902e 652 widest_int iterations;
a29c7ea6
ZD
653
654 if (!(flags & UAP_UNROLL))
655 {
656 /* We were not asked to, just return back silently. */
657 return;
658 }
659
c263766c
RH
660 if (dump_file)
661 fprintf (dump_file,
662 "\n;; Considering unrolling loop with runtime "
663 "computable number of iterations\n");
a29c7ea6
ZD
664
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);
673
40ac4f73
CB
674 if (targetm.loop_unroll_adjust)
675 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
676
a29c7ea6
ZD
677 /* Skip big loops. */
678 if (nunroll <= 1)
679 {
c263766c
RH
680 if (dump_file)
681 fprintf (dump_file, ";; Not considering loop, is too big\n");
a29c7ea6
ZD
682 return;
683 }
684
685 /* Check for simple loops. */
50654f6c 686 desc = get_simple_loop_desc (loop);
a29c7ea6
ZD
687
688 /* Check simpleness. */
50654f6c 689 if (!desc->simple_p || desc->assumptions)
a29c7ea6 690 {
c263766c
RH
691 if (dump_file)
692 fprintf (dump_file,
693 ";; Unable to prove that the number of iterations "
694 "can be counted in runtime\n");
a29c7ea6
ZD
695 return;
696 }
697
50654f6c 698 if (desc->const_iter)
a29c7ea6 699 {
c263766c
RH
700 if (dump_file)
701 fprintf (dump_file, ";; Loop iterates constant times\n");
a29c7ea6
ZD
702 return;
703 }
704
73367f92 705 /* Check whether the loop rolls. */
71343877 706 if ((get_estimated_loop_iterations (loop, &iterations)
8c383600 707 || get_likely_max_loop_iterations (loop, &iterations))
807e902e 708 && wi::ltu_p (iterations, 2 * nunroll))
a29c7ea6 709 {
c263766c
RH
710 if (dump_file)
711 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
a29c7ea6
ZD
712 return;
713 }
714
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. */
50654f6c
ZD
717 for (i = 1; 2 * i <= nunroll; i *= 2)
718 continue;
a29c7ea6
ZD
719
720 loop->lpt_decision.decision = LPT_UNROLL_RUNTIME;
721 loop->lpt_decision.times = i - 1;
722}
723
7d93d987
ZD
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. */
598ec7bd
ZD
727
728basic_block
95ecfb26 729split_edge_and_insert (edge e, rtx_insn *insns)
598ec7bd 730{
7d93d987
ZD
731 basic_block bb;
732
733 if (!insns)
734 return NULL;
b8698a0f 735 bb = split_edge (e);
598ec7bd 736 emit_insn_after (insns, BB_END (bb));
7984c787
SB
737
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,
3bea341f 743 the verify_flow_info at the end of the RTL loop passes would fail.
7984c787
SB
744
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:
750
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.
754
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.
761
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. */
767
598ec7bd
ZD
768 return bb;
769}
770
da4cfeac
RB
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. */
774
95ecfb26 775static rtx_insn *
1476d1bd
MM
776compare_and_jump_seq (rtx op0, rtx op1, enum rtx_code comp,
777 rtx_code_label *label, int prob, rtx_insn *cinsn)
da4cfeac 778{
1476d1bd
MM
779 rtx_insn *seq;
780 rtx_jump_insn *jump;
95ecfb26 781 rtx cond;
ef4bddc2 782 machine_mode mode;
da4cfeac
RB
783
784 mode = GET_MODE (op0);
785 if (mode == VOIDmode)
786 mode = GET_MODE (op1);
787
788 start_sequence ();
789 if (GET_MODE_CLASS (mode) == MODE_CC)
790 {
791 /* A hack -- there seems to be no easy generic way how to make a
792 conditional jump from a ccmode comparison. */
793 gcc_assert (cinsn);
794 cond = XEXP (SET_SRC (pc_set (cinsn)), 0);
795 gcc_assert (GET_CODE (cond) == comp);
796 gcc_assert (rtx_equal_p (op0, XEXP (cond, 0)));
797 gcc_assert (rtx_equal_p (op1, XEXP (cond, 1)));
798 emit_jump_insn (copy_insn (PATTERN (cinsn)));
1476d1bd 799 jump = as_a <rtx_jump_insn *> (get_last_insn ());
da4cfeac
RB
800 JUMP_LABEL (jump) = JUMP_LABEL (cinsn);
801 LABEL_NUSES (JUMP_LABEL (jump))++;
802 redirect_jump (jump, label, 0);
803 }
804 else
805 {
806 gcc_assert (!cinsn);
807
808 op0 = force_operand (op0, NULL_RTX);
809 op1 = force_operand (op1, NULL_RTX);
810 do_compare_rtx_and_jump (op0, op1, comp, 0,
1476d1bd
MM
811 mode, NULL_RTX, NULL, label, -1);
812 jump = as_a <rtx_jump_insn *> (get_last_insn ());
813 jump->set_jump_target (label);
da4cfeac
RB
814 LABEL_NUSES (label)++;
815 }
816 add_int_reg_note (jump, REG_BR_PROB, prob);
817
818 seq = get_insns ();
819 end_sequence ();
820
821 return seq;
822}
823
4fc2e37d
EB
824/* Unroll LOOP for which we are able to count number of iterations in runtime
825 LOOP->LPT_DECISION.TIMES times. The transformation does this (with some
a29c7ea6 826 extra care for case n < 0):
0c20a65f 827
a29c7ea6
ZD
828 for (i = 0; i < n; i++)
829 body;
0c20a65f 830
4fc2e37d 831 ==> (LOOP->LPT_DECISION.TIMES == 3)
0c20a65f 832
a29c7ea6
ZD
833 i = 0;
834 mod = n % 4;
0c20a65f 835
a29c7ea6
ZD
836 switch (mod)
837 {
838 case 3:
839 body; i++;
840 case 2:
841 body; i++;
842 case 1:
843 body; i++;
844 case 0: ;
845 }
0c20a65f 846
a29c7ea6
ZD
847 while (i < n)
848 {
849 body; i++;
850 body; i++;
851 body; i++;
852 body; i++;
853 }
854 */
855static void
d73be268 856unroll_loop_runtime_iterations (struct loop *loop)
a29c7ea6 857{
95ecfb26
DM
858 rtx old_niter, niter, tmp;
859 rtx_insn *init_code, *branch_code;
a29c7ea6 860 unsigned i, j, p;
66f97d31 861 basic_block preheader, *body, swtch, ezc_swtch;
a29c7ea6 862 int may_exit_copy;
ee8c1b05 863 unsigned n_peel;
ee8c1b05 864 edge e;
a29c7ea6
ZD
865 bool extra_zero_check, last_may_exit;
866 unsigned max_unroll = loop->lpt_decision.times;
50654f6c
ZD
867 struct niter_desc *desc = get_simple_loop_desc (loop);
868 bool exit_at_end = loop_exit_at_end_p (loop);
f37a4f14 869 struct opt_info *opt_info = NULL;
41806d92 870 bool ok;
b8698a0f 871
f37a4f14
RE
872 if (flag_split_ivs_in_unroller
873 || flag_variable_expansion_in_unroller)
874 opt_info = analyze_insns_in_loop (loop);
b8698a0f 875
a29c7ea6 876 /* Remember blocks whose dominators will have to be updated. */
ef062b13 877 auto_vec<basic_block> dom_bbs;
a29c7ea6
ZD
878
879 body = get_loop_body (loop);
880 for (i = 0; i < loop->num_nodes; i++)
881 {
9771b263 882 vec<basic_block> ldom;
66f97d31 883 basic_block bb;
a29c7ea6 884
66f97d31 885 ldom = get_dominated_by (CDI_DOMINATORS, body[i]);
9771b263 886 FOR_EACH_VEC_ELT (ldom, j, bb)
66f97d31 887 if (!flow_bb_inside_loop_p (loop, bb))
9771b263 888 dom_bbs.safe_push (bb);
a29c7ea6 889
9771b263 890 ldom.release ();
a29c7ea6
ZD
891 }
892 free (body);
893
50654f6c 894 if (!exit_at_end)
a29c7ea6
ZD
895 {
896 /* Leave exit in first copy (for explanation why see comment in
897 unroll_loop_constant_iterations). */
898 may_exit_copy = 0;
899 n_peel = max_unroll - 1;
900 extra_zero_check = true;
901 last_may_exit = false;
902 }
903 else
904 {
905 /* Leave exit in last copy (for explanation why see comment in
906 unroll_loop_constant_iterations). */
907 may_exit_copy = max_unroll;
908 n_peel = max_unroll;
909 extra_zero_check = false;
910 last_may_exit = true;
911 }
912
913 /* Get expression for number of iterations. */
914 start_sequence ();
50654f6c
ZD
915 old_niter = niter = gen_reg_rtx (desc->mode);
916 tmp = force_operand (copy_rtx (desc->niter_expr), niter);
917 if (tmp != niter)
918 emit_move_insn (niter, tmp);
a29c7ea6
ZD
919
920 /* Count modulo by ANDing it with max_unroll; we use the fact that
921 the number of unrollings is a power of two, and thus this is correct
922 even if there is overflow in the computation. */
50654f6c 923 niter = expand_simple_binop (desc->mode, AND,
2f1cd2eb 924 niter, gen_int_mode (max_unroll, desc->mode),
a29c7ea6
ZD
925 NULL_RTX, 0, OPTAB_LIB_WIDEN);
926
927 init_code = get_insns ();
928 end_sequence ();
2ed22578 929 unshare_all_rtl_in_chain (init_code);
a29c7ea6
ZD
930
931 /* Precondition the loop. */
598ec7bd 932 split_edge_and_insert (loop_preheader_edge (loop), init_code);
a29c7ea6 933
ef062b13 934 auto_vec<edge> remove_edges;
a29c7ea6 935
7ba9e72d 936 auto_sbitmap wont_exit (max_unroll + 2);
a29c7ea6
ZD
937
938 /* Peel the first copy of loop body (almost always we must leave exit test
939 here; the only exception is when we have extra zero check and the number
50654f6c
ZD
940 of iterations is reliable. Also record the place of (possible) extra
941 zero check. */
f61e445a 942 bitmap_clear (wont_exit);
50654f6c
ZD
943 if (extra_zero_check
944 && !desc->noloop_assumptions)
d7c028c0 945 bitmap_set_bit (wont_exit, 1);
a29c7ea6 946 ezc_swtch = loop_preheader_edge (loop)->src;
41806d92 947 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
d73be268 948 1, wont_exit, desc->out_edge,
ee8c1b05 949 &remove_edges,
41806d92
NS
950 DLTHE_FLAG_UPDATE_FREQ);
951 gcc_assert (ok);
a29c7ea6
ZD
952
953 /* Record the place where switch will be built for preconditioning. */
598ec7bd 954 swtch = split_edge (loop_preheader_edge (loop));
a29c7ea6
ZD
955
956 for (i = 0; i < n_peel; i++)
957 {
958 /* Peel the copy. */
f61e445a 959 bitmap_clear (wont_exit);
a29c7ea6 960 if (i != n_peel - 1 || !last_may_exit)
d7c028c0 961 bitmap_set_bit (wont_exit, 1);
41806d92 962 ok = duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
d73be268 963 1, wont_exit, desc->out_edge,
ee8c1b05 964 &remove_edges,
41806d92
NS
965 DLTHE_FLAG_UPDATE_FREQ);
966 gcc_assert (ok);
a29c7ea6 967
91f4cfe3
ZD
968 /* Create item for switch. */
969 j = n_peel - i - (extra_zero_check ? 0 : 1);
970 p = REG_BR_PROB_BASE / (i + 2);
971
598ec7bd 972 preheader = split_edge (loop_preheader_edge (loop));
50654f6c 973 branch_code = compare_and_jump_seq (copy_rtx (niter), GEN_INT (j), EQ,
41806d92 974 block_label (preheader), p,
95ecfb26 975 NULL);
91f4cfe3 976
7d93d987
ZD
977 /* We rely on the fact that the compare and jump cannot be optimized out,
978 and hence the cfg we create is correct. */
979 gcc_assert (branch_code != NULL_RTX);
980
598ec7bd 981 swtch = split_edge_and_insert (single_pred_edge (swtch), branch_code);
d47cc544 982 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
f335184d 983 single_succ_edge (swtch)->probability = REG_BR_PROB_BASE - p;
91f4cfe3 984 e = make_edge (swtch, preheader,
c5cbcccf 985 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
e3a8f1fa 986 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
91f4cfe3 987 e->probability = p;
a29c7ea6
ZD
988 }
989
990 if (extra_zero_check)
991 {
992 /* Add branch for zero iterations. */
993 p = REG_BR_PROB_BASE / (max_unroll + 1);
994 swtch = ezc_swtch;
598ec7bd 995 preheader = split_edge (loop_preheader_edge (loop));
50654f6c 996 branch_code = compare_and_jump_seq (copy_rtx (niter), const0_rtx, EQ,
41806d92 997 block_label (preheader), p,
95ecfb26 998 NULL);
7d93d987 999 gcc_assert (branch_code != NULL_RTX);
a29c7ea6 1000
598ec7bd 1001 swtch = split_edge_and_insert (single_succ_edge (swtch), branch_code);
d47cc544 1002 set_immediate_dominator (CDI_DOMINATORS, preheader, swtch);
c5cbcccf 1003 single_succ_edge (swtch)->probability = REG_BR_PROB_BASE - p;
72b8d451 1004 e = make_edge (swtch, preheader,
c5cbcccf 1005 single_succ_edge (swtch)->flags & EDGE_IRREDUCIBLE_LOOP);
e3a8f1fa 1006 e->count = RDIV (preheader->count * REG_BR_PROB_BASE, p);
a29c7ea6
ZD
1007 e->probability = p;
1008 }
1009
1010 /* Recount dominators for outer blocks. */
66f97d31 1011 iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, false);
a29c7ea6
ZD
1012
1013 /* And unroll loop. */
1014
f61e445a 1015 bitmap_ones (wont_exit);
d7c028c0 1016 bitmap_clear_bit (wont_exit, may_exit_copy);
f37a4f14 1017 opt_info_start_duplication (opt_info);
b8698a0f 1018
41806d92 1019 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
d73be268 1020 max_unroll,
41806d92 1021 wont_exit, desc->out_edge,
ee8c1b05 1022 &remove_edges,
7f7b1718
JH
1023 DLTHE_FLAG_UPDATE_FREQ
1024 | (opt_info
1025 ? DLTHE_RECORD_COPY_NUMBER
1026 : 0));
41806d92 1027 gcc_assert (ok);
b8698a0f 1028
f37a4f14 1029 if (opt_info)
113d659a 1030 {
f37a4f14
RE
1031 apply_opt_in_copies (opt_info, max_unroll, true, true);
1032 free_opt_info (opt_info);
113d659a
ZD
1033 }
1034
50654f6c
ZD
1035 if (exit_at_end)
1036 {
6580ee77 1037 basic_block exit_block = get_bb_copy (desc->in_edge->src);
41806d92
NS
1038 /* Find a new in and out edge; they are in the last copy we have
1039 made. */
b8698a0f 1040
628f6a4e 1041 if (EDGE_SUCC (exit_block, 0)->dest == desc->out_edge->dest)
50654f6c 1042 {
628f6a4e
BE
1043 desc->out_edge = EDGE_SUCC (exit_block, 0);
1044 desc->in_edge = EDGE_SUCC (exit_block, 1);
50654f6c
ZD
1045 }
1046 else
1047 {
628f6a4e
BE
1048 desc->out_edge = EDGE_SUCC (exit_block, 1);
1049 desc->in_edge = EDGE_SUCC (exit_block, 0);
50654f6c
ZD
1050 }
1051 }
1052
a29c7ea6 1053 /* Remove the edges. */
9771b263 1054 FOR_EACH_VEC_ELT (remove_edges, i, e)
ee8c1b05 1055 remove_path (e);
a29c7ea6 1056
50654f6c
ZD
1057 /* We must be careful when updating the number of iterations due to
1058 preconditioning and the fact that the value must be valid at entry
1059 of the loop. After passing through the above code, we see that
1060 the correct new number of iterations is this: */
113d659a 1061 gcc_assert (!desc->const_iter);
50654f6c 1062 desc->niter_expr =
41806d92 1063 simplify_gen_binary (UDIV, desc->mode, old_niter,
69a59f0f 1064 gen_int_mode (max_unroll + 1, desc->mode));
e3a8f1fa 1065 loop->nb_iterations_upper_bound
807e902e 1066 = wi::udiv_trunc (loop->nb_iterations_upper_bound, max_unroll + 1);
e3a8f1fa
JH
1067 if (loop->any_estimate)
1068 loop->nb_iterations_estimate
807e902e 1069 = wi::udiv_trunc (loop->nb_iterations_estimate, max_unroll + 1);
105e29c5
JH
1070 if (loop->any_likely_upper_bound)
1071 loop->nb_iterations_likely_upper_bound
1072 = wi::udiv_trunc (loop->nb_iterations_likely_upper_bound, max_unroll + 1);
50654f6c
ZD
1073 if (exit_at_end)
1074 {
1075 desc->niter_expr =
1076 simplify_gen_binary (MINUS, desc->mode, desc->niter_expr, const1_rtx);
1077 desc->noloop_assumptions = NULL_RTX;
e3a8f1fa
JH
1078 --loop->nb_iterations_upper_bound;
1079 if (loop->any_estimate
807e902e 1080 && loop->nb_iterations_estimate != 0)
e3a8f1fa
JH
1081 --loop->nb_iterations_estimate;
1082 else
1083 loop->any_estimate = false;
105e29c5
JH
1084 if (loop->any_likely_upper_bound
1085 && loop->nb_iterations_likely_upper_bound != 0)
1086 --loop->nb_iterations_likely_upper_bound;
1087 else
1088 loop->any_likely_upper_bound = false;
50654f6c
ZD
1089 }
1090
c263766c
RH
1091 if (dump_file)
1092 fprintf (dump_file,
1093 ";; Unrolled loop %d times, counting # of iterations "
1094 "in runtime, %i insns\n",
a29c7ea6
ZD
1095 max_unroll, num_loop_insns (loop));
1096}
0c20a65f 1097
a29c7ea6
ZD
1098/* Decide whether to unroll LOOP stupidly and how much. */
1099static void
d47cc544 1100decide_unroll_stupid (struct loop *loop, int flags)
a29c7ea6
ZD
1101{
1102 unsigned nunroll, nunroll_by_av, i;
50654f6c 1103 struct niter_desc *desc;
807e902e 1104 widest_int iterations;
a29c7ea6
ZD
1105
1106 if (!(flags & UAP_UNROLL_ALL))
1107 {
1108 /* We were not asked to, just return back silently. */
1109 return;
1110 }
1111
c263766c
RH
1112 if (dump_file)
1113 fprintf (dump_file, "\n;; Considering unrolling loop stupidly\n");
a29c7ea6
ZD
1114
1115 /* nunroll = total number of copies of the original loop body in
1116 unrolled loop (i.e. if it is 2, we have to duplicate loop body once. */
1117 nunroll = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / loop->ninsns;
c263766c
RH
1118 nunroll_by_av
1119 = PARAM_VALUE (PARAM_MAX_AVERAGE_UNROLLED_INSNS) / loop->av_ninsns;
a29c7ea6
ZD
1120 if (nunroll > nunroll_by_av)
1121 nunroll = nunroll_by_av;
1122 if (nunroll > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLL_TIMES))
1123 nunroll = PARAM_VALUE (PARAM_MAX_UNROLL_TIMES);
1124
40ac4f73
CB
1125 if (targetm.loop_unroll_adjust)
1126 nunroll = targetm.loop_unroll_adjust (nunroll, loop);
1127
a29c7ea6
ZD
1128 /* Skip big loops. */
1129 if (nunroll <= 1)
1130 {
c263766c
RH
1131 if (dump_file)
1132 fprintf (dump_file, ";; Not considering loop, is too big\n");
a29c7ea6
ZD
1133 return;
1134 }
1135
1136 /* Check for simple loops. */
50654f6c 1137 desc = get_simple_loop_desc (loop);
a29c7ea6
ZD
1138
1139 /* Check simpleness. */
50654f6c 1140 if (desc->simple_p && !desc->assumptions)
a29c7ea6 1141 {
c263766c
RH
1142 if (dump_file)
1143 fprintf (dump_file, ";; The loop is simple\n");
a29c7ea6
ZD
1144 return;
1145 }
1146
1147 /* Do not unroll loops with branches inside -- it increases number
6acf25e4
JH
1148 of mispredicts.
1149 TODO: this heuristic needs tunning; call inside the loop body
1150 is also relatively good reason to not unroll. */
50654f6c 1151 if (num_loop_branches (loop) > 1)
a29c7ea6 1152 {
c263766c
RH
1153 if (dump_file)
1154 fprintf (dump_file, ";; Not unrolling, contains branches\n");
a29c7ea6
ZD
1155 return;
1156 }
1157
73367f92 1158 /* Check whether the loop rolls. */
71343877 1159 if ((get_estimated_loop_iterations (loop, &iterations)
8c383600 1160 || get_likely_max_loop_iterations (loop, &iterations))
807e902e 1161 && wi::ltu_p (iterations, 2 * nunroll))
a29c7ea6 1162 {
c263766c
RH
1163 if (dump_file)
1164 fprintf (dump_file, ";; Not unrolling loop, doesn't roll\n");
a29c7ea6
ZD
1165 return;
1166 }
1167
1168 /* Success. Now force nunroll to be power of 2, as it seems that this
e0bb17a8 1169 improves results (partially because of better alignments, partially
a29c7ea6 1170 because of some dark magic). */
50654f6c
ZD
1171 for (i = 1; 2 * i <= nunroll; i *= 2)
1172 continue;
a29c7ea6
ZD
1173
1174 loop->lpt_decision.decision = LPT_UNROLL_STUPID;
1175 loop->lpt_decision.times = i - 1;
1176}
1177
4fc2e37d
EB
1178/* Unroll a LOOP LOOP->LPT_DECISION.TIMES times. The transformation does this:
1179
a29c7ea6
ZD
1180 while (cond)
1181 body;
1182
4fc2e37d 1183 ==> (LOOP->LPT_DECISION.TIMES == 3)
a29c7ea6
ZD
1184
1185 while (cond)
1186 {
1187 body;
1188 if (!cond) break;
1189 body;
1190 if (!cond) break;
1191 body;
1192 if (!cond) break;
1193 body;
1194 }
1195 */
1196static void
d73be268 1197unroll_loop_stupid (struct loop *loop)
a29c7ea6 1198{
a29c7ea6 1199 unsigned nunroll = loop->lpt_decision.times;
50654f6c 1200 struct niter_desc *desc = get_simple_loop_desc (loop);
f37a4f14 1201 struct opt_info *opt_info = NULL;
41806d92 1202 bool ok;
b8698a0f 1203
f37a4f14
RE
1204 if (flag_split_ivs_in_unroller
1205 || flag_variable_expansion_in_unroller)
1206 opt_info = analyze_insns_in_loop (loop);
b8698a0f 1207
7ba9e72d 1208 auto_sbitmap wont_exit (nunroll + 1);
f61e445a 1209 bitmap_clear (wont_exit);
f37a4f14 1210 opt_info_start_duplication (opt_info);
b8698a0f 1211
41806d92 1212 ok = duplicate_loop_to_header_edge (loop, loop_latch_edge (loop),
d73be268 1213 nunroll, wont_exit,
ee8c1b05 1214 NULL, NULL,
7f7b1718
JH
1215 DLTHE_FLAG_UPDATE_FREQ
1216 | (opt_info
1217 ? DLTHE_RECORD_COPY_NUMBER
1218 : 0));
41806d92 1219 gcc_assert (ok);
b8698a0f 1220
f37a4f14 1221 if (opt_info)
113d659a 1222 {
f37a4f14
RE
1223 apply_opt_in_copies (opt_info, nunroll, true, true);
1224 free_opt_info (opt_info);
113d659a
ZD
1225 }
1226
50654f6c
ZD
1227 if (desc->simple_p)
1228 {
1229 /* We indeed may get here provided that there are nontrivial assumptions
1230 for a loop to be really simple. We could update the counts, but the
1231 problem is that we are unable to decide which exit will be taken
1232 (not really true in case the number of iterations is constant,
1aa95df7 1233 but no one will do anything with this information, so we do not
50654f6c
ZD
1234 worry about it). */
1235 desc->simple_p = false;
1236 }
1237
c263766c
RH
1238 if (dump_file)
1239 fprintf (dump_file, ";; Unrolled loop %d times, %i insns\n",
a29c7ea6
ZD
1240 nunroll, num_loop_insns (loop));
1241}
113d659a 1242
60c48e4c
AO
1243/* Returns true if REG is referenced in one nondebug insn in LOOP.
1244 Set *DEBUG_USES to the number of debug insns that reference the
1245 variable. */
f37a4f14 1246
dd637013 1247static bool
60c48e4c
AO
1248referenced_in_one_insn_in_loop_p (struct loop *loop, rtx reg,
1249 int *debug_uses)
f37a4f14
RE
1250{
1251 basic_block *body, bb;
1252 unsigned i;
1253 int count_ref = 0;
95ecfb26 1254 rtx_insn *insn;
b8698a0f
L
1255
1256 body = get_loop_body (loop);
f37a4f14
RE
1257 for (i = 0; i < loop->num_nodes; i++)
1258 {
1259 bb = body[i];
b8698a0f 1260
f37a4f14 1261 FOR_BB_INSNS (bb, insn)
60c48e4c
AO
1262 if (!rtx_referenced_p (reg, insn))
1263 continue;
1264 else if (DEBUG_INSN_P (insn))
1265 ++*debug_uses;
1266 else if (++count_ref > 1)
1267 break;
f37a4f14 1268 }
60c48e4c 1269 free (body);
f37a4f14
RE
1270 return (count_ref == 1);
1271}
1272
60c48e4c
AO
1273/* Reset the DEBUG_USES debug insns in LOOP that reference REG. */
1274
1275static void
1276reset_debug_uses_in_loop (struct loop *loop, rtx reg, int debug_uses)
1277{
1278 basic_block *body, bb;
1279 unsigned i;
95ecfb26 1280 rtx_insn *insn;
60c48e4c
AO
1281
1282 body = get_loop_body (loop);
1283 for (i = 0; debug_uses && i < loop->num_nodes; i++)
1284 {
1285 bb = body[i];
1286
1287 FOR_BB_INSNS (bb, insn)
1288 if (!DEBUG_INSN_P (insn) || !rtx_referenced_p (reg, insn))
1289 continue;
1290 else
1291 {
1292 validate_change (insn, &INSN_VAR_LOCATION_LOC (insn),
1293 gen_rtx_UNKNOWN_VAR_LOC (), 0);
1294 if (!--debug_uses)
1295 break;
1296 }
1297 }
1298 free (body);
1299}
1300
f37a4f14 1301/* Determine whether INSN contains an accumulator
b8698a0f 1302 which can be expanded into separate copies,
f37a4f14 1303 one for each copy of the LOOP body.
b8698a0f 1304
f37a4f14
RE
1305 for (i = 0 ; i < n; i++)
1306 sum += a[i];
b8698a0f 1307
f37a4f14 1308 ==>
b8698a0f 1309
f37a4f14
RE
1310 sum += a[i]
1311 ....
1312 i = i+1;
1313 sum1 += a[i]
1314 ....
1315 i = i+1
1316 sum2 += a[i];
1317 ....
1318
b8698a0f
L
1319 Return NULL if INSN contains no opportunity for expansion of accumulator.
1320 Otherwise, allocate a VAR_TO_EXPAND structure, fill it with the relevant
f37a4f14
RE
1321 information and return a pointer to it.
1322*/
1323
1324static struct var_to_expand *
95ecfb26 1325analyze_insn_to_expand_var (struct loop *loop, rtx_insn *insn)
f37a4f14 1326{
531e5376 1327 rtx set, dest, src;
f37a4f14 1328 struct var_to_expand *ves;
76fd2caa 1329 unsigned accum_pos;
531e5376 1330 enum rtx_code code;
60c48e4c 1331 int debug_uses = 0;
76fd2caa 1332
f37a4f14
RE
1333 set = single_set (insn);
1334 if (!set)
1335 return NULL;
b8698a0f 1336
f37a4f14
RE
1337 dest = SET_DEST (set);
1338 src = SET_SRC (set);
531e5376 1339 code = GET_CODE (src);
b8698a0f 1340
531e5376 1341 if (code != PLUS && code != MINUS && code != MULT && code != FMA)
f37a4f14 1342 return NULL;
f2dd440f 1343
531e5376
RH
1344 if (FLOAT_MODE_P (GET_MODE (dest)))
1345 {
1346 if (!flag_associative_math)
1347 return NULL;
1348 /* In the case of FMA, we're also changing the rounding. */
1349 if (code == FMA && !flag_unsafe_math_optimizations)
1350 return NULL;
1351 }
1352
f2dd440f
SB
1353 /* Hmm, this is a bit paradoxical. We know that INSN is a valid insn
1354 in MD. But if there is no optab to generate the insn, we can not
1355 perform the variable expansion. This can happen if an MD provides
1356 an insn but not a named pattern to generate it, for example to avoid
1357 producing code that needs additional mode switches like for x87/mmx.
1358
1359 So we check have_insn_for which looks for an optab for the operation
1360 in SRC. If it doesn't exist, we can't perform the expansion even
1361 though INSN is valid. */
531e5376 1362 if (!have_insn_for (code, GET_MODE (src)))
f2dd440f
SB
1363 return NULL;
1364
f37a4f14
RE
1365 if (!REG_P (dest)
1366 && !(GET_CODE (dest) == SUBREG
1367 && REG_P (SUBREG_REG (dest))))
1368 return NULL;
b8698a0f 1369
531e5376
RH
1370 /* Find the accumulator use within the operation. */
1371 if (code == FMA)
1372 {
1373 /* We only support accumulation via FMA in the ADD position. */
1374 if (!rtx_equal_p (dest, XEXP (src, 2)))
1375 return NULL;
1376 accum_pos = 2;
1377 }
1378 else if (rtx_equal_p (dest, XEXP (src, 0)))
76fd2caa 1379 accum_pos = 0;
531e5376
RH
1380 else if (rtx_equal_p (dest, XEXP (src, 1)))
1381 {
1382 /* The method of expansion that we are using; which includes the
1383 initialization of the expansions with zero and the summation of
1384 the expansions at the end of the computation will yield wrong
1385 results for (x = something - x) thus avoid using it in that case. */
1386 if (code == MINUS)
1387 return NULL;
1388 accum_pos = 1;
1389 }
76fd2caa
RE
1390 else
1391 return NULL;
1392
531e5376
RH
1393 /* It must not otherwise be used. */
1394 if (code == FMA)
1395 {
1396 if (rtx_referenced_p (dest, XEXP (src, 0))
1397 || rtx_referenced_p (dest, XEXP (src, 1)))
1398 return NULL;
1399 }
1400 else if (rtx_referenced_p (dest, XEXP (src, 1 - accum_pos)))
f37a4f14 1401 return NULL;
b8698a0f 1402
531e5376 1403 /* It must be used in exactly one insn. */
60c48e4c 1404 if (!referenced_in_one_insn_in_loop_p (loop, dest, &debug_uses))
f37a4f14 1405 return NULL;
b8698a0f 1406
c1c5a431 1407 if (dump_file)
531e5376
RH
1408 {
1409 fprintf (dump_file, "\n;; Expanding Accumulator ");
1410 print_rtl (dump_file, dest);
1411 fprintf (dump_file, "\n");
1412 }
c1c5a431 1413
60c48e4c
AO
1414 if (debug_uses)
1415 /* Instead of resetting the debug insns, we could replace each
1416 debug use in the loop with the sum or product of all expanded
1417 accummulators. Since we'll only know of all expansions at the
1418 end, we'd have to keep track of which vars_to_expand a debug
1419 insn in the loop references, take note of each copy of the
1420 debug insn during unrolling, and when it's all done, compute
1421 the sum or product of each variable and adjust the original
1422 debug insn and each copy thereof. What a pain! */
1423 reset_debug_uses_in_loop (loop, dest, debug_uses);
1424
f37a4f14 1425 /* Record the accumulator to expand. */
5ed6ace5 1426 ves = XNEW (struct var_to_expand);
f37a4f14 1427 ves->insn = insn;
f37a4f14 1428 ves->reg = copy_rtx (dest);
9771b263 1429 ves->var_expansions.create (1);
a9f6ecee 1430 ves->next = NULL;
f37a4f14
RE
1431 ves->op = GET_CODE (src);
1432 ves->expansion_count = 0;
1433 ves->reuse_expansion = 0;
b8698a0f 1434 return ves;
f37a4f14
RE
1435}
1436
113d659a 1437/* Determine whether there is an induction variable in INSN that
b8698a0f 1438 we would like to split during unrolling.
f37a4f14
RE
1439
1440 I.e. replace
1441
1442 i = i + 1;
1443 ...
1444 i = i + 1;
1445 ...
1446 i = i + 1;
1447 ...
1448
1449 type chains by
1450
1451 i0 = i + 1
1452 ...
1453 i = i0 + 1
1454 ...
1455 i = i0 + 2
1456 ...
1457
b8698a0f 1458 Return NULL if INSN contains no interesting IVs. Otherwise, allocate
f37a4f14 1459 an IV_TO_SPLIT structure, fill it with the relevant information and return a
113d659a
ZD
1460 pointer to it. */
1461
1462static struct iv_to_split *
1b20d55a 1463analyze_iv_to_split_insn (rtx_insn *insn)
113d659a
ZD
1464{
1465 rtx set, dest;
1466 struct rtx_iv iv;
1467 struct iv_to_split *ivts;
41806d92 1468 bool ok;
113d659a
ZD
1469
1470 /* For now we just split the basic induction variables. Later this may be
1471 extended for example by selecting also addresses of memory references. */
1472 set = single_set (insn);
1473 if (!set)
1474 return NULL;
1475
1476 dest = SET_DEST (set);
1477 if (!REG_P (dest))
1478 return NULL;
1479
1480 if (!biv_p (insn, dest))
1481 return NULL;
1482
03fd2215 1483 ok = iv_analyze_result (insn, dest, &iv);
4dc7782d
JL
1484
1485 /* This used to be an assert under the assumption that if biv_p returns
1486 true that iv_analyze_result must also return true. However, that
1487 assumption is not strictly correct as evidenced by pr25569.
1488
1489 Returning NULL when iv_analyze_result returns false is safe and
1490 avoids the problems in pr25569 until the iv_analyze_* routines
1491 can be fixed, which is apparently hard and time consuming
1492 according to their author. */
1493 if (! ok)
1494 return NULL;
113d659a
ZD
1495
1496 if (iv.step == const0_rtx
1497 || iv.mode != iv.extend_mode)
1498 return NULL;
1499
1500 /* Record the insn to split. */
5ed6ace5 1501 ivts = XNEW (struct iv_to_split);
113d659a 1502 ivts->insn = insn;
4a0c3fde 1503 ivts->orig_var = dest;
113d659a
ZD
1504 ivts->base_var = NULL_RTX;
1505 ivts->step = iv.step;
a9f6ecee 1506 ivts->next = NULL;
b8698a0f 1507
113d659a
ZD
1508 return ivts;
1509}
1510
f37a4f14
RE
1511/* Determines which of insns in LOOP can be optimized.
1512 Return a OPT_INFO struct with the relevant hash tables filled
1513 with all insns to be optimized. The FIRST_NEW_BLOCK field
113d659a
ZD
1514 is undefined for the return value. */
1515
f37a4f14
RE
1516static struct opt_info *
1517analyze_insns_in_loop (struct loop *loop)
113d659a
ZD
1518{
1519 basic_block *body, bb;
ca83d385 1520 unsigned i;
5ed6ace5 1521 struct opt_info *opt_info = XCNEW (struct opt_info);
1b20d55a 1522 rtx_insn *insn;
f37a4f14
RE
1523 struct iv_to_split *ivts = NULL;
1524 struct var_to_expand *ves = NULL;
4a8fb1a1
LC
1525 iv_to_split **slot1;
1526 var_to_expand **slot2;
9771b263 1527 vec<edge> edges = get_loop_exit_edges (loop);
ca83d385 1528 edge exit;
f37a4f14 1529 bool can_apply = false;
b8698a0f 1530
113d659a
ZD
1531 iv_analysis_loop_init (loop);
1532
1533 body = get_loop_body (loop);
f37a4f14
RE
1534
1535 if (flag_split_ivs_in_unroller)
a9f6ecee 1536 {
c203e8a7
TS
1537 opt_info->insns_to_split
1538 = new hash_table<iv_split_hasher> (5 * loop->num_nodes);
a9f6ecee
AO
1539 opt_info->iv_to_split_head = NULL;
1540 opt_info->iv_to_split_tail = &opt_info->iv_to_split_head;
1541 }
b8698a0f 1542
f37a4f14 1543 /* Record the loop exit bb and loop preheader before the unrolling. */
598ec7bd 1544 opt_info->loop_preheader = loop_preheader_edge (loop)->src;
b8698a0f 1545
9771b263 1546 if (edges.length () == 1)
f37a4f14 1547 {
9771b263 1548 exit = edges[0];
ca83d385
ZD
1549 if (!(exit->flags & EDGE_COMPLEX))
1550 {
1551 opt_info->loop_exit = split_edge (exit);
1552 can_apply = true;
1553 }
f37a4f14 1554 }
b8698a0f 1555
f37a4f14
RE
1556 if (flag_variable_expansion_in_unroller
1557 && can_apply)
a9f6ecee 1558 {
c203e8a7
TS
1559 opt_info->insns_with_var_to_expand
1560 = new hash_table<var_expand_hasher> (5 * loop->num_nodes);
a9f6ecee
AO
1561 opt_info->var_to_expand_head = NULL;
1562 opt_info->var_to_expand_tail = &opt_info->var_to_expand_head;
1563 }
b8698a0f 1564
113d659a
ZD
1565 for (i = 0; i < loop->num_nodes; i++)
1566 {
1567 bb = body[i];
1568 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1569 continue;
1570
1571 FOR_BB_INSNS (bb, insn)
f37a4f14
RE
1572 {
1573 if (!INSN_P (insn))
1574 continue;
b8698a0f 1575
c203e8a7 1576 if (opt_info->insns_to_split)
f37a4f14 1577 ivts = analyze_iv_to_split_insn (insn);
b8698a0f 1578
f37a4f14
RE
1579 if (ivts)
1580 {
c203e8a7 1581 slot1 = opt_info->insns_to_split->find_slot (ivts, INSERT);
a9f6ecee 1582 gcc_assert (*slot1 == NULL);
f37a4f14 1583 *slot1 = ivts;
a9f6ecee
AO
1584 *opt_info->iv_to_split_tail = ivts;
1585 opt_info->iv_to_split_tail = &ivts->next;
f37a4f14
RE
1586 continue;
1587 }
b8698a0f 1588
c203e8a7 1589 if (opt_info->insns_with_var_to_expand)
f37a4f14 1590 ves = analyze_insn_to_expand_var (loop, insn);
b8698a0f 1591
f37a4f14
RE
1592 if (ves)
1593 {
c203e8a7 1594 slot2 = opt_info->insns_with_var_to_expand->find_slot (ves, INSERT);
a9f6ecee 1595 gcc_assert (*slot2 == NULL);
f37a4f14 1596 *slot2 = ves;
a9f6ecee
AO
1597 *opt_info->var_to_expand_tail = ves;
1598 opt_info->var_to_expand_tail = &ves->next;
f37a4f14
RE
1599 }
1600 }
113d659a 1601 }
b8698a0f 1602
9771b263 1603 edges.release ();
113d659a 1604 free (body);
f37a4f14 1605 return opt_info;
113d659a
ZD
1606}
1607
1608/* Called just before loop duplication. Records start of duplicated area
f37a4f14 1609 to OPT_INFO. */
113d659a 1610
b8698a0f 1611static void
f37a4f14 1612opt_info_start_duplication (struct opt_info *opt_info)
113d659a 1613{
f37a4f14 1614 if (opt_info)
8b1c6fd7 1615 opt_info->first_new_block = last_basic_block_for_fn (cfun);
113d659a
ZD
1616}
1617
1618/* Determine the number of iterations between initialization of the base
1619 variable and the current copy (N_COPY). N_COPIES is the total number
1620 of newly created copies. UNROLLING is true if we are unrolling
1621 (not peeling) the loop. */
1622
1623static unsigned
1624determine_split_iv_delta (unsigned n_copy, unsigned n_copies, bool unrolling)
1625{
1626 if (unrolling)
1627 {
1628 /* If we are unrolling, initialization is done in the original loop
1629 body (number 0). */
1630 return n_copy;
1631 }
1632 else
1633 {
1634 /* If we are peeling, the copy in that the initialization occurs has
1635 number 1. The original loop (number 0) is the last. */
1636 if (n_copy)
1637 return n_copy - 1;
1638 else
1639 return n_copies;
1640 }
1641}
1642
a9f6ecee 1643/* Allocate basic variable for the induction variable chain. */
113d659a 1644
a9f6ecee
AO
1645static void
1646allocate_basic_variable (struct iv_to_split *ivts)
113d659a 1647{
8cab83f0 1648 rtx expr = SET_SRC (single_set (ivts->insn));
113d659a
ZD
1649
1650 ivts->base_var = gen_reg_rtx (GET_MODE (expr));
113d659a
ZD
1651}
1652
1653/* Insert initialization of basic variable of IVTS before INSN, taking
1654 the initial value from INSN. */
1655
1656static void
95ecfb26 1657insert_base_initialization (struct iv_to_split *ivts, rtx_insn *insn)
113d659a 1658{
8cab83f0 1659 rtx expr = copy_rtx (SET_SRC (single_set (insn)));
95ecfb26 1660 rtx_insn *seq;
113d659a
ZD
1661
1662 start_sequence ();
1663 expr = force_operand (expr, ivts->base_var);
1664 if (expr != ivts->base_var)
1665 emit_move_insn (ivts->base_var, expr);
1666 seq = get_insns ();
1667 end_sequence ();
1668
1669 emit_insn_before (seq, insn);
1670}
1671
1672/* Replace the use of induction variable described in IVTS in INSN
1673 by base variable + DELTA * step. */
1674
1675static void
95ecfb26 1676split_iv (struct iv_to_split *ivts, rtx_insn *insn, unsigned delta)
113d659a 1677{
95ecfb26
DM
1678 rtx expr, *loc, incr, var;
1679 rtx_insn *seq;
ef4bddc2 1680 machine_mode mode = GET_MODE (ivts->base_var);
113d659a
ZD
1681 rtx src, dest, set;
1682
1683 /* Construct base + DELTA * step. */
1684 if (!delta)
1685 expr = ivts->base_var;
1686 else
1687 {
1688 incr = simplify_gen_binary (MULT, mode,
1689 ivts->step, gen_int_mode (delta, mode));
1690 expr = simplify_gen_binary (PLUS, GET_MODE (ivts->base_var),
1691 ivts->base_var, incr);
1692 }
1693
1694 /* Figure out where to do the replacement. */
8cab83f0 1695 loc = &SET_SRC (single_set (insn));
113d659a
ZD
1696
1697 /* If we can make the replacement right away, we're done. */
1698 if (validate_change (insn, loc, expr, 0))
1699 return;
1700
1701 /* Otherwise, force EXPR into a register and try again. */
1702 start_sequence ();
1703 var = gen_reg_rtx (mode);
1704 expr = force_operand (expr, var);
1705 if (expr != var)
1706 emit_move_insn (var, expr);
1707 seq = get_insns ();
1708 end_sequence ();
1709 emit_insn_before (seq, insn);
b8698a0f 1710
113d659a
ZD
1711 if (validate_change (insn, loc, var, 0))
1712 return;
1713
1714 /* The last chance. Try recreating the assignment in insn
1715 completely from scratch. */
1716 set = single_set (insn);
1717 gcc_assert (set);
1718
1719 start_sequence ();
1720 *loc = var;
1721 src = copy_rtx (SET_SRC (set));
1722 dest = copy_rtx (SET_DEST (set));
1723 src = force_operand (src, dest);
1724 if (src != dest)
1725 emit_move_insn (dest, src);
1726 seq = get_insns ();
1727 end_sequence ();
b8698a0f 1728
113d659a
ZD
1729 emit_insn_before (seq, insn);
1730 delete_insn (insn);
1731}
1732
113d659a 1733
2cd0e9f4 1734/* Return one expansion of the accumulator recorded in struct VE. */
113d659a 1735
f37a4f14
RE
1736static rtx
1737get_expansion (struct var_to_expand *ve)
1738{
1739 rtx reg;
b8698a0f 1740
f37a4f14
RE
1741 if (ve->reuse_expansion == 0)
1742 reg = ve->reg;
1743 else
9771b263 1744 reg = ve->var_expansions[ve->reuse_expansion - 1];
b8698a0f 1745
9771b263 1746 if (ve->var_expansions.length () == (unsigned) ve->reuse_expansion)
f37a4f14 1747 ve->reuse_expansion = 0;
b8698a0f 1748 else
f37a4f14 1749 ve->reuse_expansion++;
b8698a0f 1750
f37a4f14
RE
1751 return reg;
1752}
113d659a 1753
113d659a 1754
b8698a0f 1755/* Given INSN replace the uses of the accumulator recorded in VE
f37a4f14
RE
1756 with a new register. */
1757
1758static void
95ecfb26 1759expand_var_during_unrolling (struct var_to_expand *ve, rtx_insn *insn)
f37a4f14
RE
1760{
1761 rtx new_reg, set;
1762 bool really_new_expansion = false;
b8698a0f 1763
f37a4f14 1764 set = single_set (insn);
b5e624c6 1765 gcc_assert (set);
b8698a0f 1766
f37a4f14
RE
1767 /* Generate a new register only if the expansion limit has not been
1768 reached. Else reuse an already existing expansion. */
1769 if (PARAM_VALUE (PARAM_MAX_VARIABLE_EXPANSIONS) > ve->expansion_count)
1770 {
1771 really_new_expansion = true;
1772 new_reg = gen_reg_rtx (GET_MODE (ve->reg));
1773 }
1774 else
1775 new_reg = get_expansion (ve);
1776
6e74642b 1777 validate_replace_rtx_group (SET_DEST (set), new_reg, insn);
f37a4f14
RE
1778 if (apply_change_group ())
1779 if (really_new_expansion)
1780 {
9771b263 1781 ve->var_expansions.safe_push (new_reg);
f37a4f14
RE
1782 ve->expansion_count++;
1783 }
1784}
1785
a9f6ecee
AO
1786/* Initialize the variable expansions in loop preheader. PLACE is the
1787 loop-preheader basic block where the initialization of the
1788 expansions should take place. The expansions are initialized with
1789 (-0) when the operation is plus or minus to honor sign zero. This
1790 way we can prevent cases where the sign of the final result is
1791 effected by the sign of the expansion. Here is an example to
1792 demonstrate this:
b8698a0f 1793
290358f7
RE
1794 for (i = 0 ; i < n; i++)
1795 sum += something;
1796
1797 ==>
1798
1799 sum += something
1800 ....
1801 i = i+1;
1802 sum1 += something
1803 ....
1804 i = i+1
1805 sum2 += something;
1806 ....
b8698a0f 1807
290358f7
RE
1808 When SUM is initialized with -zero and SOMETHING is also -zero; the
1809 final result of sum should be -zero thus the expansions sum1 and sum2
1810 should be initialized with -zero as well (otherwise we will get +zero
1811 as the final result). */
f37a4f14 1812
a9f6ecee
AO
1813static void
1814insert_var_expansion_initialization (struct var_to_expand *ve,
1815 basic_block place)
f37a4f14 1816{
95ecfb26
DM
1817 rtx_insn *seq;
1818 rtx var, zero_init;
f37a4f14 1819 unsigned i;
ef4bddc2 1820 machine_mode mode = GET_MODE (ve->reg);
290358f7
RE
1821 bool honor_signed_zero_p = HONOR_SIGNED_ZEROS (mode);
1822
9771b263 1823 if (ve->var_expansions.length () == 0)
a9f6ecee 1824 return;
b8698a0f 1825
f37a4f14 1826 start_sequence ();
531e5376
RH
1827 switch (ve->op)
1828 {
1829 case FMA:
1830 /* Note that we only accumulate FMA via the ADD operand. */
1831 case PLUS:
1832 case MINUS:
9771b263 1833 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
531e5376
RH
1834 {
1835 if (honor_signed_zero_p)
1836 zero_init = simplify_gen_unary (NEG, mode, CONST0_RTX (mode), mode);
1837 else
1838 zero_init = CONST0_RTX (mode);
1839 emit_move_insn (var, zero_init);
1840 }
1841 break;
1842
1843 case MULT:
9771b263 1844 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
531e5376
RH
1845 {
1846 zero_init = CONST1_RTX (GET_MODE (var));
1847 emit_move_insn (var, zero_init);
1848 }
1849 break;
1850
1851 default:
1852 gcc_unreachable ();
1853 }
b8698a0f 1854
f37a4f14
RE
1855 seq = get_insns ();
1856 end_sequence ();
b8698a0f 1857
6e74642b 1858 emit_insn_after (seq, BB_END (place));
f37a4f14
RE
1859}
1860
a9f6ecee
AO
1861/* Combine the variable expansions at the loop exit. PLACE is the
1862 loop exit basic block where the summation of the expansions should
1863 take place. */
f37a4f14 1864
a9f6ecee
AO
1865static void
1866combine_var_copies_in_loop_exit (struct var_to_expand *ve, basic_block place)
f37a4f14 1867{
f37a4f14 1868 rtx sum = ve->reg;
95ecfb26
DM
1869 rtx expr, var;
1870 rtx_insn *seq, *insn;
f37a4f14
RE
1871 unsigned i;
1872
9771b263 1873 if (ve->var_expansions.length () == 0)
a9f6ecee 1874 return;
b8698a0f 1875
f37a4f14 1876 start_sequence ();
531e5376
RH
1877 switch (ve->op)
1878 {
1879 case FMA:
1880 /* Note that we only accumulate FMA via the ADD operand. */
1881 case PLUS:
1882 case MINUS:
9771b263 1883 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
531e5376
RH
1884 sum = simplify_gen_binary (PLUS, GET_MODE (ve->reg), var, sum);
1885 break;
1886
1887 case MULT:
9771b263 1888 FOR_EACH_VEC_ELT (ve->var_expansions, i, var)
531e5376
RH
1889 sum = simplify_gen_binary (MULT, GET_MODE (ve->reg), var, sum);
1890 break;
1891
1892 default:
1893 gcc_unreachable ();
1894 }
b8698a0f 1895
f37a4f14
RE
1896 expr = force_operand (sum, ve->reg);
1897 if (expr != ve->reg)
1898 emit_move_insn (ve->reg, expr);
1899 seq = get_insns ();
1900 end_sequence ();
b8698a0f 1901
f37a4f14
RE
1902 insn = BB_HEAD (place);
1903 while (!NOTE_INSN_BASIC_BLOCK_P (insn))
1904 insn = NEXT_INSN (insn);
1905
1906 emit_insn_after (seq, insn);
f37a4f14
RE
1907}
1908
4a0c3fde
SB
1909/* Strip away REG_EQUAL notes for IVs we're splitting.
1910
1911 Updating REG_EQUAL notes for IVs we split is tricky: We
1912 cannot tell until after unrolling, DF-rescanning, and liveness
1913 updating, whether an EQ_USE is reached by the split IV while
1914 the IV reg is still live. See PR55006.
1915
1916 ??? We cannot use remove_reg_equal_equiv_notes_for_regno,
1917 because RTL loop-iv requires us to defer rescanning insns and
1918 any notes attached to them. So resort to old techniques... */
1919
1920static void
95ecfb26 1921maybe_strip_eq_note_for_split_iv (struct opt_info *opt_info, rtx_insn *insn)
4a0c3fde
SB
1922{
1923 struct iv_to_split *ivts;
1924 rtx note = find_reg_equal_equiv_note (insn);
1925 if (! note)
1926 return;
1927 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1928 if (reg_mentioned_p (ivts->orig_var, note))
1929 {
1930 remove_note (insn, note);
1931 return;
1932 }
1933}
1934
b8698a0f
L
1935/* Apply loop optimizations in loop copies using the
1936 data which gathered during the unrolling. Structure
f37a4f14 1937 OPT_INFO record that data.
b8698a0f 1938
113d659a
ZD
1939 UNROLLING is true if we unrolled (not peeled) the loop.
1940 REWRITE_ORIGINAL_BODY is true if we should also rewrite the original body of
1941 the loop (as it should happen in complete unrolling, but not in ordinary
1942 peeling of the loop). */
1943
1944static void
b8698a0f
L
1945apply_opt_in_copies (struct opt_info *opt_info,
1946 unsigned n_copies, bool unrolling,
f37a4f14 1947 bool rewrite_original_loop)
113d659a
ZD
1948{
1949 unsigned i, delta;
1950 basic_block bb, orig_bb;
95ecfb26 1951 rtx_insn *insn, *orig_insn, *next;
113d659a 1952 struct iv_to_split ivts_templ, *ivts;
f37a4f14 1953 struct var_to_expand ve_templ, *ves;
b8698a0f 1954
113d659a
ZD
1955 /* Sanity check -- we need to put initialization in the original loop
1956 body. */
1957 gcc_assert (!unrolling || rewrite_original_loop);
b8698a0f 1958
113d659a 1959 /* Allocate the basic variables (i0). */
c203e8a7 1960 if (opt_info->insns_to_split)
a9f6ecee
AO
1961 for (ivts = opt_info->iv_to_split_head; ivts; ivts = ivts->next)
1962 allocate_basic_variable (ivts);
b8698a0f 1963
8b1c6fd7
DM
1964 for (i = opt_info->first_new_block;
1965 i < (unsigned) last_basic_block_for_fn (cfun);
1966 i++)
113d659a 1967 {
06e28de2 1968 bb = BASIC_BLOCK_FOR_FN (cfun, i);
6580ee77 1969 orig_bb = get_bb_original (bb);
b8698a0f 1970
6580ee77
JH
1971 /* bb->aux holds position in copy sequence initialized by
1972 duplicate_loop_to_header_edge. */
1973 delta = determine_split_iv_delta ((size_t)bb->aux, n_copies,
113d659a 1974 unrolling);
7f7b1718 1975 bb->aux = 0;
113d659a 1976 orig_insn = BB_HEAD (orig_bb);
4a0c3fde 1977 FOR_BB_INSNS_SAFE (bb, insn, next)
f37a4f14 1978 {
0397b965
JJ
1979 if (!INSN_P (insn)
1980 || (DEBUG_INSN_P (insn)
1981 && TREE_CODE (INSN_VAR_LOCATION_DECL (insn)) == LABEL_DECL))
f37a4f14 1982 continue;
b8698a0f 1983
0397b965
JJ
1984 while (!INSN_P (orig_insn)
1985 || (DEBUG_INSN_P (orig_insn)
1986 && (TREE_CODE (INSN_VAR_LOCATION_DECL (orig_insn))
1987 == LABEL_DECL)))
f37a4f14 1988 orig_insn = NEXT_INSN (orig_insn);
b8698a0f 1989
f37a4f14
RE
1990 ivts_templ.insn = orig_insn;
1991 ve_templ.insn = orig_insn;
b8698a0f 1992
f37a4f14 1993 /* Apply splitting iv optimization. */
c203e8a7 1994 if (opt_info->insns_to_split)
f37a4f14 1995 {
4a0c3fde
SB
1996 maybe_strip_eq_note_for_split_iv (opt_info, insn);
1997
c203e8a7 1998 ivts = opt_info->insns_to_split->find (&ivts_templ);
b8698a0f 1999
f37a4f14
RE
2000 if (ivts)
2001 {
21f868a2
ZD
2002 gcc_assert (GET_CODE (PATTERN (insn))
2003 == GET_CODE (PATTERN (orig_insn)));
b8698a0f 2004
f37a4f14
RE
2005 if (!delta)
2006 insert_base_initialization (ivts, insn);
2007 split_iv (ivts, insn, delta);
2008 }
2009 }
2010 /* Apply variable expansion optimization. */
c203e8a7 2011 if (unrolling && opt_info->insns_with_var_to_expand)
f37a4f14 2012 {
d3bfe4de 2013 ves = (struct var_to_expand *)
c203e8a7 2014 opt_info->insns_with_var_to_expand->find (&ve_templ);
f37a4f14 2015 if (ves)
b8698a0f 2016 {
21f868a2
ZD
2017 gcc_assert (GET_CODE (PATTERN (insn))
2018 == GET_CODE (PATTERN (orig_insn)));
f37a4f14
RE
2019 expand_var_during_unrolling (ves, insn);
2020 }
2021 }
2022 orig_insn = NEXT_INSN (orig_insn);
2023 }
113d659a
ZD
2024 }
2025
2026 if (!rewrite_original_loop)
2027 return;
b8698a0f 2028
f37a4f14 2029 /* Initialize the variable expansions in the loop preheader
b8698a0f 2030 and take care of combining them at the loop exit. */
c203e8a7 2031 if (opt_info->insns_with_var_to_expand)
f37a4f14 2032 {
a9f6ecee
AO
2033 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2034 insert_var_expansion_initialization (ves, opt_info->loop_preheader);
2035 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
2036 combine_var_copies_in_loop_exit (ves, opt_info->loop_exit);
f37a4f14 2037 }
b8698a0f 2038
113d659a
ZD
2039 /* Rewrite also the original loop body. Find them as originals of the blocks
2040 in the last copied iteration, i.e. those that have
6580ee77 2041 get_bb_copy (get_bb_original (bb)) == bb. */
8b1c6fd7
DM
2042 for (i = opt_info->first_new_block;
2043 i < (unsigned) last_basic_block_for_fn (cfun);
2044 i++)
113d659a 2045 {
06e28de2 2046 bb = BASIC_BLOCK_FOR_FN (cfun, i);
6580ee77
JH
2047 orig_bb = get_bb_original (bb);
2048 if (get_bb_copy (orig_bb) != bb)
113d659a 2049 continue;
b8698a0f 2050
113d659a
ZD
2051 delta = determine_split_iv_delta (0, n_copies, unrolling);
2052 for (orig_insn = BB_HEAD (orig_bb);
f37a4f14
RE
2053 orig_insn != NEXT_INSN (BB_END (bb));
2054 orig_insn = next)
2055 {
2056 next = NEXT_INSN (orig_insn);
b8698a0f 2057
f37a4f14
RE
2058 if (!INSN_P (orig_insn))
2059 continue;
b8698a0f 2060
f37a4f14 2061 ivts_templ.insn = orig_insn;
c203e8a7 2062 if (opt_info->insns_to_split)
f37a4f14 2063 {
4a0c3fde
SB
2064 maybe_strip_eq_note_for_split_iv (opt_info, orig_insn);
2065
d3bfe4de 2066 ivts = (struct iv_to_split *)
c203e8a7 2067 opt_info->insns_to_split->find (&ivts_templ);
f37a4f14
RE
2068 if (ivts)
2069 {
2070 if (!delta)
2071 insert_base_initialization (ivts, orig_insn);
2072 split_iv (ivts, orig_insn, delta);
2073 continue;
2074 }
2075 }
b8698a0f 2076
f37a4f14
RE
2077 }
2078 }
2079}
113d659a 2080
f37a4f14 2081/* Release OPT_INFO. */
113d659a
ZD
2082
2083static void
f37a4f14 2084free_opt_info (struct opt_info *opt_info)
113d659a 2085{
c203e8a7
TS
2086 delete opt_info->insns_to_split;
2087 opt_info->insns_to_split = NULL;
2088 if (opt_info->insns_with_var_to_expand)
f37a4f14 2089 {
a9f6ecee
AO
2090 struct var_to_expand *ves;
2091
2092 for (ves = opt_info->var_to_expand_head; ves; ves = ves->next)
9771b263 2093 ves->var_expansions.release ();
c203e8a7
TS
2094 delete opt_info->insns_with_var_to_expand;
2095 opt_info->insns_with_var_to_expand = NULL;
f37a4f14
RE
2096 }
2097 free (opt_info);
113d659a 2098}