LCOV - code coverage report
Current view: top level - gcc - tree-ssa-loop-ivcanon.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 97.7 % 728 711
Test Date: 2026-12-05 16:10:02 Functions: 100.0 % 24 24
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Induction variable canonicalization and loop peeling.
       2              :    Copyright (C) 2004-2026 Free Software Foundation, Inc.
       3              : 
       4              : This file is part of GCC.
       5              : 
       6              : GCC is free software; you can redistribute it and/or modify it
       7              : under the terms of the GNU General Public License as published by the
       8              : Free Software Foundation; either version 3, or (at your option) any
       9              : later version.
      10              : 
      11              : GCC is distributed in the hope that it will be useful, but WITHOUT
      12              : ANY 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.
      15              : 
      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/>.  */
      19              : 
      20              : /* This pass detects the loops that iterate a constant number of times,
      21              :    adds a canonical induction variable (step -1, tested against 0)
      22              :    and replaces the exit test.  This enables the less powerful rtl
      23              :    level analysis to use this information.
      24              : 
      25              :    This might spoil the code in some cases (by increasing register pressure).
      26              :    Note that in the case the new variable is not needed, ivopts will get rid
      27              :    of it, so it might only be a problem when there are no other linear induction
      28              :    variables.  In that case the created optimization possibilities are likely
      29              :    to pay up.
      30              : 
      31              :    We also perform
      32              :      - complete unrolling (or peeling) when the loops is rolling few enough
      33              :        times
      34              :      - simple peeling (i.e. copying few initial iterations prior the loop)
      35              :        when number of iteration estimate is known (typically by the profile
      36              :        info).  */
      37              : 
      38              : #include "config.h"
      39              : #include "system.h"
      40              : #include "coretypes.h"
      41              : #include "backend.h"
      42              : #include "tree.h"
      43              : #include "gimple.h"
      44              : #include "cfghooks.h"
      45              : #include "tree-pass.h"
      46              : #include "ssa.h"
      47              : #include "cgraph.h"
      48              : #include "gimple-pretty-print.h"
      49              : #include "fold-const.h"
      50              : #include "profile.h"
      51              : #include "gimple-iterator.h"
      52              : #include "gimple-fold.h"
      53              : #include "tree-eh.h"
      54              : #include "tree-cfg.h"
      55              : #include "tree-ssa-loop-manip.h"
      56              : #include "tree-ssa-loop-niter.h"
      57              : #include "tree-ssa-loop.h"
      58              : #include "tree-into-ssa.h"
      59              : #include "cfgloop.h"
      60              : #include "tree-chrec.h"
      61              : #include "tree-scalar-evolution.h"
      62              : #include "tree-inline.h"
      63              : #include "tree-cfgcleanup.h"
      64              : #include "builtins.h"
      65              : #include "tree-ssa-sccvn.h"
      66              : #include "tree-vectorizer.h" /* For find_loop_location */
      67              : #include "dbgcnt.h"
      68              : 
      69              : /* Specifies types of loops that may be unrolled.  */
      70              : 
      71              : enum unroll_level
      72              : {
      73              :   UL_SINGLE_ITER,       /* Only loops that exit immediately in the first
      74              :                            iteration.  */
      75              :   UL_NO_GROWTH,         /* Only loops whose unrolling will not cause increase
      76              :                            of code size.  */
      77              :   UL_ALL                /* All suitable loops.  */
      78              : };
      79              : 
      80              : /* Adds a canonical induction variable to LOOP iterating NITER times.  EXIT
      81              :    is the exit edge whose condition is replaced.  The ssa versions of the new
      82              :    IV before and after increment will be stored in VAR_BEFORE and VAR_AFTER
      83              :    if they are not NULL.  */
      84              : 
      85              : void
      86       328612 : create_canonical_iv (class loop *loop, edge exit, tree niter,
      87              :                      tree *var_before = NULL, tree *var_after = NULL)
      88              : {
      89       328612 :   edge in;
      90       328612 :   tree type, var;
      91       328612 :   gcond *cond;
      92       328612 :   gimple_stmt_iterator incr_at;
      93       328612 :   enum tree_code cmp;
      94              : 
      95       328612 :   if (dump_file && (dump_flags & TDF_DETAILS))
      96              :     {
      97           41 :       fprintf (dump_file, "Added canonical iv to loop %d, ", loop->num);
      98           41 :       print_generic_expr (dump_file, niter, TDF_SLIM);
      99           41 :       fprintf (dump_file, " iterations.\n");
     100              :     }
     101              : 
     102       657224 :   cond = as_a <gcond *> (*gsi_last_bb (exit->src));
     103       328612 :   in = EDGE_SUCC (exit->src, 0);
     104       328612 :   if (in == exit)
     105        94102 :     in = EDGE_SUCC (exit->src, 1);
     106              : 
     107              :   /* Note that we do not need to worry about overflows, since
     108              :      type of niter is always unsigned and all comparisons are
     109              :      just for equality/nonequality -- i.e. everything works
     110              :      with a modulo arithmetics.  */
     111              : 
     112       328612 :   type = TREE_TYPE (niter);
     113       328612 :   niter = fold_build2 (PLUS_EXPR, type,
     114              :                        niter,
     115              :                        build_int_cst (type, 1));
     116       328612 :   incr_at = gsi_last_bb (in->src);
     117       328612 :   create_iv (niter, PLUS_EXPR,
     118              :              build_int_cst (type, -1),
     119              :              NULL_TREE, loop,
     120              :              &incr_at, false, var_before, &var);
     121       328612 :   if (var_after)
     122          100 :     *var_after = var;
     123              : 
     124       328612 :   cmp = (exit->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR;
     125       328612 :   gimple_cond_set_code (cond, cmp);
     126       328612 :   gimple_cond_set_lhs (cond, var);
     127       328612 :   gimple_cond_set_rhs (cond, build_int_cst (type, 0));
     128       328612 :   update_stmt (cond);
     129       328612 : }
     130              : 
     131              : /* Describe size of loop as detected by tree_estimate_loop_size.  */
     132              : struct loop_size
     133              : {
     134              :   /* Number of instructions in the loop.  */
     135              :   int overall;
     136              : 
     137              :   /* Number of instructions that will be likely optimized out in
     138              :      peeled iterations of loop  (i.e. computation based on induction
     139              :      variable where induction variable starts at known constant.)  */
     140              :   int eliminated_by_peeling;
     141              : 
     142              :   /* Number of instructions that cannot be further optimized in the
     143              :      peeled loop, for example volatile accesses.  */
     144              :   int not_eliminatable_after_peeling;
     145              : 
     146              :   /* Same statistics for last iteration of loop: it is smaller because
     147              :      instructions after exit are not executed.  */
     148              :   int last_iteration;
     149              :   int last_iteration_eliminated_by_peeling;
     150              :   int last_iteration_not_eliminatable_after_peeling;
     151              : 
     152              :   /* If some IV computation will become constant.  */
     153              :   bool constant_iv;
     154              : 
     155              :   /* Number of call stmts that are not a builtin and are pure or const
     156              :      present on the hot path.  */
     157              :   int num_pure_calls_on_hot_path;
     158              :   /* Number of call stmts that are not a builtin and are not pure nor const
     159              :      present on the hot path.  */
     160              :   int num_non_pure_calls_on_hot_path;
     161              :   /* Number of statements other than calls in the loop.  */
     162              :   int non_call_stmts_on_hot_path;
     163              :   /* Number of branches seen on the hot path.  */
     164              :   int num_branches_on_hot_path;
     165              : };
     166              : 
     167              : /* Return true if OP in STMT will be constant after peeling LOOP.  */
     168              : 
     169              : static bool
     170     13931242 : constant_after_peeling (tree op, gimple *stmt, class loop *loop)
     171              : {
     172     13931242 :   if (CONSTANT_CLASS_P (op))
     173              :     return true;
     174              : 
     175              :   /* Get at the actual SSA operand.  */
     176     13088517 :   if (handled_component_p (op)
     177      1436614 :       && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
     178        32429 :     op = TREE_OPERAND (op, 0);
     179              : 
     180              :   /* We can still fold accesses to constant arrays when index is known.  */
     181     13088517 :   if (TREE_CODE (op) != SSA_NAME)
     182              :     {
     183              :       tree base = op;
     184              : 
     185              :       /* First make fast look if we see constant array inside.  */
     186      4378138 :       while (handled_component_p (base))
     187      2266834 :         base = TREE_OPERAND (base, 0);
     188      2111304 :       if ((DECL_P (base)
     189       946063 :            && ctor_for_folding (base) != error_mark_node)
     190      2995565 :           || CONSTANT_CLASS_P (base))
     191              :         {
     192              :           /* If so, see if we understand all the indices.  */
     193              :           base = op;
     194       117441 :           while (handled_component_p (base))
     195              :             {
     196        69611 :               if (TREE_CODE (base) == ARRAY_REF
     197        69611 :                   && !constant_after_peeling (TREE_OPERAND (base, 1), stmt, loop))
     198              :                 return false;
     199        55624 :               base = TREE_OPERAND (base, 0);
     200              :             }
     201              :           return true;
     202              :         }
     203              :       return false;
     204              :     }
     205              : 
     206              :   /* Induction variables are constants when defined in loop.  */
     207     21954426 :   if (loop_containing_stmt (stmt) != loop)
     208              :     return false;
     209      8237557 :   tree ev = analyze_scalar_evolution (loop, op);
     210      8237557 :   if (chrec_contains_undetermined (ev)
     211      8237557 :       || chrec_contains_symbols (ev))
     212              :     {
     213      5961670 :       if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (op)))
     214              :         {
     215      4419271 :           gassign *ass = nullptr;
     216      4419271 :           gphi *phi = nullptr;
     217      4419271 :           if (is_a <gassign *> (SSA_NAME_DEF_STMT (op)))
     218              :             {
     219      3979802 :               ass = as_a <gassign *> (SSA_NAME_DEF_STMT (op));
     220      3979802 :               if (TREE_CODE (gimple_assign_rhs1 (ass)) == SSA_NAME)
     221      2509270 :                 phi = dyn_cast <gphi *>
     222      2509270 :                         (SSA_NAME_DEF_STMT (gimple_assign_rhs1  (ass)));
     223              :             }
     224       439469 :           else if (is_a <gphi *> (SSA_NAME_DEF_STMT (op)))
     225              :             {
     226       339947 :               phi = as_a <gphi *> (SSA_NAME_DEF_STMT (op));
     227       339947 :               if (gimple_bb (phi) == loop->header)
     228              :                 {
     229       222121 :                   tree def = gimple_phi_arg_def_from_edge
     230       222121 :                     (phi, loop_latch_edge (loop));
     231       222121 :                   if (TREE_CODE (def) == SSA_NAME
     232       222121 :                       && is_a <gassign *> (SSA_NAME_DEF_STMT (def)))
     233       155989 :                     ass = as_a <gassign *> (SSA_NAME_DEF_STMT (def));
     234              :                 }
     235              :             }
     236      4419271 :           if (ass && phi)
     237              :             {
     238       595523 :               tree rhs1 = gimple_assign_rhs1 (ass);
     239       595523 :               if (gimple_assign_rhs_class (ass) == GIMPLE_BINARY_RHS
     240       476793 :                   && CONSTANT_CLASS_P (gimple_assign_rhs2 (ass))
     241       347856 :                   && rhs1 == gimple_phi_result (phi)
     242       346958 :                   && gimple_bb (phi) == loop->header
     243       269378 :                   && (gimple_phi_arg_def_from_edge (phi, loop_latch_edge (loop))
     244       269378 :                       == gimple_assign_lhs (ass))
     245       802065 :                   && (CONSTANT_CLASS_P (gimple_phi_arg_def_from_edge
     246              :                                          (phi, loop_preheader_edge (loop)))))
     247              :                 return true;
     248              :             }
     249              :         }
     250      5947725 :       return false;
     251              :     }
     252              :   return true;
     253              : }
     254              : 
     255              : /* Computes an estimated number of insns in LOOP.
     256              :    EXIT (if non-NULL) is an exit edge that will be eliminated in all but last
     257              :    iteration of the loop.
     258              :    EDGE_TO_CANCEL (if non-NULL) is an non-exit edge eliminated in the last iteration
     259              :    of loop.
     260              :    Return results in SIZE, estimate benefits for complete unrolling exiting by EXIT.
     261              :    Stop estimating after UPPER_BOUND is met.  Return true in this case.  */
     262              : 
     263              : static bool
     264       534347 : tree_estimate_loop_size (class loop *loop, edge exit, edge edge_to_cancel,
     265              :                          struct loop_size *size, int upper_bound)
     266              : {
     267       534347 :   basic_block *body = get_loop_body (loop);
     268       534347 :   gimple_stmt_iterator gsi;
     269       534347 :   unsigned int i;
     270       534347 :   bool after_exit;
     271       534347 :   auto_vec<basic_block> path = get_loop_hot_path (loop);
     272              : 
     273       534347 :   size->overall = 0;
     274       534347 :   size->eliminated_by_peeling = 0;
     275       534347 :   size->not_eliminatable_after_peeling = 0;
     276       534347 :   size->last_iteration = 0;
     277       534347 :   size->last_iteration_eliminated_by_peeling = 0;
     278       534347 :   size->last_iteration_not_eliminatable_after_peeling = 0;
     279       534347 :   size->num_pure_calls_on_hot_path = 0;
     280       534347 :   size->num_non_pure_calls_on_hot_path = 0;
     281       534347 :   size->non_call_stmts_on_hot_path = 0;
     282       534347 :   size->num_branches_on_hot_path = 0;
     283       534347 :   size->constant_iv = 0;
     284              : 
     285       534347 :   if (dump_file && (dump_flags & TDF_DETAILS))
     286           65 :     fprintf (dump_file, "Estimating sizes for loop %i\n", loop->num);
     287      2977692 :   for (i = 0; i < loop->num_nodes; i++)
     288              :     {
     289      2348198 :       if (edge_to_cancel && body[i] != edge_to_cancel->src
     290      4281558 :           && dominated_by_p (CDI_DOMINATORS, body[i], edge_to_cancel->src))
     291              :         after_exit = true;
     292              :       else
     293              :         after_exit = false;
     294      2450280 :       if (dump_file && (dump_flags & TDF_DETAILS))
     295          192 :         fprintf (dump_file, " BB: %i, after_exit: %i\n", body[i]->index,
     296              :                  after_exit);
     297              : 
     298     15648656 :       for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
     299              :         {
     300     10755031 :           gimple *stmt = gsi_stmt (gsi);
     301     10755031 :           int num = estimate_num_insns (stmt, &eni_size_weights);
     302     10755031 :           bool not_eliminatable_after_peeling = false;
     303     10755031 :           bool likely_eliminated = false;
     304     10755031 :           bool likely_eliminated_last = false;
     305     10755031 :           bool likely_eliminated_peeled = false;
     306              : 
     307     10755031 :           if (dump_file && (dump_flags & TDF_DETAILS))
     308              :             {
     309          974 :               fprintf (dump_file, "  size: %3i ", num);
     310          974 :               print_gimple_stmt (dump_file, gsi_stmt (gsi), 0);
     311              :             }
     312              : 
     313              :           /* Look for reasons why we might optimize this stmt away. */
     314              : 
     315     10755031 :           if (gimple_has_side_effects (stmt))
     316              :             not_eliminatable_after_peeling = true;
     317              :           else
     318              :             {
     319              :               /* Exit conditional.  */
     320      8433109 :               if (exit && body[i] == exit->src
     321     14384706 :                   && stmt == *gsi_last_bb (exit->src))
     322              :                 {
     323       437377 :                   if (dump_file && (dump_flags & TDF_DETAILS))
     324           32 :                     fprintf (dump_file, "   Exit condition will be eliminated "
     325              :                              "in peeled copies.\n");
     326              :                   likely_eliminated_peeled = true;
     327              :                 }
     328     10069447 :               if (edge_to_cancel && body[i] == edge_to_cancel->src
     329     16264818 :                   && stmt == *gsi_last_bb (edge_to_cancel->src))
     330              :                 {
     331       516743 :                   if (dump_file && (dump_flags & TDF_DETAILS))
     332           59 :                     fprintf (dump_file, "   Exit condition will be eliminated "
     333              :                              "in last copy.\n");
     334              :                   likely_eliminated_last = true;
     335              :                 }
     336              :               /* Sets of IV variables  */
     337     10460220 :               auto assign = dyn_cast<gassign *> (stmt);
     338      6274283 :               if (assign
     339      6274283 :                   && constant_after_peeling (gimple_assign_lhs (assign),
     340              :                                              stmt, loop))
     341              :                 {
     342      1245037 :                   if (dump_file && (dump_flags & TDF_DETAILS))
     343          105 :                     fprintf (dump_file, "   Induction variable computation will"
     344              :                              " be folded away.\n");
     345              :                   likely_eliminated = true;
     346              :                 }
     347              :               /* Assignments of IV variables.  */
     348      9215183 :               else if (assign
     349      5029246 :                        && TREE_CODE (gimple_assign_lhs (assign)) == SSA_NAME
     350      4236189 :                        && constant_after_peeling (gimple_assign_rhs1 (assign),
     351              :                                                   stmt, loop)
     352       191527 :                        && (gimple_assign_rhs_class (stmt) != GIMPLE_BINARY_RHS
     353       100738 :                            || constant_after_peeling (gimple_assign_rhs2 (stmt),
     354              :                                                       stmt, loop))
     355      9319147 :                        && gimple_assign_rhs_class (stmt) != GIMPLE_TERNARY_RHS)
     356              :                 {
     357       103293 :                   size->constant_iv = true;
     358       103293 :                   if (dump_file && (dump_flags & TDF_DETAILS))
     359           13 :                     fprintf (dump_file,
     360              :                              "   Constant expression will be folded away.\n");
     361              :                   likely_eliminated = true;
     362              :                 }
     363              :               /* Conditionals.  */
     364      9111890 :               else if ((gimple_code (stmt) == GIMPLE_COND
     365      1323525 :                         && constant_after_peeling (gimple_cond_lhs (stmt), stmt,
     366              :                                                    loop)
     367       460687 :                         && constant_after_peeling (gimple_cond_rhs (stmt), stmt,
     368              :                                                    loop)
     369              :                         /* We don't simplify all constant compares so make sure
     370              :                            they are not both constant already.  See PR70288.  */
     371       432276 :                         && (! is_gimple_min_invariant (gimple_cond_lhs (stmt))
     372          276 :                             || ! is_gimple_min_invariant
     373          276 :                                  (gimple_cond_rhs (stmt))))
     374     10003415 :                        || (gimple_code (stmt) == GIMPLE_SWITCH
     375         1419 :                            && constant_after_peeling (gimple_switch_index (
     376              :                                                         as_a <gswitch *>
     377         1419 :                                                           (stmt)),
     378              :                                                       stmt, loop)
     379          315 :                            && ! is_gimple_min_invariant
     380          315 :                                    (gimple_switch_index
     381          315 :                                       (as_a <gswitch *> (stmt)))))
     382              :                 {
     383       432315 :                   if (dump_file && (dump_flags & TDF_DETAILS))
     384           29 :                     fprintf (dump_file, "   Constant conditional.\n");
     385              :                   likely_eliminated = true;
     386              :                 }
     387              :             }
     388              : 
     389     10755031 :           size->overall += num;
     390     10755031 :           if (likely_eliminated || likely_eliminated_peeled)
     391      1801385 :             size->eliminated_by_peeling += num;
     392     10755031 :           if (not_eliminatable_after_peeling)
     393       294811 :             size->not_eliminatable_after_peeling += num;
     394     10755031 :           if (!after_exit)
     395              :             {
     396      6739107 :               size->last_iteration += num;
     397      6739107 :               if (likely_eliminated || likely_eliminated_last)
     398      1331008 :                 size->last_iteration_eliminated_by_peeling += num;
     399      6739107 :               if (not_eliminatable_after_peeling)
     400       152931 :                 size->last_iteration_not_eliminatable_after_peeling += num;
     401              :             }
     402     10755031 :           if ((size->overall * 3 / 2 - size->eliminated_by_peeling
     403     10755031 :               - size->last_iteration_eliminated_by_peeling) > upper_bound)
     404              :             {
     405         6935 :               free (body);
     406         6935 :               return true;
     407              :             }
     408              :         }
     409              :     }
     410      2340969 :   while (path.length ())
     411              :     {
     412      1813557 :       basic_block bb = path.pop ();
     413     11973122 :       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
     414              :         {
     415      8346008 :           gimple *stmt = gsi_stmt (gsi);
     416      8346008 :           if (gimple_code (stmt) == GIMPLE_CALL
     417      8346008 :               && !gimple_inexpensive_call_p (as_a <gcall *>  (stmt)))
     418              :             {
     419       157634 :               int flags = gimple_call_flags (stmt);
     420       157634 :               if (flags & (ECF_PURE | ECF_CONST))
     421        29046 :                 size->num_pure_calls_on_hot_path++;
     422              :               else
     423       128588 :                 size->num_non_pure_calls_on_hot_path++;
     424       157634 :               size->num_branches_on_hot_path ++;
     425              :             }
     426              :           /* Count inexpensive calls as non-calls, because they will likely
     427              :              expand inline.  */
     428      8188374 :           else if (gimple_code (stmt) != GIMPLE_DEBUG)
     429      6193909 :             size->non_call_stmts_on_hot_path++;
     430      8346008 :           if (((gimple_code (stmt) == GIMPLE_COND
     431      1062466 :                 && (!constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop)
     432       408126 :                     || !constant_after_peeling (gimple_cond_rhs (stmt), stmt,
     433              :                                                 loop)))
     434      7663702 :                || (gimple_code (stmt) == GIMPLE_SWITCH
     435          942 :                    && !constant_after_peeling (gimple_switch_index (
     436          942 :                                                  as_a <gswitch *> (stmt)),
     437              :                                                stmt, loop)))
     438      9029052 :               && (!exit || bb != exit->src))
     439       663149 :             size->num_branches_on_hot_path++;
     440              :         }
     441              :     }
     442              : 
     443       527412 :   if (dump_file && (dump_flags & TDF_DETAILS))
     444           65 :     fprintf (dump_file, "size: %i-%i, last_iteration: %i-%i\n", size->overall,
     445              :              size->eliminated_by_peeling, size->last_iteration,
     446              :              size->last_iteration_eliminated_by_peeling);
     447              : 
     448       527412 :   free (body);
     449       527412 :   return false;
     450       534347 : }
     451              : 
     452              : /* Estimate number of insns of completely unrolled loop.
     453              :    It is (NUNROLL + 1) * size of loop body with taking into account
     454              :    the fact that in last copy everything after exit conditional
     455              :    is dead and that some instructions will be eliminated after
     456              :    peeling.  Set *EST_ELIMINATED to the number of stmts that could be
     457              :    optimistically eliminated by followup transforms.  */
     458              : static unsigned HOST_WIDE_INT
     459       526692 : estimated_unrolled_size (struct loop_size *size,
     460              :                          unsigned HOST_WIDE_INT *est_eliminated,
     461              :                          unsigned HOST_WIDE_INT nunroll)
     462              : {
     463       526692 :   HOST_WIDE_INT unr_insns = ((nunroll)
     464       526692 :                              * (HOST_WIDE_INT) (size->overall
     465       526692 :                                                 - size->eliminated_by_peeling));
     466       526692 :   HOST_WIDE_INT not_elim
     467       526692 :     = ((nunroll) * (HOST_WIDE_INT) size->not_eliminatable_after_peeling);
     468       526692 :   unr_insns += size->last_iteration - size->last_iteration_eliminated_by_peeling;
     469       526692 :   not_elim += size->last_iteration_not_eliminatable_after_peeling;
     470              : 
     471              :   /* Testcases rely on rounding up, so do not write as
     472              :      (unr_insns - not_elim) / 3.  */
     473       526692 :   *est_eliminated = unr_insns - not_elim - (unr_insns - not_elim) * 2 / 3;
     474       526692 :   return unr_insns;
     475              : }
     476              : 
     477              : /* Loop LOOP is known to not loop.  See if there is an edge in the loop
     478              :    body that can be remove to make the loop to always exit and at
     479              :    the same time it does not make any code potentially executed
     480              :    during the last iteration dead.
     481              : 
     482              :    After complete unrolling we still may get rid of the conditional
     483              :    on the exit in the last copy even if we have no idea what it does.
     484              :    This is quite common case for loops of form
     485              : 
     486              :      int a[5];
     487              :      for (i=0;i<b;i++)
     488              :        a[i]=0;
     489              : 
     490              :    Here we prove the loop to iterate 5 times but we do not know
     491              :    it from induction variable.
     492              : 
     493              :    For now we handle only simple case where there is exit condition
     494              :    just before the latch block and the latch block contains no statements
     495              :    with side effect that may otherwise terminate the execution of loop
     496              :    (such as by EH or by terminating the program or longjmp).
     497              : 
     498              :    In the general case we may want to cancel the paths leading to statements
     499              :    loop-niter identified as having undefined effect in the last iteration.
     500              :    The other cases are hopefully rare and will be cleaned up later.  */
     501              : 
     502              : static edge
     503       109440 : loop_edge_to_cancel (class loop *loop)
     504              : {
     505       109440 :   unsigned i;
     506       109440 :   edge edge_to_cancel;
     507       109440 :   gimple_stmt_iterator gsi;
     508              : 
     509              :   /* We want only one predecestor of the loop.  */
     510       109440 :   if (EDGE_COUNT (loop->latch->preds) > 1)
     511              :     return NULL;
     512              : 
     513        95380 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     514              : 
     515       297012 :   FOR_EACH_VEC_ELT (exits, i, edge_to_cancel)
     516              :     {
     517              :        /* Find the other edge than the loop exit
     518              :           leaving the conditional.  */
     519       104340 :        if (EDGE_COUNT (edge_to_cancel->src->succs) != 2)
     520           82 :          continue;
     521       104258 :        if (EDGE_SUCC (edge_to_cancel->src, 0) == edge_to_cancel)
     522        28344 :          edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 1);
     523              :        else
     524              :          edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 0);
     525              : 
     526              :       /* We only can handle conditionals.  */
     527       104258 :       if (!(edge_to_cancel->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
     528          415 :         continue;
     529              : 
     530              :       /* We should never have conditionals in the loop latch. */
     531       103843 :       gcc_assert (edge_to_cancel->dest != loop->header);
     532              : 
     533              :       /* Check that it leads to loop latch.  */
     534       103843 :       if (edge_to_cancel->dest != loop->latch)
     535        10451 :         continue;
     536              : 
     537              :       /* Verify that the code in loop latch does nothing that may end program
     538              :          execution without really reaching the exit.  This may include
     539              :          non-pure/const function calls, EH statements, volatile ASMs etc.  */
     540       388702 :       for (gsi = gsi_start_bb (loop->latch); !gsi_end_p (gsi); gsi_next (&gsi))
     541       202690 :         if (gimple_has_side_effects (gsi_stmt (gsi)))
     542              :            return NULL;
     543              :       return edge_to_cancel;
     544              :     }
     545              :   return NULL;
     546        95380 : }
     547              : 
     548              : /* Remove all tests for exits that are known to be taken after LOOP was
     549              :    peeled NPEELED times. Put gcc_unreachable before every statement
     550              :    known to not be executed.  */
     551              : 
     552              : static bool
     553       152493 : remove_exits_and_undefined_stmts (class loop *loop, unsigned int npeeled)
     554              : {
     555       152493 :   class nb_iter_bound *elt;
     556       152493 :   bool changed = false;
     557              : 
     558       463395 :   for (elt = loop->bounds; elt; elt = elt->next)
     559              :     {
     560              :       /* If statement is known to be undefined after peeling, turn it
     561              :          into unreachable (or trap when debugging experience is supposed
     562              :          to be good).  */
     563       310902 :       if (!elt->is_exit
     564       310902 :           && wi::ltu_p (elt->bound, npeeled))
     565              :         {
     566        40076 :           gimple_stmt_iterator gsi = gsi_for_stmt (elt->stmt);
     567        40076 :           location_t loc = gimple_location (elt->stmt);
     568        40076 :           gcall *stmt = gimple_build_builtin_unreachable (loc);
     569        40076 :           gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
     570        40076 :           split_block (gimple_bb (stmt), stmt);
     571        40076 :           changed = true;
     572        40076 :           if (dump_file && (dump_flags & TDF_DETAILS))
     573              :             {
     574            4 :               fprintf (dump_file, "Forced statement unreachable: ");
     575            4 :               print_gimple_stmt (dump_file, elt->stmt, 0);
     576              :             }
     577              :         }
     578              :       /* If we know the exit will be taken after peeling, update.  */
     579       270826 :       else if (elt->is_exit
     580       270826 :                && wi::leu_p (elt->bound, npeeled))
     581              :         {
     582       115802 :           basic_block bb = gimple_bb (elt->stmt);
     583       115802 :           edge exit_edge = EDGE_SUCC (bb, 0);
     584              : 
     585       115802 :           if (dump_file && (dump_flags & TDF_DETAILS))
     586              :             {
     587           78 :               fprintf (dump_file, "Forced exit to be taken: ");
     588           78 :               print_gimple_stmt (dump_file, elt->stmt, 0);
     589              :             }
     590       115802 :           if (!loop_exit_edge_p (loop, exit_edge))
     591        44233 :             exit_edge = EDGE_SUCC (bb, 1);
     592       115802 :           exit_edge->probability = profile_probability::always ();
     593       115802 :           gcc_checking_assert (loop_exit_edge_p (loop, exit_edge));
     594       115802 :           gcond *cond_stmt = as_a <gcond *> (elt->stmt);
     595       115802 :           if (exit_edge->flags & EDGE_TRUE_VALUE)
     596        69457 :             gimple_cond_make_true (cond_stmt);
     597              :           else
     598        46345 :             gimple_cond_make_false (cond_stmt);
     599       115802 :           update_stmt (cond_stmt);
     600       115802 :           changed = true;
     601              :         }
     602              :     }
     603       152493 :   return changed;
     604              : }
     605              : 
     606              : /* Remove all exits that are known to be never taken because of the loop bound
     607              :    discovered.  */
     608              : 
     609              : static bool
     610      2356862 : remove_redundant_iv_tests (class loop *loop)
     611              : {
     612      2356862 :   class nb_iter_bound *elt;
     613      2356862 :   bool changed = false;
     614              : 
     615      2356862 :   if (!loop->any_upper_bound)
     616              :     return false;
     617      5682656 :   for (elt = loop->bounds; elt; elt = elt->next)
     618              :     {
     619              :       /* Exit is pointless if it won't be taken before loop reaches
     620              :          upper bound.  */
     621      1713197 :       if (elt->is_exit && loop->any_upper_bound
     622      5608744 :           && wi::ltu_p (loop->nb_iterations_upper_bound, elt->bound))
     623              :         {
     624       297154 :           basic_block bb = gimple_bb (elt->stmt);
     625       297154 :           edge exit_edge = EDGE_SUCC (bb, 0);
     626       297154 :           class tree_niter_desc niter;
     627              : 
     628       297154 :           if (!loop_exit_edge_p (loop, exit_edge))
     629       218309 :             exit_edge = EDGE_SUCC (bb, 1);
     630              : 
     631              :           /* Only when we know the actual number of iterations, not
     632              :              just a bound, we can remove the exit.  */
     633       297154 :           if (!number_of_iterations_exit (loop, exit_edge,
     634              :                                           &niter, false, false)
     635       297123 :               || !integer_onep (niter.assumptions)
     636       297123 :               || !integer_zerop (niter.may_be_zero)
     637       196036 :               || !niter.niter
     638       196036 :               || TREE_CODE (niter.niter) != INTEGER_CST
     639       299713 :               || !wi::ltu_p (widest_int::from (loop->nb_iterations_upper_bound,
     640              :                                                SIGNED),
     641       299713 :                              wi::to_widest (niter.niter)))
     642       294595 :             continue;
     643              : 
     644         2559 :           if (dump_file && (dump_flags & TDF_DETAILS))
     645              :             {
     646            2 :               fprintf (dump_file, "Removed pointless exit: ");
     647            2 :               print_gimple_stmt (dump_file, elt->stmt, 0);
     648              :             }
     649         2559 :           gcond *cond_stmt = as_a <gcond *> (elt->stmt);
     650         2559 :           if (exit_edge->flags & EDGE_TRUE_VALUE)
     651          579 :             gimple_cond_make_false (cond_stmt);
     652              :           else
     653         1980 :             gimple_cond_make_true (cond_stmt);
     654         2559 :           update_stmt (cond_stmt);
     655         2559 :           changed = true;
     656       297154 :         }
     657              :     }
     658              :   return changed;
     659              : }
     660              : 
     661              : /* Stores loops that will be unlooped and edges that will be removed
     662              :    after we process whole loop tree. */
     663              : static vec<loop_p> loops_to_unloop;
     664              : static vec<int> loops_to_unloop_nunroll;
     665              : static vec<edge> edges_to_remove;
     666              : /* Stores loops that has been peeled.  */
     667              : static bitmap peeled_loops;
     668              : 
     669              : /* Cancel all fully unrolled loops by putting __builtin_unreachable
     670              :    on the latch edge.
     671              :    We do it after all unrolling since unlooping moves basic blocks
     672              :    across loop boundaries trashing loop closed SSA form as well
     673              :    as SCEV info needed to be intact during unrolling.
     674              : 
     675              :    IRRED_INVALIDATED is used to bookkeep if information about
     676              :    irreducible regions may become invalid as a result
     677              :    of the transformation.
     678              :    LOOP_CLOSED_SSA_INVALIDATED is used to bookkeep the case
     679              :    when we need to go into loop closed SSA form.  */
     680              : 
     681              : void
     682       309771 : unloop_loops (vec<class loop *> &loops_to_unloop,
     683              :               vec<int> &loops_to_unloop_nunroll,
     684              :               vec<edge> &edges_to_remove,
     685              :               bitmap loop_closed_ssa_invalidated,
     686              :               bool *irred_invalidated)
     687              : {
     688       462264 :   while (loops_to_unloop.length ())
     689              :     {
     690       152493 :       class loop *loop = loops_to_unloop.pop ();
     691       152493 :       int n_unroll = loops_to_unloop_nunroll.pop ();
     692       152493 :       basic_block latch = loop->latch;
     693       152493 :       edge latch_edge = loop_latch_edge (loop);
     694       152493 :       int flags = latch_edge->flags;
     695       152493 :       location_t locus = latch_edge->goto_locus;
     696       152493 :       gcall *stmt;
     697       152493 :       gimple_stmt_iterator gsi;
     698              : 
     699       152493 :       remove_exits_and_undefined_stmts (loop, n_unroll);
     700              : 
     701              :       /* Unloop destroys the latch edge.  */
     702       152493 :       unloop (loop, irred_invalidated, loop_closed_ssa_invalidated);
     703              : 
     704              :       /* Create new basic block for the latch edge destination and wire
     705              :          it in.  */
     706       152493 :       stmt = gimple_build_builtin_unreachable (locus);
     707       152493 :       latch_edge = make_edge (latch, create_basic_block (NULL, NULL, latch), flags);
     708       152493 :       latch_edge->probability = profile_probability::never ();
     709       152493 :       latch_edge->flags |= flags;
     710       152493 :       latch_edge->goto_locus = locus;
     711              : 
     712       152493 :       add_bb_to_loop (latch_edge->dest, current_loops->tree_root);
     713       152493 :       latch_edge->dest->count = profile_count::zero ();
     714       152493 :       set_immediate_dominator (CDI_DOMINATORS, latch_edge->dest, latch_edge->src);
     715              : 
     716       152493 :       gsi = gsi_start_bb (latch_edge->dest);
     717       152493 :       gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
     718              :     }
     719              : 
     720              :   /* Remove edges in peeled copies.  Given remove_path removes dominated
     721              :      regions we need to cope with removal of already removed paths.  */
     722       309771 :   unsigned i;
     723       309771 :   edge e;
     724       309771 :   auto_vec<int, 20> src_bbs;
     725       347866 :   src_bbs.reserve_exact (edges_to_remove.length ());
     726       933075 :   FOR_EACH_VEC_ELT (edges_to_remove, i, e)
     727       313533 :     src_bbs.quick_push (e->src->index);
     728       623304 :   FOR_EACH_VEC_ELT (edges_to_remove, i, e)
     729       313533 :     if (BASIC_BLOCK_FOR_FN (cfun, src_bbs[i]))
     730              :       {
     731       313533 :         bool ok = remove_path (e, irred_invalidated,
     732              :                                loop_closed_ssa_invalidated);
     733       313533 :         gcc_assert (ok);
     734              :       }
     735       309771 :   edges_to_remove.release ();
     736       309771 : }
     737              : 
     738              : /* Tries to unroll LOOP completely, i.e. NITER times.
     739              :    UL determines which loops we are allowed to unroll.
     740              :    EXIT is the exit of the loop that should be eliminated.
     741              :    MAXITER specify bound on number of iterations, -1 if it is
     742              :    not known or too large for HOST_WIDE_INT.  The location
     743              :    LOCUS corresponding to the loop is used when emitting
     744              :    a summary of the unroll to the dump file.  */
     745              : 
     746              : static bool
     747      2356862 : try_unroll_loop_completely (class loop *loop,
     748              :                             edge exit, tree niter, bool may_be_zero,
     749              :                             enum unroll_level ul,
     750              :                             HOST_WIDE_INT maxiter,
     751              :                             dump_user_location_t locus, bool allow_peel,
     752              :                             bool cunrolli)
     753              : {
     754      2356862 :   unsigned HOST_WIDE_INT n_unroll = 0;
     755      2356862 :   bool n_unroll_found = false;
     756      2356862 :   edge edge_to_cancel = NULL;
     757              : 
     758              :   /* See if we proved number of iterations to be low constant.
     759              : 
     760              :      EXIT is an edge that will be removed in all but last iteration of
     761              :      the loop.
     762              : 
     763              :      EDGE_TO_CACNEL is an edge that will be removed from the last iteration
     764              :      of the unrolled sequence and is expected to make the final loop not
     765              :      rolling.
     766              : 
     767              :      If the number of execution of loop is determined by standard induction
     768              :      variable test, then EXIT and EDGE_TO_CANCEL are the two edges leaving
     769              :      from the iv test.  */
     770      2356862 :   if (tree_fits_uhwi_p (niter))
     771              :     {
     772      1100398 :       n_unroll = tree_to_uhwi (niter);
     773      1100398 :       n_unroll_found = true;
     774      1100398 :       edge_to_cancel = EDGE_SUCC (exit->src, 0);
     775      1100398 :       if (edge_to_cancel == exit)
     776       362603 :         edge_to_cancel = EDGE_SUCC (exit->src, 1);
     777              :     }
     778              :   /* We do not know the number of iterations and thus we cannot eliminate
     779              :      the EXIT edge.  */
     780              :   else
     781              :     exit = NULL;
     782              : 
     783              :   /* See if we can improve our estimate by using recorded loop bounds.  */
     784      2356862 :   if ((maxiter == 0 || ul != UL_SINGLE_ITER)
     785      1649104 :       && maxiter >= 0
     786      1204838 :       && (!n_unroll_found || (unsigned HOST_WIDE_INT)maxiter < n_unroll))
     787              :     {
     788       430739 :       n_unroll = maxiter;
     789       430739 :       n_unroll_found = true;
     790              :       /* Loop terminates before the IV variable test, so we cannot
     791              :          remove it in the last iteration.  */
     792       430739 :       edge_to_cancel = NULL;
     793              :       /* If we do not allow peeling and we iterate just allow cases
     794              :          that do not grow code.  */
     795       430739 :       if (!allow_peel && maxiter != 0)
     796              :         ul = UL_NO_GROWTH;
     797              :     }
     798              : 
     799      1926123 :   if (!n_unroll_found)
     800              :     return false;
     801              : 
     802      1531031 :   if (!loop->unroll
     803      1528689 :       && n_unroll > (unsigned) param_max_completely_peel_times)
     804              :     {
     805       799344 :       if (dump_file && (dump_flags & TDF_DETAILS))
     806           33 :         fprintf (dump_file, "Not unrolling loop %d "
     807              :                  "(--param max-completely-peel-times limit reached).\n",
     808              :                  loop->num);
     809              :       return false;
     810              :     }
     811              : 
     812       731687 :   if (!edge_to_cancel)
     813       109440 :     edge_to_cancel = loop_edge_to_cancel (loop);
     814              : 
     815       731687 :   if (n_unroll)
     816              :     {
     817       700613 :       if (ul == UL_SINGLE_ITER)
     818      2356862 :         return false;
     819              : 
     820       535469 :       if (loop->unroll)
     821              :         {
     822              :           /* If the unrolling factor is too large, bail out.  */
     823         1844 :           if (n_unroll > (unsigned)loop->unroll)
     824              :             {
     825         1303 :               if (dump_file && (dump_flags & TDF_DETAILS))
     826           44 :                 fprintf (dump_file,
     827              :                          "Not unrolling loop %d: "
     828              :                          "user didn't want it unrolled completely.\n",
     829              :                          loop->num);
     830              :               return false;
     831              :             }
     832              :         }
     833              :       else
     834              :         {
     835       533625 :           struct loop_size size;
     836              :           /* EXIT can be removed only if we are sure it passes first N_UNROLL
     837              :              iterations.  */
     838       533625 :           bool remove_exit = (exit && niter
     839       437523 :                               && TREE_CODE (niter) == INTEGER_CST
     840       971148 :                               && wi::leu_p (n_unroll, wi::to_widest (niter)));
     841       533625 :           bool large
     842              :             = tree_estimate_loop_size
     843       533625 :                 (loop, remove_exit ? exit : NULL, edge_to_cancel, &size,
     844              :                  param_max_completely_peeled_insns);
     845       533625 :           if (large)
     846              :             {
     847         6933 :               if (dump_file && (dump_flags & TDF_DETAILS))
     848            0 :                 fprintf (dump_file, "Not unrolling loop %d: it is too large.\n",
     849              :                          loop->num);
     850       415741 :               return false;
     851              :             }
     852              : 
     853       526692 :           unsigned HOST_WIDE_INT ninsns = size.overall;
     854       526692 :           unsigned HOST_WIDE_INT est_eliminated;
     855       526692 :           unsigned HOST_WIDE_INT unr_insns
     856       526692 :             = estimated_unrolled_size (&size, &est_eliminated, n_unroll);
     857       526692 :           if (dump_file && (dump_flags & TDF_DETAILS))
     858              :             {
     859           62 :               fprintf (dump_file, "  Loop size: %d\n", (int) ninsns);
     860           62 :               fprintf (dump_file, "  Estimated size after unrolling: %d-%d\n",
     861              :                        (int) unr_insns, (int) est_eliminated);
     862              :             }
     863              : 
     864              :           /* If the code is going to shrink, we don't need to be extra
     865              :              cautious on guessing if the unrolling is going to be
     866              :              profitable.
     867              :              Move from estimated_unrolled_size to unroll small loops.  */
     868       526692 :           if (unr_insns - est_eliminated
     869              :               /* If there is IV variable that will become constant, we
     870              :                  save one instruction in the loop prologue we do not
     871              :                  account otherwise.  */
     872       526692 :               <= ninsns + (size.constant_iv != false))
     873              :             ;
     874              :           /* We unroll only inner loops, because we do not consider it
     875              :              profitable otherwise.  We still can cancel loopback edge
     876              :              of not rolling loop; this is always a good idea.  */
     877       442576 :           else if (ul == UL_NO_GROWTH)
     878              :             {
     879       388561 :               if (dump_file && (dump_flags & TDF_DETAILS))
     880           24 :                 fprintf (dump_file, "Not unrolling loop %d: size would grow.\n",
     881              :                          loop->num);
     882              :               return false;
     883              :             }
     884              :           /* Outer loops tend to be less interesting candidates for
     885              :              complete unrolling unless we can do a lot of propagation
     886              :              into the inner loop body.  For now we disable outer loop
     887              :              unrolling when the code would grow.  */
     888        54015 :           else if (loop->inner)
     889              :             {
     890         5014 :               if (dump_file && (dump_flags & TDF_DETAILS))
     891            0 :                 fprintf (dump_file, "Not unrolling loop %d: "
     892              :                          "it is not innermost and code would grow.\n",
     893              :                          loop->num);
     894              :               return false;
     895              :             }
     896              :           /* If there is call on a hot path through the loop, then
     897              :              there is most probably not much to optimize.  */
     898        49001 :           else if (size.num_non_pure_calls_on_hot_path)
     899              :             {
     900        11116 :               if (dump_file && (dump_flags & TDF_DETAILS))
     901            1 :                 fprintf (dump_file, "Not unrolling loop %d: "
     902              :                          "contains call and code would grow.\n",
     903              :                          loop->num);
     904              :               return false;
     905              :             }
     906              :           /* If there is pure/const call in the function, then we can
     907              :              still optimize the unrolled loop body if it contains some
     908              :              other interesting code than the calls and code storing or
     909              :              cumulating the return value.  */
     910        37885 :           else if (size.num_pure_calls_on_hot_path
     911              :                    /* One IV increment, one test, one ivtmp store and
     912              :                       one useful stmt.  That is about minimal loop
     913              :                       doing pure call.  */
     914         2547 :                    && (size.non_call_stmts_on_hot_path
     915         2547 :                        <= 3 + size.num_pure_calls_on_hot_path))
     916              :             {
     917           30 :               if (dump_file && (dump_flags & TDF_DETAILS))
     918            0 :                 fprintf (dump_file, "Not unrolling loop %d: "
     919              :                          "contains just pure calls and code would grow.\n",
     920              :                          loop->num);
     921              :               return false;
     922              :             }
     923              :           /* Complete unrolling is major win when control flow is
     924              :              removed and one big basic block is created.  If the loop
     925              :              contains control flow the optimization may still be a win
     926              :              because of eliminating the loop overhead but it also may
     927              :              blow the branch predictor tables.  Limit number of
     928              :              branches on the hot path through the peeled sequence.  */
     929        37855 :           else if (size.num_branches_on_hot_path * (int)n_unroll
     930        37855 :                    > param_max_peel_branches)
     931              :             {
     932         2501 :               if (dump_file && (dump_flags & TDF_DETAILS))
     933            0 :                 fprintf (dump_file, "Not unrolling loop %d: "
     934              :                          "number of branches on hot path in the unrolled "
     935              :                          "sequence reaches --param max-peel-branches limit.\n",
     936              :                          loop->num);
     937              :               return false;
     938              :             }
     939              :           /* Move 2 / 3 reduction from estimated_unrolled_size, but don't reduce
     940              :              unrolled size for innermost loop.
     941              :              1) It could increase register pressure.
     942              :              2) Big loop after completely unroll may not be vectorized
     943              :              by BB vectorizer.  */
     944        35354 :           else if ((cunrolli ? unr_insns : unr_insns - est_eliminated)
     945        35354 :                    > (unsigned) param_max_completely_peeled_insns)
     946              :             {
     947         1586 :               if (dump_file && (dump_flags & TDF_DETAILS))
     948            1 :                 fprintf (dump_file, "Not unrolling loop %d: "
     949              :                          "number of insns in the unrolled sequence reaches "
     950              :                          "--param max-completely-peeled-insns limit.\n",
     951              :                          loop->num);
     952              :               return false;
     953              :             }
     954              :         }
     955              : 
     956       118425 :       if (!dbg_cnt (gimple_unroll))
     957              :         return false;
     958              : 
     959       118425 :       initialize_original_copy_tables ();
     960       118425 :       auto_sbitmap wont_exit (n_unroll + 1);
     961       118425 :       if (exit && niter
     962       106693 :           && TREE_CODE (niter) == INTEGER_CST
     963       225118 :           && wi::leu_p (n_unroll, wi::to_widest (niter)))
     964              :         {
     965       106693 :           bitmap_ones (wont_exit);
     966       213386 :           if (wi::eq_p (wi::to_widest (niter), n_unroll)
     967       106693 :               || edge_to_cancel)
     968       106684 :             bitmap_clear_bit (wont_exit, 0);
     969              :         }
     970              :       else
     971              :         {
     972        11732 :           exit = NULL;
     973        11732 :           bitmap_clear (wont_exit);
     974              :         }
     975       118425 :       if (may_be_zero)
     976            5 :         bitmap_clear_bit (wont_exit, 1);
     977              : 
     978              :       /* If loop was originally estimated to iterate too many times,
     979              :          reduce the profile to avoid new profile inconsistencies.  */
     980       118425 :       scale_loop_profile (loop, profile_probability::always (), n_unroll);
     981              : 
     982       118425 :       if (!gimple_duplicate_loop_body_to_header_edge (
     983              :             loop, loop_preheader_edge (loop), n_unroll, wont_exit, exit,
     984              :             &edges_to_remove,
     985              :             DLTHE_FLAG_UPDATE_FREQ | DLTHE_FLAG_COMPLETTE_PEEL))
     986              :         {
     987            7 :           free_original_copy_tables ();
     988            7 :           if (dump_file && (dump_flags & TDF_DETAILS))
     989            0 :             fprintf (dump_file, "Failed to duplicate the loop\n");
     990            7 :           return false;
     991              :         }
     992              : 
     993       118418 :       free_original_copy_tables ();
     994       118425 :     }
     995              :   else
     996        31074 :     scale_loop_profile (loop, profile_probability::always (), 0);
     997              : 
     998              :   /* Remove the conditional from the last copy of the loop.  */
     999       149492 :   if (edge_to_cancel)
    1000              :     {
    1001       298800 :       gcond *cond = as_a <gcond *> (*gsi_last_bb (edge_to_cancel->src));
    1002       149400 :       force_edge_cold (edge_to_cancel, true);
    1003       149400 :       if (edge_to_cancel->flags & EDGE_TRUE_VALUE)
    1004        67866 :         gimple_cond_make_false (cond);
    1005              :       else
    1006        81534 :         gimple_cond_make_true (cond);
    1007       149400 :       update_stmt (cond);
    1008              :       /* Do not remove the path, as doing so may remove outer loop and
    1009              :          confuse bookkeeping code in tree_unroll_loops_completely.  */
    1010              :     }
    1011              : 
    1012              :   /* Store the loop for later unlooping and exit removal.  */
    1013       149492 :   loops_to_unloop.safe_push (loop);
    1014       149492 :   loops_to_unloop_nunroll.safe_push (n_unroll);
    1015              : 
    1016       149492 :   if (dump_enabled_p ())
    1017              :     {
    1018          164 :       if (!n_unroll)
    1019           63 :         dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus,
    1020              :                          "loop turned into non-loop; it never loops\n");
    1021              :       else
    1022              :         {
    1023          101 :           dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus,
    1024              :                            "loop with %d iterations completely unrolled",
    1025              :                            (int) n_unroll);
    1026          101 :           if (loop->header->count.initialized_p ())
    1027          100 :             dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS,
    1028              :                          " (header execution count %d)",
    1029          100 :                          (int)loop->header->count.to_gcov_type ());
    1030          101 :           dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, "\n");
    1031              :         }
    1032              :     }
    1033              : 
    1034       149492 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1035              :     {
    1036          101 :       if (exit)
    1037           76 :         fprintf (dump_file, "Exit condition of peeled iterations was "
    1038              :                  "eliminated.\n");
    1039          101 :       if (edge_to_cancel)
    1040          101 :         fprintf (dump_file, "Last iteration exit edge was proved true.\n");
    1041              :       else
    1042            0 :         fprintf (dump_file, "Latch of last iteration was marked by "
    1043              :                  "__builtin_unreachable ().\n");
    1044              :     }
    1045              : 
    1046              :   return true;
    1047              : }
    1048              : 
    1049              : /* Return number of instructions after peeling.  */
    1050              : static unsigned HOST_WIDE_INT
    1051          722 : estimated_peeled_sequence_size (struct loop_size *size,
    1052              :                                 unsigned HOST_WIDE_INT npeel)
    1053              : {
    1054          722 :   return MAX (npeel * (HOST_WIDE_INT) (size->overall
    1055              :                                        - size->eliminated_by_peeling), 1);
    1056              : }
    1057              : 
    1058              : /* Update loop estimates after peeling LOOP by NPEEL.
    1059              :    If PRECISE is false only likely exists were duplicated and thus
    1060              :    do not update any estimates that are supposed to be always reliable.  */
    1061              : void
    1062       472035 : adjust_loop_info_after_peeling (class loop *loop, int npeel, bool precise)
    1063              : {
    1064       472035 :   if (loop->any_estimate)
    1065              :     {
    1066              :       /* Since peeling is mostly about loops where first few
    1067              :          iterations are special, it is not quite correct to
    1068              :          assume that the remaining iterations will behave
    1069              :          the same way.  However we do not have better info
    1070              :          so update the estimate, since it is likely better
    1071              :          than keeping it as it is.
    1072              : 
    1073              :          Remove it if it looks wrong.
    1074              : 
    1075              :          TODO: We likely want to special case the situation where
    1076              :          peeling is optimizing out exit edges and only update
    1077              :          estimates here.  */
    1078       240277 :       if (wi::leu_p (npeel, loop->nb_iterations_estimate))
    1079       240261 :         loop->nb_iterations_estimate -= npeel;
    1080              :       else
    1081           16 :         loop->any_estimate = false;
    1082              :     }
    1083       472035 :   if (loop->any_upper_bound && precise)
    1084              :     {
    1085       279973 :       if (wi::leu_p (npeel, loop->nb_iterations_upper_bound))
    1086       279973 :         loop->nb_iterations_upper_bound -= npeel;
    1087              :       else
    1088              :         {
    1089              :           /* Peeling maximal number of iterations or more
    1090              :              makes no sense and is a bug.
    1091              :              We should peel completely.  */
    1092            0 :           gcc_unreachable ();
    1093              :         }
    1094              :     }
    1095       472035 :   if (loop->any_likely_upper_bound)
    1096              :     {
    1097       393141 :       if (wi::leu_p (npeel, loop->nb_iterations_likely_upper_bound))
    1098       392900 :         loop->nb_iterations_likely_upper_bound -= npeel;
    1099              :       else
    1100              :         {
    1101          241 :           loop->any_estimate = true;
    1102          241 :           loop->nb_iterations_estimate = 0;
    1103          241 :           loop->nb_iterations_likely_upper_bound = 0;
    1104              :         }
    1105              :     }
    1106       472035 : }
    1107              : 
    1108              : /* If the loop is expected to iterate N times and is
    1109              :    small enough, duplicate the loop body N+1 times before
    1110              :    the loop itself.  This way the hot path will never
    1111              :    enter the loop.
    1112              :    Parameters are the same as for try_unroll_loops_completely */
    1113              : 
    1114              : static bool
    1115       132931 : try_peel_loop (class loop *loop,
    1116              :                edge exit, tree niter, bool may_be_zero,
    1117              :                HOST_WIDE_INT maxiter)
    1118              : {
    1119       132931 :   HOST_WIDE_INT npeel;
    1120       132931 :   struct loop_size size;
    1121       132931 :   int peeled_size;
    1122              : 
    1123       132931 :   if (!flag_peel_loops
    1124       114641 :       || param_max_peel_times <= 0
    1125       114641 :       || !peeled_loops)
    1126              :     return false;
    1127              : 
    1128        85597 :   if (bitmap_bit_p (peeled_loops, loop->num))
    1129              :     {
    1130          226 :       if (dump_file)
    1131            2 :         fprintf (dump_file, "Not peeling: loop is already peeled\n");
    1132              :       return false;
    1133              :     }
    1134              : 
    1135              :   /* We don't peel loops that will be unrolled as this can duplicate a
    1136              :      loop more times than the user requested.  */
    1137        85371 :   if (loop->unroll)
    1138              :     {
    1139          101 :       if (dump_file)
    1140            0 :         fprintf (dump_file, "Not peeling: user didn't want it peeled.\n");
    1141              :       return false;
    1142              :     }
    1143              : 
    1144              :   /* Peel only innermost loops.
    1145              :      While the code is perfectly capable of peeling non-innermost loops,
    1146              :      the heuristics would probably need some improvements. */
    1147        85270 :   if (loop->inner)
    1148              :     {
    1149        15629 :       if (dump_file)
    1150            2 :         fprintf (dump_file, "Not peeling: outer loop\n");
    1151              :       return false;
    1152              :     }
    1153              : 
    1154        69641 :   if (!optimize_loop_for_speed_p (loop))
    1155              :     {
    1156            0 :       if (dump_file)
    1157            0 :         fprintf (dump_file, "Not peeling: cold loop\n");
    1158              :       return false;
    1159              :     }
    1160              : 
    1161              :   /* Check if there is an estimate on the number of iterations.  */
    1162        69641 :   npeel = estimated_loop_iterations_int (loop);
    1163        69641 :   if (npeel < 0)
    1164        50532 :     npeel = likely_max_loop_iterations_int (loop);
    1165        69641 :   if (npeel < 0)
    1166              :     {
    1167        14363 :       if (dump_file)
    1168            0 :         fprintf (dump_file, "Not peeling: number of iterations is not "
    1169              :                  "estimated\n");
    1170              :       return false;
    1171              :     }
    1172        55278 :   if (maxiter >= 0 && maxiter <= npeel)
    1173              :     {
    1174        53461 :       if (dump_file)
    1175           23 :         fprintf (dump_file, "Not peeling: upper bound is known so can "
    1176              :                  "unroll completely\n");
    1177              :       return false;
    1178              :     }
    1179              : 
    1180              :   /* We want to peel estimated number of iterations + 1 (so we never
    1181              :      enter the loop on quick path).  Check against PARAM_MAX_PEEL_TIMES
    1182              :      and be sure to avoid overflows.  */
    1183         1817 :   if (npeel > param_max_peel_times - 1)
    1184              :     {
    1185         1095 :       if (dump_file)
    1186            0 :         fprintf (dump_file, "Not peeling: rolls too much "
    1187              :                  "(%i + 1 > --param max-peel-times)\n", (int) npeel);
    1188              :       return false;
    1189              :     }
    1190          722 :   npeel++;
    1191              : 
    1192              :   /* Check peeled loops size.  */
    1193          722 :   tree_estimate_loop_size (loop, exit, NULL, &size,
    1194              :                            param_max_peeled_insns);
    1195          722 :   if ((peeled_size = estimated_peeled_sequence_size (&size, (int) npeel))
    1196          722 :       > param_max_peeled_insns)
    1197              :     {
    1198          472 :       if (dump_file)
    1199            0 :         fprintf (dump_file, "Not peeling: peeled sequence size is too large "
    1200              :                  "(%i insns > --param max-peel-insns)", peeled_size);
    1201              :       return false;
    1202              :     }
    1203              : 
    1204          250 :   if (!dbg_cnt (gimple_unroll))
    1205              :     return false;
    1206              : 
    1207              :   /* Duplicate possibly eliminating the exits.  */
    1208          250 :   initialize_original_copy_tables ();
    1209          250 :   auto_sbitmap wont_exit (npeel + 1);
    1210          250 :   if (exit && niter
    1211            7 :       && TREE_CODE (niter) == INTEGER_CST
    1212          257 :       && wi::leu_p (npeel, wi::to_widest (niter)))
    1213              :     {
    1214            7 :       bitmap_ones (wont_exit);
    1215            7 :       bitmap_clear_bit (wont_exit, 0);
    1216              :     }
    1217              :   else
    1218              :     {
    1219          243 :       exit = NULL;
    1220          243 :       bitmap_clear (wont_exit);
    1221              :     }
    1222          250 :   if (may_be_zero)
    1223            0 :     bitmap_clear_bit (wont_exit, 1);
    1224              : 
    1225          250 :   if (!gimple_duplicate_loop_body_to_header_edge (
    1226              :         loop, loop_preheader_edge (loop), npeel, wont_exit, exit,
    1227              :         &edges_to_remove,
    1228              :         DLTHE_FLAG_UPDATE_FREQ))
    1229              :     {
    1230            0 :       free_original_copy_tables ();
    1231            0 :       return false;
    1232              :     }
    1233          250 :   free_original_copy_tables ();
    1234          250 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1235              :     {
    1236            3 :       fprintf (dump_file, "Peeled loop %d, %i times.\n",
    1237              :                loop->num, (int) npeel);
    1238              :     }
    1239          250 :   adjust_loop_info_after_peeling (loop, npeel, true);
    1240              : 
    1241          250 :   bitmap_set_bit (peeled_loops, loop->num);
    1242          250 :   return true;
    1243          250 : }
    1244              : /* Adds a canonical induction variable to LOOP if suitable.
    1245              :    CREATE_IV is true if we may create a new iv.  UL determines
    1246              :    which loops we are allowed to completely unroll.  If TRY_EVAL is true, we try
    1247              :    to determine the number of iterations of a loop by direct evaluation.
    1248              :    Returns true if cfg is changed.   */
    1249              : 
    1250              : static bool
    1251      2356862 : canonicalize_loop_induction_variables (class loop *loop,
    1252              :                                        bool create_iv, enum unroll_level ul,
    1253              :                                        bool try_eval, bool allow_peel,
    1254              :                                        const_sbitmap innermost,
    1255              :                                        bool cunrolli)
    1256              : {
    1257      2356862 :   edge exit = NULL;
    1258      2356862 :   tree niter;
    1259      2356862 :   HOST_WIDE_INT maxiter;
    1260      2356862 :   bool modified = false;
    1261      2356862 :   class tree_niter_desc niter_desc;
    1262      2356862 :   bool may_be_zero = false;
    1263      2356862 :   bool by_eval = false;
    1264              : 
    1265              :   /* For unrolling allow conditional constant or zero iterations, thus
    1266              :      perform loop-header copying on-the-fly.  */
    1267      2356862 :   exit = single_exit (loop);
    1268      2356862 :   niter = chrec_dont_know;
    1269      2356862 :   if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
    1270              :     {
    1271      1176396 :       niter = niter_desc.niter;
    1272      1176396 :       may_be_zero
    1273      1176396 :         = niter_desc.may_be_zero && !integer_zerop (niter_desc.may_be_zero);
    1274              :     }
    1275      2356862 :   if (TREE_CODE (niter) != INTEGER_CST)
    1276              :     {
    1277              :       /* For non-constant niter fold may_be_zero into niter again.  */
    1278      1629207 :       if (may_be_zero)
    1279              :         {
    1280       133965 :           if (COMPARISON_CLASS_P (niter_desc.may_be_zero))
    1281       133962 :             niter = fold_build3 (COND_EXPR, TREE_TYPE (niter),
    1282              :                                  niter_desc.may_be_zero,
    1283              :                                  build_int_cst (TREE_TYPE (niter), 0), niter);
    1284              :           else
    1285            3 :             niter = chrec_dont_know;
    1286              :           may_be_zero = false;
    1287              :         }
    1288              : 
    1289              :       /* If the loop has more than one exit, try checking all of them
    1290              :          for # of iterations determinable through scev.  */
    1291      1629207 :       if (!exit)
    1292       793242 :         niter = find_loop_niter (loop, &exit);
    1293              : 
    1294              :       /* Finally if everything else fails, try brute force evaluation.  */
    1295      1629207 :       if (try_eval
    1296      1629207 :           && (chrec_contains_undetermined (niter)
    1297       544706 :               || TREE_CODE (niter) != INTEGER_CST))
    1298              :         {
    1299       819649 :           niter = find_loop_niter_by_eval (loop, &exit);
    1300       819649 :           if (TREE_CODE (niter) == INTEGER_CST)
    1301        15715 :             by_eval = true;
    1302              :         }
    1303              : 
    1304      1629207 :       if (TREE_CODE (niter) != INTEGER_CST)
    1305      1256464 :         exit = NULL;
    1306              :     }
    1307              : 
    1308              :   /* We work exceptionally hard here to estimate the bound
    1309              :      by find_loop_niter_by_eval.  Be sure to keep it for future.  */
    1310      2356862 :   if (niter && TREE_CODE (niter) == INTEGER_CST)
    1311              :     {
    1312      1100398 :       auto_vec<edge> exits = get_loop_exit_edges  (loop);
    1313      1100398 :       record_niter_bound (loop, wi::to_widest (niter),
    1314      1100398 :                           exit == single_likely_exit (loop, exits), true);
    1315      1100398 :     }
    1316              : 
    1317              :   /* Force re-computation of loop bounds so we can remove redundant exits.  */
    1318      2356862 :   maxiter = max_loop_iterations_int (loop);
    1319              : 
    1320          304 :   if (dump_file && (dump_flags & TDF_DETAILS)
    1321      2357108 :       && TREE_CODE (niter) == INTEGER_CST)
    1322              :     {
    1323          146 :       fprintf (dump_file, "Loop %d iterates ", loop->num);
    1324          146 :       print_generic_expr (dump_file, niter, TDF_SLIM);
    1325          146 :       fprintf (dump_file, " times.\n");
    1326              :     }
    1327          304 :   if (dump_file && (dump_flags & TDF_DETAILS)
    1328      2357108 :       && maxiter >= 0)
    1329              :     {
    1330          210 :       fprintf (dump_file, "Loop %d iterates at most %i times.\n", loop->num,
    1331              :                (int)maxiter);
    1332              :     }
    1333          304 :   if (dump_file && (dump_flags & TDF_DETAILS)
    1334      2357108 :       && likely_max_loop_iterations_int (loop) >= 0)
    1335              :     {
    1336          210 :       fprintf (dump_file, "Loop %d likely iterates at most %i times.\n",
    1337          210 :                loop->num, (int)likely_max_loop_iterations_int (loop));
    1338              :     }
    1339              : 
    1340              :   /* Remove exits that are known to be never taken based on loop bound.
    1341              :      Needs to be called after compilation of max_loop_iterations_int that
    1342              :      populates the loop bounds.  */
    1343      2356862 :   modified |= remove_redundant_iv_tests (loop);
    1344              : 
    1345      2356862 :   dump_user_location_t locus = find_loop_location (loop);
    1346              : 
    1347      2356862 :   bool innermost_cunrolli_p
    1348              :     = cunrolli
    1349       806825 :       && (unsigned) loop->num < SBITMAP_SIZE (innermost)
    1350      3160715 :       && bitmap_bit_p (innermost, loop->num);
    1351              : 
    1352      2356862 :   if (try_unroll_loop_completely (loop, exit, niter, may_be_zero, ul,
    1353              :                                   maxiter, locus, allow_peel,
    1354              :                                   innermost_cunrolli_p))
    1355              :     return true;
    1356              : 
    1357      2207370 :   if ((create_iv || by_eval)
    1358       710099 :       && niter && !chrec_contains_undetermined (niter)
    1359      2535884 :       && exit && just_once_each_iteration_p (loop, exit->src))
    1360              :     {
    1361       328512 :       tree iv_niter = niter;
    1362       328512 :       if (may_be_zero)
    1363              :         {
    1364           21 :           if (COMPARISON_CLASS_P (niter_desc.may_be_zero))
    1365           21 :             iv_niter = fold_build3 (COND_EXPR, TREE_TYPE (iv_niter),
    1366              :                                     niter_desc.may_be_zero,
    1367              :                                     build_int_cst (TREE_TYPE (iv_niter), 0),
    1368              :                                     iv_niter);
    1369              :           else
    1370              :             iv_niter = NULL_TREE;
    1371              :         }
    1372       328512 :       if (iv_niter)
    1373       328512 :         create_canonical_iv (loop, exit, iv_niter);
    1374              :     }
    1375              : 
    1376      2207370 :   if (ul == UL_ALL)
    1377       132931 :     modified |= try_peel_loop (loop, exit, niter, may_be_zero, maxiter);
    1378              : 
    1379              :   return modified;
    1380      2356862 : }
    1381              : 
    1382              : /* The main entry point of the pass.  Adds canonical induction variables
    1383              :    to the suitable loops.  */
    1384              : 
    1385              : unsigned int
    1386       251572 : canonicalize_induction_variables (void)
    1387              : {
    1388       251572 :   bool changed = false;
    1389       251572 :   bool irred_invalidated = false;
    1390       251572 :   bitmap loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
    1391       503144 :   auto_sbitmap innermost (number_of_loops (cfun));
    1392       251572 :   bitmap_clear (innermost);
    1393              : 
    1394       251572 :   estimate_numbers_of_iterations (cfun);
    1395              : 
    1396      1462732 :   for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
    1397              :     {
    1398       708016 :       changed
    1399       708016 :         |= canonicalize_loop_induction_variables (loop,
    1400              :                                                   true, UL_SINGLE_ITER,
    1401              :                                                   true, false,
    1402       708016 :                                                   (const_sbitmap) innermost,
    1403              :                                                   false);
    1404       251572 :     }
    1405       251572 :   gcc_assert (!need_ssa_update_p (cfun));
    1406              : 
    1407       251572 :   unloop_loops (loops_to_unloop, loops_to_unloop_nunroll, edges_to_remove,
    1408              :                 loop_closed_ssa_invalidated, &irred_invalidated);
    1409       251572 :   loops_to_unloop.release ();
    1410       251572 :   loops_to_unloop_nunroll.release ();
    1411       251572 :   if (irred_invalidated
    1412       251572 :       && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
    1413            6 :     mark_irreducible_loops ();
    1414              : 
    1415              :   /* Clean up the information about numbers of iterations, since brute force
    1416              :      evaluation could reveal new information.  */
    1417       251572 :   free_numbers_of_iterations_estimates (cfun);
    1418       251572 :   scev_reset ();
    1419              : 
    1420       251572 :   if (!bitmap_empty_p (loop_closed_ssa_invalidated))
    1421              :     {
    1422           28 :       gcc_checking_assert (loops_state_satisfies_p (LOOP_CLOSED_SSA));
    1423           28 :       rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
    1424              :     }
    1425       251572 :   BITMAP_FREE (loop_closed_ssa_invalidated);
    1426              : 
    1427       251572 :   if (changed)
    1428         1102 :     return TODO_cleanup_cfg;
    1429              :   return 0;
    1430       251572 : }
    1431              : 
    1432              : /* Process loops from innermost to outer, stopping at the innermost
    1433              :    loop we unrolled.  */
    1434              : 
    1435              : static bool
    1436      2244066 : tree_unroll_loops_completely_1 (bool may_increase_size, bool unroll_outer,
    1437              :                                 bitmap father_bbs, class loop *loop,
    1438              :                                 const_sbitmap innermost, bool cunrolli)
    1439              : {
    1440      2244066 :   class loop *loop_father;
    1441      2244066 :   bool changed = false;
    1442      2244066 :   class loop *inner;
    1443      2244066 :   enum unroll_level ul;
    1444      2244066 :   unsigned num = number_of_loops (cfun);
    1445              : 
    1446              :   /* Process inner loops first.  Don't walk loops added by the recursive
    1447              :      calls because SSA form is not up-to-date.  They can be handled in the
    1448              :      next iteration.  */
    1449      2244066 :   bitmap child_father_bbs = NULL;
    1450      3948804 :   for (inner = loop->inner; inner != NULL; inner = inner->next)
    1451      1704738 :     if ((unsigned) inner->num < num)
    1452              :       {
    1453      1702614 :         if (!child_father_bbs)
    1454       802072 :           child_father_bbs = BITMAP_ALLOC (NULL);
    1455      1702614 :         if (tree_unroll_loops_completely_1 (may_increase_size, unroll_outer,
    1456              :                                             child_father_bbs, inner,
    1457              :                                             innermost, cunrolli))
    1458              :           {
    1459       191853 :             bitmap_ior_into (father_bbs, child_father_bbs);
    1460       191853 :             bitmap_clear (child_father_bbs);
    1461       191853 :             changed = true;
    1462              :           }
    1463              :       }
    1464      2244066 :   if (child_father_bbs)
    1465       802072 :     BITMAP_FREE (child_father_bbs);
    1466              : 
    1467              :   /* If we changed an inner loop we cannot process outer loops in this
    1468              :      iteration because SSA form is not up-to-date.  Continue with
    1469              :      siblings of outer loops instead.  */
    1470      2244066 :   if (changed)
    1471              :     {
    1472              :       /* If we are recorded as father clear all other fathers that
    1473              :          are necessarily covered already to avoid redundant work.  */
    1474        99524 :       if (bitmap_bit_p (father_bbs, loop->header->index))
    1475              :         {
    1476        30440 :           bitmap_clear (father_bbs);
    1477        30440 :           bitmap_set_bit (father_bbs, loop->header->index);
    1478              :         }
    1479              :       return true;
    1480              :     }
    1481              : 
    1482              :   /* Don't unroll #pragma omp simd loops until the vectorizer
    1483              :      attempts to vectorize those.  */
    1484      2144542 :   if (loop->force_vectorize)
    1485              :     return false;
    1486              : 
    1487              :   /* Try to unroll this loop.  */
    1488      2132979 :   loop_father = loop_outer (loop);
    1489      2132979 :   if (!loop_father)
    1490              :     return false;
    1491              : 
    1492      1648846 :   if (loop->unroll > 1)
    1493              :     ul = UL_ALL;
    1494       289816 :   else if (may_increase_size && optimize_loop_nest_for_speed_p (loop)
    1495              :       /* Unroll outermost loops only if asked to do so or they do
    1496              :          not cause code growth.  */
    1497      1929055 :       && (unroll_outer || loop_outer (loop_father)))
    1498              :     ul = UL_ALL;
    1499              :   else
    1500              :     ul = UL_NO_GROWTH;
    1501              : 
    1502      1648846 :   if (canonicalize_loop_induction_variables
    1503      1648891 :       (loop, false, ul, !flag_tree_loop_ivcanon || cunrolli, unroll_outer,
    1504              :        innermost, cunrolli))
    1505              :     {
    1506              :       /* If we'll continue unrolling, we need to propagate constants
    1507              :          within the new basic blocks to fold away induction variable
    1508              :          computations; otherwise, the size might blow up before the
    1509              :          iteration is complete and the IR eventually cleaned up.  */
    1510       149648 :       if (loop_outer (loop_father))
    1511              :         {
    1512              :           /* Once we process our father we will have processed
    1513              :              the fathers of our children as well, so avoid doing
    1514              :              redundant work and clear fathers we've gathered sofar.  */
    1515        39804 :           bitmap_clear (father_bbs);
    1516        39804 :           bitmap_set_bit (father_bbs, loop_father->header->index);
    1517              :         }
    1518       109844 :       else if (unroll_outer)
    1519              :         /* Trigger scalar cleanup once any outermost loop gets unrolled.  */
    1520        64301 :         cfun->pending_TODOs |= PENDING_TODO_force_next_scalar_cleanup;
    1521              : 
    1522              :       return true;
    1523              :     }
    1524              : 
    1525              :   return false;
    1526              : }
    1527              : 
    1528              : /* Unroll LOOPS completely if they iterate just few times.  Unless
    1529              :    MAY_INCREASE_SIZE is true, perform the unrolling only if the
    1530              :    size of the code does not increase.
    1531              :    cunrolli is true when pass is cunrolli.  */
    1532              : 
    1533              : static unsigned int
    1534       484148 : tree_unroll_loops_completely (bool may_increase_size, bool unroll_outer, bool cunrolli)
    1535              : {
    1536       484148 :   bitmap father_bbs = BITMAP_ALLOC (NULL);
    1537       484148 :   bool changed;
    1538       484148 :   int iteration = 0;
    1539       484148 :   bool irred_invalidated = false;
    1540       968296 :   auto_sbitmap innermost (number_of_loops (cfun));
    1541       484148 :   bitmap_clear (innermost);
    1542              : 
    1543       484148 :   estimate_numbers_of_iterations (cfun);
    1544              : 
    1545              :   /* Mark all innermost loop at the beginning.  */
    1546      2909385 :   for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
    1547              :     {
    1548      1456941 :       if (!loop->inner)
    1549      1204460 :         bitmap_set_bit (innermost, loop->num);
    1550       484148 :     }
    1551              : 
    1552       541452 :   do
    1553              :     {
    1554       541452 :       changed = false;
    1555       541452 :       bitmap loop_closed_ssa_invalidated = NULL;
    1556              : 
    1557       541452 :       if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
    1558       287418 :         loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
    1559              : 
    1560       541452 :       free_numbers_of_iterations_estimates (cfun);
    1561       541452 :       estimate_numbers_of_iterations (cfun);
    1562              : 
    1563      1082904 :       changed = tree_unroll_loops_completely_1 (may_increase_size,
    1564              :                                                 unroll_outer, father_bbs,
    1565       541452 :                                                 current_loops->tree_root,
    1566       541452 :                                                 (const_sbitmap) innermost,
    1567              :                                                 cunrolli);
    1568       541452 :       if (changed)
    1569              :         {
    1570        57319 :           unsigned i;
    1571              : 
    1572        57319 :           unloop_loops (loops_to_unloop, loops_to_unloop_nunroll,
    1573              :                         edges_to_remove, loop_closed_ssa_invalidated,
    1574              :                         &irred_invalidated);
    1575        57319 :           loops_to_unloop.release ();
    1576        57319 :           loops_to_unloop_nunroll.release ();
    1577              : 
    1578              :           /* We cannot use TODO_update_ssa_no_phi because VOPS gets confused.  */
    1579        57319 :           if (loop_closed_ssa_invalidated
    1580        57319 :               && !bitmap_empty_p (loop_closed_ssa_invalidated))
    1581         8392 :             rewrite_into_loop_closed_ssa (loop_closed_ssa_invalidated,
    1582              :                                           TODO_update_ssa);
    1583              :           else
    1584        48927 :             update_ssa (TODO_update_ssa);
    1585              : 
    1586              :           /* father_bbs is a bitmap of loop father header BB indices.
    1587              :              Translate that to what non-root loops these BBs belong to now.  */
    1588        57319 :           bitmap_iterator bi;
    1589        57319 :           bitmap fathers = BITMAP_ALLOC (NULL);
    1590        86188 :           EXECUTE_IF_SET_IN_BITMAP (father_bbs, 0, i, bi)
    1591              :             {
    1592        28869 :               basic_block unrolled_loop_bb = BASIC_BLOCK_FOR_FN (cfun, i);
    1593        28869 :               if (! unrolled_loop_bb)
    1594            0 :                 continue;
    1595        28869 :               if (loop_outer (unrolled_loop_bb->loop_father))
    1596        28869 :                 bitmap_set_bit (fathers,
    1597              :                                 unrolled_loop_bb->loop_father->num);
    1598              :             }
    1599        57319 :           bitmap_clear (father_bbs);
    1600              :           /* Propagate the constants within the new basic blocks.  */
    1601        86188 :           EXECUTE_IF_SET_IN_BITMAP (fathers, 0, i, bi)
    1602              :             {
    1603        28869 :               loop_p father = get_loop (cfun, i);
    1604        28869 :               bitmap exit_bbs = BITMAP_ALLOC (NULL);
    1605        28869 :               loop_exit *exit = father->exits->next;
    1606       140139 :               while (exit->e)
    1607              :                 {
    1608       111270 :                   bitmap_set_bit (exit_bbs, exit->e->dest->index);
    1609       111270 :                   exit = exit->next;
    1610              :                 }
    1611        28869 :               do_rpo_vn (cfun, loop_preheader_edge (father), exit_bbs);
    1612              :             }
    1613        57319 :           BITMAP_FREE (fathers);
    1614              : 
    1615              :           /* Clean up the information about numbers of iterations, since
    1616              :              complete unrolling might have invalidated it.  */
    1617        57319 :           scev_reset ();
    1618              : 
    1619              :           /* This will take care of removing completely unrolled loops
    1620              :              from the loop structures so we can continue unrolling now
    1621              :              innermost loops.  */
    1622        57319 :           if (cleanup_tree_cfg ())
    1623        57319 :             update_ssa (TODO_update_ssa_only_virtuals);
    1624              : 
    1625        57319 :           if (flag_checking && loops_state_satisfies_p (LOOP_CLOSED_SSA))
    1626        35852 :             verify_loop_closed_ssa (true);
    1627              :         }
    1628       541452 :       if (loop_closed_ssa_invalidated)
    1629       287418 :         BITMAP_FREE (loop_closed_ssa_invalidated);
    1630              :     }
    1631              :   while (changed
    1632       541467 :          && ++iteration <= param_max_unroll_iterations);
    1633              : 
    1634       484148 :   BITMAP_FREE (father_bbs);
    1635              : 
    1636       484148 :   if (irred_invalidated
    1637       484148 :       && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
    1638           22 :     mark_irreducible_loops ();
    1639              : 
    1640       484148 :   return 0;
    1641       484148 : }
    1642              : 
    1643              : /* Canonical induction variable creation pass.  */
    1644              : 
    1645              : namespace {
    1646              : 
    1647              : const pass_data pass_data_iv_canon =
    1648              : {
    1649              :   GIMPLE_PASS, /* type */
    1650              :   "ivcanon", /* name */
    1651              :   OPTGROUP_LOOP, /* optinfo_flags */
    1652              :   TV_TREE_LOOP_IVCANON, /* tv_id */
    1653              :   ( PROP_cfg | PROP_ssa ), /* properties_required */
    1654              :   0, /* properties_provided */
    1655              :   0, /* properties_destroyed */
    1656              :   0, /* todo_flags_start */
    1657              :   0, /* todo_flags_finish */
    1658              : };
    1659              : 
    1660              : class pass_iv_canon : public gimple_opt_pass
    1661              : {
    1662              : public:
    1663       302985 :   pass_iv_canon (gcc::context *ctxt)
    1664       605970 :     : gimple_opt_pass (pass_data_iv_canon, ctxt)
    1665              :   {}
    1666              : 
    1667              :   /* opt_pass methods: */
    1668       251589 :   bool gate (function *) final override { return flag_tree_loop_ivcanon != 0; }
    1669              :   unsigned int execute (function *fun) final override;
    1670              : 
    1671              : }; // class pass_iv_canon
    1672              : 
    1673              : unsigned int
    1674       251572 : pass_iv_canon::execute (function *fun)
    1675              : {
    1676       503144 :   if (number_of_loops (fun) <= 1)
    1677              :     return 0;
    1678              : 
    1679       251572 :   return canonicalize_induction_variables ();
    1680              : }
    1681              : 
    1682              : } // anon namespace
    1683              : 
    1684              : gimple_opt_pass *
    1685       302985 : make_pass_iv_canon (gcc::context *ctxt)
    1686              : {
    1687       302985 :   return new pass_iv_canon (ctxt);
    1688              : }
    1689              : 
    1690              : /* Complete unrolling of loops.  */
    1691              : 
    1692              : namespace {
    1693              : 
    1694              : const pass_data pass_data_complete_unroll =
    1695              : {
    1696              :   GIMPLE_PASS, /* type */
    1697              :   "cunroll", /* name */
    1698              :   OPTGROUP_LOOP, /* optinfo_flags */
    1699              :   TV_COMPLETE_UNROLL, /* tv_id */
    1700              :   ( PROP_cfg | PROP_ssa ), /* properties_required */
    1701              :   0, /* properties_provided */
    1702              :   0, /* properties_destroyed */
    1703              :   0, /* todo_flags_start */
    1704              :   0, /* todo_flags_finish */
    1705              : };
    1706              : 
    1707              : class pass_complete_unroll : public gimple_opt_pass
    1708              : {
    1709              : public:
    1710       302985 :   pass_complete_unroll (gcc::context *ctxt)
    1711       605970 :     : gimple_opt_pass (pass_data_complete_unroll, ctxt)
    1712              :   {}
    1713              : 
    1714              :   /* opt_pass methods: */
    1715              :   unsigned int execute (function *) final override;
    1716              : 
    1717              : }; // class pass_complete_unroll
    1718              : 
    1719              : unsigned int
    1720       251568 : pass_complete_unroll::execute (function *fun)
    1721              : {
    1722       503136 :   if (number_of_loops (fun) <= 1)
    1723              :     return 0;
    1724              : 
    1725              :   /* If we ever decide to run loop peeling more than once, we will need to
    1726              :      track loops already peeled in loop structures themselves to avoid
    1727              :      re-peeling the same loop multiple times.  */
    1728       251568 :   if (flag_peel_loops)
    1729        30530 :     peeled_loops = BITMAP_ALLOC (NULL);
    1730       251568 :   unsigned int val = tree_unroll_loops_completely (flag_cunroll_grow_size, true, false);
    1731       251568 :   if (peeled_loops)
    1732              :     {
    1733        30530 :       BITMAP_FREE (peeled_loops);
    1734        30530 :       peeled_loops = NULL;
    1735              :     }
    1736              :   return val;
    1737              : }
    1738              : 
    1739              : } // anon namespace
    1740              : 
    1741              : gimple_opt_pass *
    1742       302985 : make_pass_complete_unroll (gcc::context *ctxt)
    1743              : {
    1744       302985 :   return new pass_complete_unroll (ctxt);
    1745              : }
    1746              : 
    1747              : /* Complete unrolling of inner loops.  */
    1748              : 
    1749              : namespace {
    1750              : 
    1751              : const pass_data pass_data_complete_unrolli =
    1752              : {
    1753              :   GIMPLE_PASS, /* type */
    1754              :   "cunrolli", /* name */
    1755              :   OPTGROUP_LOOP, /* optinfo_flags */
    1756              :   TV_COMPLETE_UNROLL, /* tv_id */
    1757              :   ( PROP_cfg | PROP_ssa ), /* properties_required */
    1758              :   0, /* properties_provided */
    1759              :   0, /* properties_destroyed */
    1760              :   0, /* todo_flags_start */
    1761              :   0, /* todo_flags_finish */
    1762              : };
    1763              : 
    1764              : class pass_complete_unrolli : public gimple_opt_pass
    1765              : {
    1766              : public:
    1767       302985 :   pass_complete_unrolli (gcc::context *ctxt)
    1768       605970 :     : gimple_opt_pass (pass_data_complete_unrolli, ctxt)
    1769              :   {}
    1770              : 
    1771              :   /* opt_pass methods: */
    1772      1068301 :   bool gate (function *) final override { return optimize >= 2; }
    1773              :   unsigned int execute (function *) final override;
    1774              : 
    1775              : }; // class pass_complete_unrolli
    1776              : 
    1777              : unsigned int
    1778       987657 : pass_complete_unrolli::execute (function *fun)
    1779              : {
    1780       987657 :   unsigned ret = 0;
    1781              : 
    1782       987657 :   loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
    1783      1975314 :   if (number_of_loops (fun) > 1)
    1784              :     {
    1785       232580 :       scev_initialize ();
    1786       232580 :       ret = tree_unroll_loops_completely (optimize >= 3, false, true);
    1787       232580 :       scev_finalize ();
    1788              :     }
    1789       987657 :   loop_optimizer_finalize ();
    1790              : 
    1791       987657 :   return ret;
    1792              : }
    1793              : 
    1794              : } // anon namespace
    1795              : 
    1796              : gimple_opt_pass *
    1797       302985 : make_pass_complete_unrolli (gcc::context *ctxt)
    1798              : {
    1799       302985 :   return new pass_complete_unrolli (ctxt);
    1800              : }
    1801              : 
    1802              : 
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.