LCOV - code coverage report
Current view: top level - gcc - tree-vect-loop-manip.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 81.0 % 1963 1590
Test Date: 2026-12-05 16:10:02 Functions: 83.3 % 48 40
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Vectorizer Specific Loop Manipulations
       2              :    Copyright (C) 2003-2026 Free Software Foundation, Inc.
       3              :    Contributed by Dorit Naishlos <dorit@il.ibm.com>
       4              :    and Ira Rosen <irar@il.ibm.com>
       5              : 
       6              : This file is part of GCC.
       7              : 
       8              : GCC is free software; you can redistribute it and/or modify it under
       9              : the terms of the GNU General Public License as published by the Free
      10              : Software Foundation; either version 3, or (at your option) any later
      11              : version.
      12              : 
      13              : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
      14              : WARRANTY; without even the implied warranty of MERCHANTABILITY or
      15              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      16              : for more details.
      17              : 
      18              : You should have received a copy of the GNU General Public License
      19              : along with GCC; see the file COPYING3.  If not see
      20              : <http://www.gnu.org/licenses/>.  */
      21              : 
      22              : #include "config.h"
      23              : #include "system.h"
      24              : #include "coretypes.h"
      25              : #include "backend.h"
      26              : #include "tree.h"
      27              : #include "gimple.h"
      28              : #include "cfghooks.h"
      29              : #include "tree-pass.h"
      30              : #include "ssa.h"
      31              : #include "fold-const.h"
      32              : #include "cfganal.h"
      33              : #include "gimplify.h"
      34              : #include "gimple-iterator.h"
      35              : #include "gimplify-me.h"
      36              : #include "tree-cfg.h"
      37              : #include "tree-ssa-loop-manip.h"
      38              : #include "tree-into-ssa.h"
      39              : #include "tree-ssa.h"
      40              : #include "cfgloop.h"
      41              : #include "tree-scalar-evolution.h"
      42              : #include "tree-vectorizer.h"
      43              : #include "tree-ssa-loop-ivopts.h"
      44              : #include "gimple-fold.h"
      45              : #include "tree-ssa-loop-niter.h"
      46              : #include "internal-fn.h"
      47              : #include "stor-layout.h"
      48              : #include "optabs-query.h"
      49              : #include "vec-perm-indices.h"
      50              : #include "insn-config.h"
      51              : #include "rtl.h"
      52              : #include "recog.h"
      53              : #include "langhooks.h"
      54              : #include "tree-vector-builder.h"
      55              : #include "optabs-tree.h"
      56              : 
      57              : 
      58              : /*************************************************************************
      59              :   Simple Loop Peeling Utilities
      60              : 
      61              :   Utilities to support loop peeling for vectorization purposes.
      62              :  *************************************************************************/
      63              : 
      64              : 
      65              : /* Renames the use *OP_P.  */
      66              : 
      67              : static void
      68       967142 : rename_use_op (use_operand_p op_p)
      69              : {
      70       967142 :   tree new_name;
      71              : 
      72       967142 :   if (TREE_CODE (USE_FROM_PTR (op_p)) != SSA_NAME)
      73              :     return;
      74              : 
      75       964503 :   new_name = get_current_def (USE_FROM_PTR (op_p));
      76              : 
      77              :   /* Something defined outside of the loop.  */
      78       964503 :   if (!new_name)
      79              :     return;
      80              : 
      81              :   /* An ordinary ssa name defined in the loop.  */
      82              : 
      83       831047 :   SET_USE (op_p, new_name);
      84              : }
      85              : 
      86              : 
      87              : /* Renames the variables in basic block BB.  Allow renaming  of PHI arguments
      88              :    on edges incoming from outer-block header if RENAME_FROM_OUTER_LOOP is
      89              :    true.  */
      90              : 
      91              : static void
      92       119051 : rename_variables_in_bb (basic_block bb, bool rename_from_outer_loop)
      93              : {
      94       119051 :   gimple *stmt;
      95       119051 :   use_operand_p use_p;
      96       119051 :   ssa_op_iter iter;
      97       119051 :   edge e;
      98       119051 :   edge_iterator ei;
      99       119051 :   class loop *loop = bb->loop_father;
     100       119051 :   class loop *outer_loop = NULL;
     101              : 
     102       119051 :   if (rename_from_outer_loop)
     103              :     {
     104          873 :       gcc_assert (loop);
     105          873 :       outer_loop = loop_outer (loop);
     106              :     }
     107              : 
     108       787959 :   for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
     109       549857 :        gsi_next (&gsi))
     110              :     {
     111       549857 :       stmt = gsi_stmt (gsi);
     112      1353832 :       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
     113       803975 :         rename_use_op (use_p);
     114              :     }
     115              : 
     116       242735 :   FOR_EACH_EDGE (e, ei, bb->preds)
     117              :     {
     118       123684 :       if (!flow_bb_inside_loop_p (loop, e->src))
     119              :         {
     120        37838 :           if (!rename_from_outer_loop)
     121        37560 :             continue;
     122          278 :           if (e->src != outer_loop->header)
     123              :             {
     124          159 :               if (outer_loop->inner->next)
     125              :                 {
     126              :                   /* If outer_loop has 2 inner loops, allow there to
     127              :                      be an extra basic block which decides which of the
     128              :                      two loops to use using LOOP_VECTORIZED.  */
     129          155 :                   if (!single_pred_p (e->src)
     130           22 :                       || single_pred (e->src) != outer_loop->header)
     131          133 :                     continue;
     132              :                 }
     133              :             }
     134              :         }
     135       197186 :       for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
     136       111195 :            gsi_next (&gsi))
     137       111195 :         rename_use_op (PHI_ARG_DEF_PTR_FROM_EDGE (gsi.phi (), e));
     138              :     }
     139       119051 : }
     140              : 
     141              : 
     142              : struct adjust_info
     143              : {
     144              :   tree from, to;
     145              :   basic_block bb;
     146              : };
     147              : 
     148              : /* A stack of values to be adjusted in debug stmts.  We have to
     149              :    process them LIFO, so that the closest substitution applies.  If we
     150              :    processed them FIFO, without the stack, we might substitute uses
     151              :    with a PHI DEF that would soon become non-dominant, and when we got
     152              :    to the suitable one, it wouldn't have anything to substitute any
     153              :    more.  */
     154              : static vec<adjust_info, va_heap> adjust_vec;
     155              : 
     156              : /* Adjust any debug stmts that referenced AI->from values to use the
     157              :    loop-closed AI->to, if the references are dominated by AI->bb and
     158              :    not by the definition of AI->from.  */
     159              : 
     160              : static void
     161        79784 : adjust_debug_stmts_now (adjust_info *ai)
     162              : {
     163        79784 :   basic_block bbphi = ai->bb;
     164        79784 :   tree orig_def = ai->from;
     165        79784 :   tree new_def = ai->to;
     166        79784 :   imm_use_iterator imm_iter;
     167        79784 :   gimple *stmt;
     168        79784 :   basic_block bbdef = gimple_bb (SSA_NAME_DEF_STMT (orig_def));
     169              : 
     170        79784 :   gcc_assert (dom_info_available_p (CDI_DOMINATORS));
     171              : 
     172              :   /* Adjust any debug stmts that held onto non-loop-closed
     173              :      references.  */
     174       313646 :   FOR_EACH_IMM_USE_STMT (stmt, imm_iter, orig_def)
     175              :     {
     176       233862 :       use_operand_p use_p;
     177       233862 :       basic_block bbuse;
     178              : 
     179       233862 :       if (!is_gimple_debug (stmt))
     180       175995 :         continue;
     181              : 
     182        57867 :       gcc_assert (gimple_debug_bind_p (stmt));
     183              : 
     184        57867 :       bbuse = gimple_bb (stmt);
     185              : 
     186        57867 :       if ((bbuse == bbphi
     187        57865 :            || dominated_by_p (CDI_DOMINATORS, bbuse, bbphi))
     188        59893 :           && !(bbuse == bbdef
     189         1014 :                || dominated_by_p (CDI_DOMINATORS, bbuse, bbdef)))
     190              :         {
     191            0 :           if (new_def)
     192            0 :             FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
     193            0 :               SET_USE (use_p, new_def);
     194              :           else
     195              :             {
     196            0 :               gimple_debug_bind_reset_value (stmt);
     197            0 :               update_stmt (stmt);
     198              :             }
     199              :         }
     200        79784 :     }
     201        79784 : }
     202              : 
     203              : /* Adjust debug stmts as scheduled before.  */
     204              : 
     205              : static void
     206        36368 : adjust_vec_debug_stmts (void)
     207              : {
     208        36368 :   if (!MAY_HAVE_DEBUG_BIND_STMTS)
     209              :     return;
     210              : 
     211        12987 :   gcc_assert (adjust_vec.exists ());
     212              : 
     213        92648 :   while (!adjust_vec.is_empty ())
     214              :     {
     215        79661 :       adjust_debug_stmts_now (&adjust_vec.last ());
     216        79661 :       adjust_vec.pop ();
     217              :     }
     218              : }
     219              : 
     220              : /* Adjust any debug stmts that referenced FROM values to use the
     221              :    loop-closed TO, if the references are dominated by BB and not by
     222              :    the definition of FROM.  If adjust_vec is non-NULL, adjustments
     223              :    will be postponed until adjust_vec_debug_stmts is called.  */
     224              : 
     225              : static void
     226       110208 : adjust_debug_stmts (tree from, tree to, basic_block bb)
     227              : {
     228       110208 :   adjust_info ai;
     229              : 
     230       110208 :   if (MAY_HAVE_DEBUG_BIND_STMTS
     231       110208 :       && TREE_CODE (from) == SSA_NAME
     232        99932 :       && ! SSA_NAME_IS_DEFAULT_DEF (from)
     233       208675 :       && ! virtual_operand_p (from))
     234              :     {
     235        79784 :       ai.from = from;
     236        79784 :       ai.to = to;
     237        79784 :       ai.bb = bb;
     238              : 
     239        79784 :       if (adjust_vec.exists ())
     240        79661 :         adjust_vec.safe_push (ai);
     241              :       else
     242          123 :         adjust_debug_stmts_now (&ai);
     243              :     }
     244       110208 : }
     245              : 
     246              : /* Change E's phi arg in UPDATE_PHI to NEW_DEF, and record information
     247              :    to adjust any debug stmts that referenced the old phi arg,
     248              :    presumably non-loop-closed references left over from other
     249              :    transformations.  */
     250              : 
     251              : static void
     252       234111 : adjust_phi_and_debug_stmts (gimple *update_phi, edge e, tree new_def)
     253              : {
     254       234111 :   tree orig_def = PHI_ARG_DEF_FROM_EDGE (update_phi, e);
     255              : 
     256       234111 :   gcc_assert (TREE_CODE (orig_def) != SSA_NAME
     257              :               || orig_def != new_def);
     258              : 
     259       234111 :   SET_PHI_ARG_DEF (update_phi, e->dest_idx, new_def);
     260              : 
     261       234111 :   if (MAY_HAVE_DEBUG_BIND_STMTS)
     262        86586 :     adjust_debug_stmts (orig_def, PHI_RESULT (update_phi),
     263              :                         gimple_bb (update_phi));
     264       234111 : }
     265              : 
     266              : /* Define one loop rgroup control CTRL from loop LOOP.  INIT_CTRL is the value
     267              :    that the control should have during the first iteration and NEXT_CTRL is the
     268              :    value that it should have on subsequent iterations.  */
     269              : 
     270              : static void
     271           92 : vect_set_loop_control (class loop *loop, tree ctrl, tree init_ctrl,
     272              :                        tree next_ctrl)
     273              : {
     274           92 :   gphi *phi = create_phi_node (ctrl, loop->header);
     275           92 :   add_phi_arg (phi, init_ctrl, loop_preheader_edge (loop), UNKNOWN_LOCATION);
     276           92 :   add_phi_arg (phi, next_ctrl, loop_latch_edge (loop), UNKNOWN_LOCATION);
     277           92 : }
     278              : 
     279              : /* Add SEQ to the end of LOOP's preheader block.  */
     280              : 
     281              : static void
     282           24 : add_preheader_seq (class loop *loop, gimple_seq seq)
     283              : {
     284           24 :   if (seq)
     285              :     {
     286           19 :       edge pe = loop_preheader_edge (loop);
     287           19 :       basic_block new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
     288           19 :       gcc_assert (!new_bb);
     289              :     }
     290           24 : }
     291              : 
     292              : /* Add SEQ to the beginning of LOOP's header block.  */
     293              : 
     294              : static void
     295            0 : add_header_seq (class loop *loop, gimple_seq seq)
     296              : {
     297            0 :   if (seq)
     298              :     {
     299            0 :       gimple_stmt_iterator gsi = gsi_after_labels (loop->header);
     300            0 :       gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
     301              :     }
     302            0 : }
     303              : 
     304              : /* Return true if the target can interleave elements of two vectors.
     305              :    OFFSET is 0 if the first half of the vectors should be interleaved
     306              :    or 1 if the second half should.  When returning true, store the
     307              :    associated permutation in INDICES.  */
     308              : 
     309              : static bool
     310            0 : interleave_supported_p (vec_perm_indices *indices, tree vectype,
     311              :                         unsigned int offset)
     312              : {
     313            0 :   poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (vectype);
     314            0 :   poly_uint64 base = exact_div (nelts, 2) * offset;
     315            0 :   vec_perm_builder sel (nelts, 2, 3);
     316            0 :   for (unsigned int i = 0; i < 3; ++i)
     317              :     {
     318            0 :       sel.quick_push (base + i);
     319            0 :       sel.quick_push (base + i + nelts);
     320              :     }
     321            0 :   indices->new_vector (sel, 2, nelts);
     322            0 :   return can_vec_perm_const_p (TYPE_MODE (vectype), TYPE_MODE (vectype),
     323            0 :                                *indices);
     324            0 : }
     325              : 
     326              : /* Check if its possible to use permutes to define the masks in DEST_RGM using
     327              :    the masks in SRC_RGM, given that the former has twice as many masks as the
     328              :    latter.  Return true on success.
     329              : 
     330              :    Optionally, if SEQ is non-null add new statements for the permutation to SEQ.
     331              :    Additionally, if SRC_MASKS and DST_MASKS are defined, use these instead
     332              :    of the masks from SRC_RGM and DST_RGM.  */
     333              : 
     334              : static bool
     335            0 : vect_maybe_permute_loop_masks (gimple_seq *seq,
     336              :                                rgroup_controls *dest_rgm,
     337              :                                rgroup_controls *src_rgm,
     338              :                                vec<tree> dst_controls,
     339              :                                vec<tree> src_controls)
     340              : {
     341            0 :   tree src_masktype = src_rgm->type;
     342            0 :   tree dest_masktype = dest_rgm->type;
     343            0 :   if (!src_masktype && !seq)
     344              :     return false;
     345            0 :   machine_mode src_mode = TYPE_MODE (src_masktype);
     346            0 :   insn_code icode1, icode2;
     347              : 
     348            0 :   if (dest_rgm->max_nscalars_per_iter <= src_rgm->max_nscalars_per_iter
     349            0 :       && (icode1 = optab_handler (vec_unpacku_hi_optab,
     350              :                                   src_mode)) != CODE_FOR_nothing
     351            0 :       && (icode2 = optab_handler (vec_unpacku_lo_optab,
     352              :                                   src_mode)) != CODE_FOR_nothing)
     353              :     {
     354              :       /* Unpacking the source masks gives at least as many mask bits as
     355              :          we need.  We can then VIEW_CONVERT any excess bits away.  */
     356            0 :       machine_mode dest_mode = insn_data[icode1].operand[0].mode;
     357            0 :       gcc_assert (dest_mode == insn_data[icode2].operand[0].mode);
     358            0 :       tree unpack_masktype = vect_halve_mask_nunits (src_masktype, dest_mode);
     359            0 :       if (!seq)
     360              :         return true;
     361            0 :       for (unsigned int i = 0; i < dst_controls.length (); ++i)
     362              :         {
     363            0 :           tree src = src_controls[i / 2];
     364            0 :           tree dest = dst_controls[i];
     365            0 :           tree_code code = ((i & 1) == (BYTES_BIG_ENDIAN ? 0 : 1)
     366            0 :                             ? VEC_UNPACK_HI_EXPR
     367              :                             : VEC_UNPACK_LO_EXPR);
     368            0 :           gassign *stmt;
     369            0 :           if (dest_masktype == unpack_masktype)
     370            0 :             stmt = gimple_build_assign (dest, code, src);
     371              :           else
     372              :             {
     373            0 :               tree temp = make_ssa_name (unpack_masktype);
     374            0 :               stmt = gimple_build_assign (temp, code, src);
     375            0 :               gimple_seq_add_stmt (seq, stmt);
     376            0 :               stmt = gimple_build_assign (dest, VIEW_CONVERT_EXPR,
     377              :                                           build1 (VIEW_CONVERT_EXPR,
     378              :                                                   dest_masktype, temp));
     379              :             }
     380            0 :           gimple_seq_add_stmt (seq, stmt);
     381              :         }
     382              :       return true;
     383              :     }
     384            0 :   vec_perm_indices indices[2];
     385            0 :   if (dest_masktype == src_masktype
     386            0 :       && interleave_supported_p (&indices[0], src_masktype, 0)
     387            0 :       && interleave_supported_p (&indices[1], src_masktype, 1))
     388              :     {
     389            0 :       if (!seq)
     390              :         return true;
     391              :       /* The destination requires twice as many mask bits as the source, so
     392              :          we can use interleaving permutes to double up the number of bits.  */
     393              :       tree masks[2];
     394            0 :       for (unsigned int i = 0; i < 2; ++i)
     395            0 :         masks[i] = vect_gen_perm_mask_checked (src_masktype, indices[i]);
     396            0 :       for (unsigned int i = 0; i < dst_controls.length (); ++i)
     397              :         {
     398            0 :           tree src = src_controls[i / 2];
     399            0 :           tree dest = dst_controls[i];
     400            0 :           gimple *stmt = gimple_build_assign (dest, VEC_PERM_EXPR,
     401            0 :                                               src, src, masks[i & 1]);
     402            0 :           gimple_seq_add_stmt (seq, stmt);
     403              :         }
     404              :       return true;
     405              :     }
     406              :   return false;
     407            0 : }
     408              : 
     409              : static bool
     410            0 : vect_maybe_permute_loop_masks (gimple_seq *seq,
     411              :                                rgroup_controls *dest_rgm,
     412              :                                rgroup_controls *src_rgm)
     413              : {
     414            0 :   return vect_maybe_permute_loop_masks (seq, dest_rgm, src_rgm,
     415            0 :                                         dest_rgm->controls, src_rgm->controls);
     416              : }
     417              : 
     418              : /* Populate DEST_RGM->controls, given that they should add up to STEP.
     419              : 
     420              :      STEP = MIN_EXPR <ivtmp_34, VF>;
     421              : 
     422              :      First length (MIN (X, VF/N)):
     423              :        loop_len_15 = MIN_EXPR <STEP, VF/N>;
     424              : 
     425              :      Second length:
     426              :        tmp = STEP - loop_len_15;
     427              :        loop_len_16 = MIN (tmp, VF/N);
     428              : 
     429              :      Third length:
     430              :        tmp2 = tmp - loop_len_16;
     431              :        loop_len_17 = MIN (tmp2, VF/N);
     432              : 
     433              :      Last length:
     434              :        loop_len_18 = tmp2 - loop_len_17;
     435              : */
     436              : 
     437              : static void
     438            0 : vect_adjust_loop_lens_control (tree iv_type, gimple_seq *seq,
     439              :                                rgroup_controls *dest_rgm, tree step)
     440              : {
     441            0 :   tree ctrl_type = dest_rgm->type;
     442            0 :   poly_uint64 nitems_per_ctrl
     443            0 :     = TYPE_VECTOR_SUBPARTS (ctrl_type) * dest_rgm->factor;
     444            0 :   tree length_limit = build_int_cst (iv_type, nitems_per_ctrl);
     445              : 
     446            0 :   for (unsigned int i = 0; i < dest_rgm->controls.length (); ++i)
     447              :     {
     448            0 :       tree ctrl = dest_rgm->controls[i];
     449            0 :       if (i == 0)
     450              :         {
     451              :           /* First iteration: MIN (X, VF/N) capped to the range [0, VF/N].  */
     452            0 :           gassign *assign
     453            0 :             = gimple_build_assign (ctrl, MIN_EXPR, step, length_limit);
     454            0 :           gimple_seq_add_stmt (seq, assign);
     455              :         }
     456            0 :       else if (i == dest_rgm->controls.length () - 1)
     457              :         {
     458              :           /* Last iteration: Remain capped to the range [0, VF/N].  */
     459            0 :           gassign *assign = gimple_build_assign (ctrl, MINUS_EXPR, step,
     460            0 :                                                  dest_rgm->controls[i - 1]);
     461            0 :           gimple_seq_add_stmt (seq, assign);
     462              :         }
     463              :       else
     464              :         {
     465              :           /* (MIN (remain, VF*I/N)) capped to the range [0, VF/N].  */
     466            0 :           step = gimple_build (seq, MINUS_EXPR, iv_type, step,
     467            0 :                                dest_rgm->controls[i - 1]);
     468            0 :           gassign *assign
     469            0 :             = gimple_build_assign (ctrl, MIN_EXPR, step, length_limit);
     470            0 :           gimple_seq_add_stmt (seq, assign);
     471              :         }
     472              :     }
     473            0 : }
     474              : 
     475              : /* Stores the standard position for induction variable increment in belonging to
     476              :    LOOP_EXIT (just before the exit condition of the given exit to BSI.
     477              :    INSERT_AFTER is set to true if the increment should be inserted after
     478              :    *BSI.  */
     479              : 
     480              : void
     481           99 : vect_iv_increment_position (edge loop_exit, gimple_stmt_iterator *bsi,
     482              :                             bool *insert_after)
     483              : {
     484           99 :   basic_block bb = loop_exit->src;
     485           99 :   *bsi = gsi_last_bb (bb);
     486           99 :   *insert_after = false;
     487           99 : }
     488              : 
     489              : /* Get the virtual operand live on E.  The precondition on this is valid
     490              :    immediate dominators and an actual virtual definition dominating E.  */
     491              : /* ???  Costly band-aid.  For the use in question we can populate a
     492              :    live-on-exit/end-of-BB virtual operand when copying stmts.  */
     493              : 
     494              : static tree
     495           39 : get_live_virtual_operand_on_edge (edge e)
     496              : {
     497           39 :   basic_block bb = e->src;
     498           67 :   do
     499              :     {
     500          329 :       for (auto gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
     501              :         {
     502          256 :           gimple *stmt = gsi_stmt (gsi);
     503          485 :           if (gimple_vdef (stmt))
     504           39 :             return gimple_vdef (stmt);
     505          419 :           if (gimple_vuse (stmt))
     506              :             return gimple_vuse (stmt);
     507              :         }
     508           20 :       if (gphi *vphi = get_virtual_phi (bb))
     509            6 :         return gimple_phi_result (vphi);
     510           14 :       bb = get_immediate_dominator (CDI_DOMINATORS, bb);
     511           14 :     }
     512              :   while (1);
     513              : }
     514              : 
     515              : /* Helper for vect_set_loop_condition_partial_vectors.  Generate definitions
     516              :    for all the rgroup controls in RGC and return a control that is nonzero
     517              :    when the loop needs to iterate.  Add any new preheader statements to
     518              :    PREHEADER_SEQ.  Use LOOP_COND_GSI to insert code before the exit gcond.
     519              : 
     520              :    RGC belongs to loop LOOP.  The loop originally iterated NITERS
     521              :    times and has been vectorized according to LOOP_VINFO.
     522              : 
     523              :    If NITERS_SKIP is nonnull, the first iteration of the vectorized loop
     524              :    starts with NITERS_SKIP dummy iterations of the scalar loop before
     525              :    the real work starts.  The mask elements for these dummy iterations
     526              :    must be 0, to ensure that the extra iterations do not have an effect.
     527              : 
     528              :    It is known that:
     529              : 
     530              :      NITERS * RGC->max_nscalars_per_iter * RGC->factor
     531              : 
     532              :    does not overflow.  However, MIGHT_WRAP_P says whether an induction
     533              :    variable that starts at 0 and has step:
     534              : 
     535              :      VF * RGC->max_nscalars_per_iter * RGC->factor
     536              : 
     537              :    might overflow before hitting a value above:
     538              : 
     539              :      (NITERS + NITERS_SKIP) * RGC->max_nscalars_per_iter * RGC->factor
     540              : 
     541              :    This means that we cannot guarantee that such an induction variable
     542              :    would ever hit a value that produces a set of all-false masks or zero
     543              :    lengths for RGC.
     544              : 
     545              :    Note: the cost of the code generated by this function is modeled
     546              :    by vect_estimate_min_profitable_iters, so changes here may need
     547              :    corresponding changes there.  */
     548              : 
     549              : static tree
     550            0 : vect_set_loop_controls_directly (class loop *loop, loop_vec_info loop_vinfo,
     551              :                                  gimple_seq *preheader_seq,
     552              :                                  gimple_seq *header_seq,
     553              :                                  gimple_stmt_iterator loop_cond_gsi,
     554              :                                  rgroup_controls *rgc, tree niters,
     555              :                                  tree niters_skip, bool might_wrap_p,
     556              :                                  tree *iv_step, tree *compare_step)
     557              : {
     558            0 :   tree compare_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
     559            0 :   tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
     560            0 :   bool use_masks_p = LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
     561              : 
     562            0 :   tree ctrl_type = rgc->type;
     563            0 :   unsigned int nitems_per_iter = rgc->max_nscalars_per_iter * rgc->factor;
     564            0 :   poly_uint64 nitems_per_ctrl = TYPE_VECTOR_SUBPARTS (ctrl_type) * rgc->factor;
     565            0 :   tree length_limit = NULL_TREE;
     566              :   /* For length, we need length_limit to ensure length in range.  */
     567            0 :   if (!use_masks_p)
     568            0 :     length_limit = build_int_cst (compare_type, nitems_per_ctrl);
     569              : 
     570              :   /* Calculate the maximum number of item values that the rgroup
     571              :      handles in total, the number that it handles for each iteration
     572              :      of the vector loop, and the number that it should skip during the
     573              :      first iteration of the vector loop.  */
     574            0 :   tree nitems_total = niters;
     575            0 :   tree nitems_vf
     576            0 :     = build_int_cst (iv_type, LOOP_VINFO_VECT_FACTOR (loop_vinfo));
     577            0 :   tree nitems_step
     578            0 :     = LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo)
     579            0 :         ? gimple_convert (preheader_seq, iv_type,
     580              :                           LOOP_VINFO_IV_INCREMENT (loop_vinfo))
     581            0 :         : gimple_convert (&loop_cond_gsi, true, GSI_SAME_STMT, UNKNOWN_LOCATION,
     582              :                           iv_type, LOOP_VINFO_IV_INCREMENT (loop_vinfo));
     583              : 
     584            0 :   tree nitems_skip = niters_skip;
     585            0 :   if (nitems_per_iter != 1)
     586              :     {
     587              :       /* We checked before setting LOOP_VINFO_USING_PARTIAL_VECTORS_P that
     588              :          these multiplications don't overflow.  */
     589            0 :       tree compare_factor = build_int_cst (compare_type, nitems_per_iter);
     590            0 :       tree iv_factor = build_int_cst (iv_type, nitems_per_iter);
     591            0 :       nitems_total = gimple_build (preheader_seq, MULT_EXPR, compare_type,
     592              :                                    nitems_total, compare_factor);
     593            0 :       nitems_vf = gimple_build (preheader_seq, MULT_EXPR, iv_type,
     594              :                                   nitems_vf, iv_factor);
     595            0 :       nitems_step = LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo)
     596            0 :                       ? gimple_build (preheader_seq, MULT_EXPR, iv_type,
     597              :                                       nitems_step, iv_factor)
     598            0 :                       : gimple_build (&loop_cond_gsi, true, GSI_SAME_STMT,
     599              :                                       UNKNOWN_LOCATION, MULT_EXPR, iv_type,
     600              :                                       nitems_step, iv_factor);
     601            0 :       if (nitems_skip)
     602            0 :         nitems_skip = gimple_build (preheader_seq, MULT_EXPR, compare_type,
     603              :                                     nitems_skip, compare_factor);
     604              :     }
     605              : 
     606              :   /* Create an induction variable that counts the number of items
     607              :      processed.  */
     608            0 :   tree index_before_incr, index_after_incr;
     609            0 :   gimple_stmt_iterator incr_gsi;
     610            0 :   bool insert_after;
     611            0 :   standard_iv_increment_position (loop, &incr_gsi, &insert_after);
     612              : 
     613            0 :   if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
     614              :     {
     615              :       /* Create an IV that counts down from niters_total and whose step
     616              :          is the (variable) amount processed in the current iteration:
     617              :            ...
     618              :            _10 = (unsigned long) count_12(D);
     619              :            ...
     620              :            # ivtmp_9 = PHI <ivtmp_35(6), _10(5)>
     621              :            _36 = (MIN_EXPR | SELECT_VL) <ivtmp_9, POLY_INT_CST [4, 4]>;
     622              :            ...
     623              :            vect__4.8_28 = .LEN_LOAD (_17, 32B, _36, 0);
     624              :            ...
     625              :            ivtmp_35 = ivtmp_9 - POLY_INT_CST [4, 4];
     626              :            ...
     627              :            if (ivtmp_9 > POLY_INT_CST [4, 4])
     628              :              goto <bb 4>; [83.33%]
     629              :            else
     630              :              goto <bb 5>; [16.67%]
     631              :       */
     632            0 :       nitems_total = gimple_convert (preheader_seq, iv_type, nitems_total);
     633            0 :       tree step = rgc->controls.length () == 1 ? rgc->controls[0]
     634            0 :                                                : make_ssa_name (iv_type);
     635              :       /* Create decrement IV.  */
     636            0 :       if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
     637              :         {
     638            0 :           create_iv (nitems_total, MINUS_EXPR, step, NULL_TREE, loop, &incr_gsi,
     639              :                      insert_after, &index_before_incr, &index_after_incr);
     640            0 :           tree vectype = build_zero_cst (rgc->type);
     641            0 :           tree len = gimple_build (header_seq, IFN_SELECT_VL, iv_type,
     642              :                                    index_before_incr, nitems_vf,
     643              :                                    vectype);
     644            0 :           gimple_seq_add_stmt (header_seq, gimple_build_assign (step, len));
     645            0 :           len = gimple_convert (header_seq, sizetype, len);
     646              : 
     647              :           /* Remove the previous initialization of IV_INCREMENT to VARYING.  */
     648            0 :           gimple *varying_def
     649            0 :             = SSA_NAME_DEF_STMT (LOOP_VINFO_IV_INCREMENT (loop_vinfo));
     650            0 :           auto def_gsi = gsi_for_stmt (varying_def);
     651            0 :           gsi_remove (&def_gsi, true);
     652              : 
     653              :           /* Set the LOOP_VINFO_IV_INCREMENT to be len.  */
     654            0 :           gassign* assign_iv_increment
     655            0 :             = gimple_build_assign (LOOP_VINFO_IV_INCREMENT (loop_vinfo), len);
     656            0 :           gimple_seq_add_stmt (header_seq, assign_iv_increment);
     657              :         }
     658              :       else
     659              :         {
     660            0 :           create_iv (nitems_total, MINUS_EXPR, nitems_step, NULL_TREE, loop,
     661              :                      &incr_gsi, insert_after, &index_before_incr,
     662              :                      &index_after_incr);
     663            0 :           gimple_seq_add_stmt (header_seq,
     664            0 :                                gimple_build_assign (step, MIN_EXPR,
     665              :                                                     index_before_incr,
     666              :                                                     nitems_step));
     667              :         }
     668            0 :       *iv_step = step;
     669            0 :       *compare_step = nitems_vf;
     670            0 :       return LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) ? index_after_incr
     671            0 :                                                        : index_before_incr;
     672              :     }
     673              : 
     674              :   /* Create increment IV.  */
     675            0 :   create_iv (build_int_cst (iv_type, 0), PLUS_EXPR, nitems_step, NULL_TREE,
     676              :              loop, &incr_gsi, insert_after, &index_before_incr,
     677              :              &index_after_incr,
     678            0 :              LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo));
     679              : 
     680            0 :   tree zero_index = build_int_cst (compare_type, 0);
     681            0 :   tree test_index, test_limit, first_limit;
     682            0 :   if (might_wrap_p)
     683              :     {
     684              :       /* In principle the loop should stop iterating once the incremented
     685              :          IV reaches a value greater than or equal to:
     686              : 
     687              :            NITEMS_TOTAL +[infinite-prec] NITEMS_SKIP
     688              : 
     689              :          However, there's no guarantee that this addition doesn't overflow
     690              :          the comparison type, or that the IV hits a value above it before
     691              :          wrapping around.  We therefore adjust the limit down by one
     692              :          IV step:
     693              : 
     694              :            (NITEMS_TOTAL +[infinite-prec] NITEMS_SKIP)
     695              :            -[infinite-prec] NITEMS_STEP
     696              : 
     697              :          and compare the IV against this limit _before_ incrementing it.
     698              :          Since the comparison type is unsigned, we actually want the
     699              :          subtraction to saturate at zero:
     700              : 
     701              :            (NITEMS_TOTAL +[infinite-prec] NITEMS_SKIP)
     702              :            -[sat] NITEMS_STEP
     703              : 
     704              :          And since NITEMS_SKIP < NITEMS_STEP, we can reassociate this as:
     705              : 
     706              :            NITEMS_TOTAL -[sat] (NITEMS_STEP - NITEMS_SKIP)
     707              : 
     708              :          where the rightmost subtraction can be done directly in
     709              :          COMPARE_TYPE.  */
     710            0 :       test_index = index_before_incr;
     711            0 :       tree adjust = gimple_convert (preheader_seq, compare_type,
     712              :                                     nitems_vf);
     713            0 :       if (nitems_skip)
     714            0 :         adjust = gimple_build (preheader_seq, MINUS_EXPR, compare_type,
     715              :                                adjust, nitems_skip);
     716            0 :       test_limit = gimple_build (preheader_seq, MAX_EXPR, compare_type,
     717              :                                  nitems_total, adjust);
     718            0 :       test_limit = gimple_build (preheader_seq, MINUS_EXPR, compare_type,
     719              :                                  test_limit, adjust);
     720              : 
     721              :       /* Get a safe limit for the first iteration.  */
     722            0 :       if (nitems_skip)
     723              :         {
     724              :           /* The first vector iteration can handle at most NITEMS_STEP
     725              :              items.  NITEMS_STEP <= CONST_LIMIT, and adding
     726              :              NITEMS_SKIP to that cannot overflow.  */
     727            0 :           tree const_limit = build_int_cst (compare_type,
     728            0 :                                             LOOP_VINFO_VECT_FACTOR (loop_vinfo)
     729            0 :                                             * nitems_per_iter);
     730            0 :           first_limit = gimple_build (preheader_seq, MIN_EXPR, compare_type,
     731              :                                       nitems_total, const_limit);
     732            0 :           first_limit = gimple_build (preheader_seq, PLUS_EXPR, compare_type,
     733              :                                       first_limit, nitems_skip);
     734              :         }
     735              :       else
     736              :         /* For the first iteration it doesn't matter whether the IV hits
     737              :            a value above NITEMS_TOTAL.  That only matters for the latch
     738              :            condition.  */
     739              :         first_limit = nitems_total;
     740              :     }
     741              :   else
     742              :     {
     743              :       /* Test the incremented IV, which will always hit a value above
     744              :          the bound before wrapping.  */
     745            0 :       test_index = index_after_incr;
     746            0 :       test_limit = nitems_total;
     747            0 :       if (nitems_skip)
     748            0 :         test_limit = gimple_build (preheader_seq, PLUS_EXPR, compare_type,
     749              :                                    test_limit, nitems_skip);
     750              : 
     751              :       first_limit = test_limit;
     752              :     }
     753              : 
     754              :   /* Convert the IV value to the comparison type (either a no-op or
     755              :      a demotion).  */
     756            0 :   gimple_seq test_seq = NULL;
     757            0 :   test_index = gimple_convert (&test_seq, compare_type, test_index);
     758            0 :   gsi_insert_seq_after (&incr_gsi, test_seq, GSI_NEW_STMT);
     759              : 
     760              :   /* Provide a definition of each control in the group.  */
     761            0 :   tree next_ctrl = NULL_TREE;
     762            0 :   tree ctrl;
     763            0 :   unsigned int i;
     764            0 :   FOR_EACH_VEC_ELT_REVERSE (rgc->controls, i, ctrl)
     765              :     {
     766              :       /* Previous controls will cover BIAS items.  This control covers the
     767              :          next batch.  */
     768            0 :       poly_uint64 bias = nitems_per_ctrl * i;
     769            0 :       tree bias_tree = build_int_cst (compare_type, bias);
     770              : 
     771              :       /* See whether the first iteration of the vector loop is known
     772              :          to have a full control.  */
     773            0 :       poly_uint64 const_limit;
     774            0 :       bool first_iteration_full
     775            0 :         = (poly_int_tree_p (first_limit, &const_limit)
     776            0 :            && known_ge (const_limit, (i + 1) * nitems_per_ctrl));
     777              : 
     778              :       /* Rather than have a new IV that starts at BIAS and goes up to
     779              :          TEST_LIMIT, prefer to use the same 0-based IV for each control
     780              :          and adjust the bound down by BIAS.  */
     781            0 :       tree this_test_limit = test_limit;
     782            0 :       if (i != 0)
     783              :         {
     784            0 :           this_test_limit = gimple_build (preheader_seq, MAX_EXPR,
     785              :                                           compare_type, this_test_limit,
     786              :                                           bias_tree);
     787            0 :           this_test_limit = gimple_build (preheader_seq, MINUS_EXPR,
     788              :                                           compare_type, this_test_limit,
     789              :                                           bias_tree);
     790              :         }
     791              : 
     792              :       /* Create the initial control.  First include all items that
     793              :          are within the loop limit.  */
     794            0 :       tree init_ctrl = NULL_TREE;
     795            0 :       if (!first_iteration_full)
     796              :         {
     797            0 :           tree start, end;
     798            0 :           if (first_limit == test_limit)
     799              :             {
     800              :               /* Use a natural test between zero (the initial IV value)
     801              :                  and the loop limit.  The "else" block would be valid too,
     802              :                  but this choice can avoid the need to load BIAS_TREE into
     803              :                  a register.  */
     804              :               start = zero_index;
     805              :               end = this_test_limit;
     806              :             }
     807              :           else
     808              :             {
     809              :               /* FIRST_LIMIT is the maximum number of items handled by the
     810              :                  first iteration of the vector loop.  Test the portion
     811              :                  associated with this control.  */
     812            0 :               start = bias_tree;
     813            0 :               end = first_limit;
     814              :             }
     815              : 
     816            0 :           if (use_masks_p)
     817            0 :             init_ctrl = vect_gen_while (preheader_seq, ctrl_type,
     818              :                                         start, end, "max_mask");
     819              :           else
     820              :             {
     821            0 :               init_ctrl = make_temp_ssa_name (compare_type, NULL, "max_len");
     822            0 :               gimple_seq seq = vect_gen_len (init_ctrl, start,
     823              :                                              end, length_limit);
     824            0 :               gimple_seq_add_seq (preheader_seq, seq);
     825              :             }
     826              :         }
     827              : 
     828              :       /* Now AND out the bits that are within the number of skipped
     829              :          items.  */
     830            0 :       poly_uint64 const_skip;
     831            0 :       if (nitems_skip
     832            0 :           && !(poly_int_tree_p (nitems_skip, &const_skip)
     833            0 :                && known_le (const_skip, bias)))
     834              :         {
     835            0 :           gcc_assert (use_masks_p);
     836            0 :           tree unskipped_mask = vect_gen_while_not (preheader_seq, ctrl_type,
     837              :                                                     bias_tree, nitems_skip);
     838            0 :           if (init_ctrl)
     839            0 :             init_ctrl = gimple_build (preheader_seq, BIT_AND_EXPR, ctrl_type,
     840              :                                       init_ctrl, unskipped_mask);
     841              :           else
     842              :             init_ctrl = unskipped_mask;
     843              :         }
     844              : 
     845            0 :       if (!init_ctrl)
     846              :         {
     847              :           /* First iteration is full.  */
     848            0 :           if (use_masks_p)
     849            0 :             init_ctrl = build_minus_one_cst (ctrl_type);
     850              :           else
     851              :             init_ctrl = length_limit;
     852              :         }
     853              : 
     854              :       /* Get the control value for the next iteration of the loop.  */
     855            0 :       if (use_masks_p)
     856              :         {
     857            0 :           gimple_seq stmts = NULL;
     858            0 :           next_ctrl = vect_gen_while (&stmts, ctrl_type, test_index,
     859              :                                       this_test_limit, "next_mask");
     860            0 :           gsi_insert_seq_after (&incr_gsi, stmts, GSI_SAME_STMT);
     861              :         }
     862              :       else
     863              :         {
     864            0 :           next_ctrl = make_temp_ssa_name (compare_type, NULL, "next_len");
     865            0 :           gimple_seq seq = vect_gen_len (next_ctrl, test_index, this_test_limit,
     866              :                                          length_limit);
     867            0 :           gsi_insert_seq_after (&incr_gsi, seq, GSI_SAME_STMT);
     868              :         }
     869              : 
     870            0 :       vect_set_loop_control (loop, ctrl, init_ctrl, next_ctrl);
     871              :     }
     872              : 
     873            0 :   int partial_load_bias = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
     874            0 :   if (partial_load_bias != 0)
     875              :     {
     876            0 :       tree adjusted_len = rgc->bias_adjusted_ctrl;
     877            0 :       gassign *minus = gimple_build_assign (adjusted_len, PLUS_EXPR,
     878            0 :                                             rgc->controls[0],
     879              :                                             build_int_cst
     880            0 :                                             (TREE_TYPE (rgc->controls[0]),
     881            0 :                                              partial_load_bias));
     882            0 :       gimple_seq_add_stmt (header_seq, minus);
     883              :     }
     884              : 
     885              :   return next_ctrl;
     886              : }
     887              : 
     888              : /* Set up the iteration condition and rgroup controls for LOOP, given
     889              :    that LOOP_VINFO_USING_PARTIAL_VECTORS_P is true for the vectorized
     890              :    loop.  LOOP_VINFO describes the vectorization of LOOP.  NITERS is
     891              :    the number of iterations of the original scalar loop that should be
     892              :    handled by the vector loop.  NITERS_MAYBE_ZERO is as for
     893              :    vect_set_loop_condition.  Return the branch-back condition for the caller
     894              :    to insert.  */
     895              : 
     896              : static gcond *
     897            0 : vect_set_loop_condition_partial_vectors (class loop *loop, edge exit_edge,
     898              :                                          loop_vec_info loop_vinfo, tree niters,
     899              :                                          bool niters_maybe_zero,
     900              :                                          gimple_stmt_iterator loop_cond_gsi)
     901              : {
     902            0 :   gimple_seq preheader_seq = NULL;
     903            0 :   gimple_seq header_seq = NULL;
     904              : 
     905            0 :   bool use_masks_p = LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
     906            0 :   tree compare_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
     907            0 :   unsigned int compare_precision = TYPE_PRECISION (compare_type);
     908              : 
     909              :   /* Type of the initial value of NITERS.  */
     910            0 :   tree ni_actual_type = TREE_TYPE (niters);
     911            0 :   unsigned int ni_actual_precision = TYPE_PRECISION (ni_actual_type);
     912            0 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
     913            0 :   if (niters_skip)
     914            0 :     niters_skip = gimple_convert (&preheader_seq, compare_type, niters_skip);
     915              : 
     916              :   /* Convert NITERS to the same size as the compare.  */
     917            0 :   if (compare_precision > ni_actual_precision
     918            0 :       && niters_maybe_zero)
     919              :     {
     920              :       /* We know that there is always at least one iteration, so if the
     921              :          count is zero then it must have wrapped.  Cope with this by
     922              :          subtracting 1 before the conversion and adding 1 to the result.  */
     923            0 :       gcc_assert (TYPE_UNSIGNED (ni_actual_type));
     924            0 :       niters = gimple_build (&preheader_seq, PLUS_EXPR, ni_actual_type,
     925              :                              niters, build_minus_one_cst (ni_actual_type));
     926            0 :       niters = gimple_convert (&preheader_seq, compare_type, niters);
     927            0 :       niters = gimple_build (&preheader_seq, PLUS_EXPR, compare_type,
     928              :                              niters, build_one_cst (compare_type));
     929              :     }
     930              :   else
     931            0 :     niters = gimple_convert (&preheader_seq, compare_type, niters);
     932              : 
     933              :   /* Iterate over all the rgroups and fill in their controls.  We could use
     934              :      the first control from any rgroup for the loop condition; here we
     935              :      arbitrarily pick the last.  */
     936            0 :   tree test_ctrl = NULL_TREE;
     937            0 :   tree iv_step = NULL_TREE;
     938            0 :   tree compare_step = NULL_TREE;
     939            0 :   rgroup_controls *rgc;
     940            0 :   rgroup_controls *iv_rgc = nullptr;
     941            0 :   unsigned int i;
     942            0 :   auto_vec<rgroup_controls> *controls = use_masks_p
     943            0 :                                           ? &LOOP_VINFO_MASKS (loop_vinfo).rgc_vec
     944              :                                           : &LOOP_VINFO_LENS (loop_vinfo);
     945            0 :   FOR_EACH_VEC_ELT (*controls, i, rgc)
     946            0 :     if (!rgc->controls.is_empty ())
     947              :       {
     948              :         /* First try using permutes.  This adds a single vector
     949              :            instruction to the loop for each mask, but needs no extra
     950              :            loop invariants or IVs.  */
     951            0 :         unsigned int nmasks = i + 1;
     952            0 :         if (use_masks_p && (nmasks & 1) == 0)
     953              :           {
     954            0 :             rgroup_controls *half_rgc = &(*controls)[nmasks / 2 - 1];
     955            0 :             if (!half_rgc->controls.is_empty ()
     956            0 :                 && vect_maybe_permute_loop_masks (&header_seq, rgc, half_rgc))
     957            0 :               continue;
     958              :           }
     959              : 
     960            0 :         if (!LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo)
     961            0 :             || !iv_rgc
     962            0 :             || (iv_rgc->max_nscalars_per_iter * iv_rgc->factor
     963            0 :                 != rgc->max_nscalars_per_iter * rgc->factor))
     964              :           {
     965              :             /* See whether zero-based IV would ever generate all-false masks
     966              :                or zero length before wrapping around.  */
     967            0 :             bool might_wrap_p = vect_rgroup_iv_might_wrap_p (loop_vinfo, rgc);
     968              : 
     969              :             /* Set up all controls for this group.  */
     970            0 :             test_ctrl
     971            0 :               = vect_set_loop_controls_directly (loop, loop_vinfo,
     972              :                                                  &preheader_seq, &header_seq,
     973              :                                                  loop_cond_gsi, rgc, niters,
     974              :                                                  niters_skip, might_wrap_p,
     975              :                                                  &iv_step, &compare_step);
     976              : 
     977            0 :             iv_rgc = rgc;
     978              :           }
     979              : 
     980            0 :         if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo)
     981            0 :             && rgc->controls.length () > 1)
     982              :           {
     983              :             /* vect_set_loop_controls_directly creates an IV whose step
     984              :                is equal to the expected sum of RGC->controls.  Use that
     985              :                information to populate RGC->controls.  */
     986            0 :             tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
     987            0 :             gcc_assert (iv_step);
     988            0 :             vect_adjust_loop_lens_control (iv_type, &header_seq, rgc, iv_step);
     989              :           }
     990              :       }
     991              : 
     992              :   /* Emit all accumulated statements.  */
     993            0 :   add_preheader_seq (loop, preheader_seq);
     994            0 :   add_header_seq (loop, header_seq);
     995              : 
     996              :   /* Get a boolean result that tells us whether to iterate.  */
     997            0 :   gcond *cond_stmt;
     998            0 :   if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo)
     999            0 :       && !LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    1000              :     {
    1001            0 :       gcc_assert (compare_step);
    1002            0 :       tree_code code = (exit_edge->flags & EDGE_TRUE_VALUE) ? LE_EXPR : GT_EXPR;
    1003            0 :       cond_stmt = gimple_build_cond (code, test_ctrl, compare_step, NULL_TREE,
    1004              :                                      NULL_TREE);
    1005            0 :     }
    1006              :   else
    1007              :     {
    1008            0 :       tree_code code = (exit_edge->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR;
    1009            0 :       tree zero_ctrl = build_zero_cst (TREE_TYPE (test_ctrl));
    1010            0 :       cond_stmt
    1011            0 :         = gimple_build_cond (code, test_ctrl, zero_ctrl, NULL_TREE, NULL_TREE);
    1012              :     }
    1013              :   /* The loop iterates (NITERS - 1) / VF + 1 times.
    1014              :      Subtract one from this to get the latch count.  */
    1015            0 :   tree step = build_int_cst (compare_type,
    1016            0 :                              LOOP_VINFO_VECT_FACTOR (loop_vinfo));
    1017            0 :   tree niters_minus_one = fold_build2 (PLUS_EXPR, compare_type, niters,
    1018              :                                        build_minus_one_cst (compare_type));
    1019            0 :   loop->nb_iterations = fold_build2 (TRUNC_DIV_EXPR, compare_type,
    1020              :                                      niters_minus_one, step);
    1021              : 
    1022            0 :   return cond_stmt;
    1023              : }
    1024              : 
    1025              : /* Set up the iteration condition and rgroup controls for LOOP in AVX512
    1026              :    style, given that LOOP_VINFO_USING_PARTIAL_VECTORS_P is true for the
    1027              :    vectorized loop.  LOOP_VINFO describes the vectorization of LOOP.  NITERS is
    1028              :    the number of iterations of the original scalar loop that should be
    1029              :    handled by the vector loop.  NITERS_MAYBE_ZERO is as for
    1030              :    vect_set_loop_condition.  Return the branch-back condition for the caller
    1031              :    to insert.  */
    1032              : 
    1033              : static gcond *
    1034           24 : vect_set_loop_condition_partial_vectors_avx512 (class loop *loop,
    1035              :                                          edge exit_edge,
    1036              :                                          loop_vec_info loop_vinfo, tree niters,
    1037              :                                          bool niters_maybe_zero)
    1038              : {
    1039           24 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
    1040           24 :   tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
    1041           24 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    1042           24 :   tree orig_niters = niters;
    1043           24 :   gimple_seq preheader_seq = NULL;
    1044              : 
    1045              :   /* Create an IV that counts down from niters and whose step
    1046              :      is the number of iterations processed in the current iteration.
    1047              :      Produce the controls with compares like the following.
    1048              : 
    1049              :        # iv_2 = PHI <niters, iv_3>
    1050              :        rem_4 = MIN <iv_2, VF>;
    1051              :        remv_6 = { rem_4, rem_4, rem_4, ... }
    1052              :        mask_5 = { 0, 0, 1, 1, 2, 2, ... } < remv6;
    1053              :        iv_3 = iv_2 - VF;
    1054              :        if (iv_2 > VF)
    1055              :          continue;
    1056              : 
    1057              :      Where the constant is built with elements at most VF - 1 and
    1058              :      repetitions according to max_nscalars_per_iter which is guaranteed
    1059              :      to be the same within a group.  */
    1060              : 
    1061              :   /* Convert NITERS to the determined IV type.  */
    1062           24 :   if (TYPE_PRECISION (iv_type) > TYPE_PRECISION (TREE_TYPE (niters))
    1063           24 :       && niters_maybe_zero)
    1064              :     {
    1065              :       /* We know that there is always at least one iteration, so if the
    1066              :          count is zero then it must have wrapped.  Cope with this by
    1067              :          subtracting 1 before the conversion and adding 1 to the result.  */
    1068            0 :       gcc_assert (TYPE_UNSIGNED (TREE_TYPE (niters)));
    1069            0 :       niters = gimple_build (&preheader_seq, PLUS_EXPR, TREE_TYPE (niters),
    1070            0 :                              niters, build_minus_one_cst (TREE_TYPE (niters)));
    1071            0 :       niters = gimple_convert (&preheader_seq, iv_type, niters);
    1072            0 :       niters = gimple_build (&preheader_seq, PLUS_EXPR, iv_type,
    1073              :                              niters, build_one_cst (iv_type));
    1074              :     }
    1075              :   else
    1076           24 :     niters = gimple_convert (&preheader_seq, iv_type, niters);
    1077              : 
    1078              :   /* Bias the initial value of the IV in case we need to skip iterations
    1079              :      at the beginning.  */
    1080           24 :   tree niters_adj = niters;
    1081           24 :   if (niters_skip)
    1082              :     {
    1083            2 :       tree skip = gimple_convert (&preheader_seq, iv_type, niters_skip);
    1084            2 :       niters_adj = gimple_build (&preheader_seq, PLUS_EXPR,
    1085              :                                  iv_type, niters, skip);
    1086              :     }
    1087              : 
    1088           24 :   gimple_stmt_iterator incr_gsi;
    1089           24 :   tree index_before_incr, index_after_incr;
    1090           24 :   bool insert_after;
    1091           24 :   standard_iv_increment_position (loop, &incr_gsi, &insert_after);
    1092              : 
    1093              :   /* The iteration step is the vectorization factor.  */
    1094           24 :   tree iv_step = gimple_convert (&preheader_seq, iv_type,
    1095              :                                  LOOP_VINFO_IV_INCREMENT (loop_vinfo));
    1096              : 
    1097              :   /* Create the decrement IV.  */
    1098           24 :   create_iv (niters_adj, MINUS_EXPR, iv_step, NULL_TREE, loop,
    1099              :              &incr_gsi, insert_after, &index_before_incr,
    1100              :              &index_after_incr);
    1101              : 
    1102              :   /* Iterate over all the rgroups and fill in their controls.  */
    1103          105 :   for (auto &rgc : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
    1104              :     {
    1105           33 :       if (rgc.controls.is_empty ())
    1106            7 :         continue;
    1107              : 
    1108           26 :       tree ctrl_type = rgc.type;
    1109           26 :       poly_uint64 nitems_per_ctrl = TYPE_VECTOR_SUBPARTS (ctrl_type);
    1110              : 
    1111           26 :       tree vectype = rgc.compare_type;
    1112              : 
    1113              :       /* index_after_incr is the IV specifying the remaining iterations in
    1114              :          the next iteration.  */
    1115           26 :       tree rem = index_after_incr;
    1116              :       /* When the data type for the compare to produce the mask is
    1117              :          smaller than the IV type we need to saturate.  Saturate to
    1118              :          the smallest possible value (IV_TYPE) so we only have to
    1119              :          saturate once (CSE will catch redundant ones we add).  */
    1120           26 :       if (TYPE_PRECISION (TREE_TYPE (vectype)) < TYPE_PRECISION (iv_type))
    1121            9 :         rem = gimple_build (&incr_gsi, false, GSI_CONTINUE_LINKING,
    1122              :                             UNKNOWN_LOCATION,
    1123            9 :                             MIN_EXPR, TREE_TYPE (rem), rem, iv_step);
    1124           26 :       rem = gimple_convert (&incr_gsi, false, GSI_CONTINUE_LINKING,
    1125           26 :                             UNKNOWN_LOCATION, TREE_TYPE (vectype), rem);
    1126              : 
    1127              :       /* Build a data vector composed of the remaining iterations.  */
    1128           26 :       rem = gimple_build_vector_from_val (&incr_gsi, false, GSI_CONTINUE_LINKING,
    1129              :                                           UNKNOWN_LOCATION, vectype, rem);
    1130              : 
    1131              :       /* Provide a definition of each vector in the control group.  */
    1132           26 :       tree next_ctrl = NULL_TREE;
    1133           26 :       tree first_rem = NULL_TREE;
    1134           26 :       tree ctrl;
    1135           26 :       unsigned int i;
    1136          177 :       FOR_EACH_VEC_ELT_REVERSE (rgc.controls, i, ctrl)
    1137              :         {
    1138              :           /* Previous controls will cover BIAS items.  This control covers the
    1139              :              next batch.  */
    1140           92 :           poly_uint64 bias = nitems_per_ctrl * i;
    1141              : 
    1142              :           /* Build the constant to compare the remaining iters against,
    1143              :              this is sth like { 0, 0, 1, 1, 2, 2, 3, 3, ... } appropriately
    1144              :              split into pieces.  */
    1145           92 :           unsigned n = TYPE_VECTOR_SUBPARTS (ctrl_type).to_constant ();
    1146           92 :           tree_vector_builder builder (vectype, n, 1);
    1147         1418 :           for (unsigned i = 0; i < n; ++i)
    1148              :             {
    1149         1234 :               unsigned HOST_WIDE_INT val
    1150         1234 :                 = (i + bias.to_constant ()) / rgc.max_nscalars_per_iter;
    1151         1234 :               gcc_assert (val < vf.to_constant ());
    1152         1234 :               builder.quick_push (build_int_cst (TREE_TYPE (vectype), val));
    1153              :             }
    1154           92 :           tree cmp_series = builder.build ();
    1155              : 
    1156              :           /* Create the initial control.  First include all items that
    1157              :              are within the loop limit.  */
    1158           92 :           tree init_ctrl = NULL_TREE;
    1159           92 :           poly_uint64 const_limit;
    1160              :           /* See whether the first iteration of the vector loop is known
    1161              :              to have a full control.  */
    1162           92 :           if (poly_int_tree_p (niters, &const_limit)
    1163           92 :               && known_ge (const_limit, (i + 1) * nitems_per_ctrl))
    1164            3 :             init_ctrl = build_minus_one_cst (ctrl_type);
    1165              :           else
    1166              :             {
    1167              :               /* The remaining work items initially are niters.  Saturate,
    1168              :                  splat and compare.  */
    1169           89 :               if (!first_rem)
    1170              :                 {
    1171           23 :                   first_rem = niters;
    1172           23 :                   if (TYPE_PRECISION (TREE_TYPE (vectype))
    1173           23 :                       < TYPE_PRECISION (iv_type))
    1174            9 :                     first_rem = gimple_build (&preheader_seq,
    1175            9 :                                               MIN_EXPR, TREE_TYPE (first_rem),
    1176              :                                               first_rem, iv_step);
    1177           23 :                   first_rem = gimple_convert (&preheader_seq, TREE_TYPE (vectype),
    1178              :                                               first_rem);
    1179           23 :                   first_rem = gimple_build_vector_from_val (&preheader_seq,
    1180              :                                                             vectype, first_rem);
    1181              :                 }
    1182           89 :               init_ctrl = gimple_build (&preheader_seq, LT_EXPR, ctrl_type,
    1183              :                                         cmp_series, first_rem);
    1184              :             }
    1185              : 
    1186              :           /* Now AND out the bits that are within the number of skipped
    1187              :              items.  */
    1188           92 :           poly_uint64 const_skip;
    1189           92 :           if (niters_skip
    1190           92 :               && !(poly_int_tree_p (niters_skip, &const_skip)
    1191            2 :                    && known_le (const_skip, bias)))
    1192              :             {
    1193              :               /* For integer mode masks it's cheaper to shift out the bits
    1194              :                  since that avoids loading a constant.  */
    1195            2 :               gcc_assert (GET_MODE_CLASS (TYPE_MODE (ctrl_type)) == MODE_INT);
    1196            2 :               init_ctrl = gimple_build (&preheader_seq, VIEW_CONVERT_EXPR,
    1197            2 :                                         lang_hooks.types.type_for_mode
    1198            2 :                                           (TYPE_MODE (ctrl_type), 1),
    1199              :                                         init_ctrl);
    1200              :               /* ???  But when the shift amount isn't constant this requires
    1201              :                  a round-trip to GRPs.  We could apply the bias to either
    1202              :                  side of the compare instead.  */
    1203            4 :               tree shift = gimple_build (&preheader_seq, MINUS_EXPR,
    1204            2 :                                          TREE_TYPE (niters_skip), niters_skip,
    1205            2 :                                          build_int_cst (TREE_TYPE (niters_skip),
    1206            2 :                                                         bias));
    1207            4 :               shift = gimple_build (&preheader_seq, MULT_EXPR,
    1208            2 :                                     TREE_TYPE (niters_skip), shift,
    1209            2 :                                     build_int_cst (TREE_TYPE (niters_skip),
    1210            2 :                                                    rgc.max_nscalars_per_iter));
    1211            2 :               init_ctrl = gimple_build (&preheader_seq, LSHIFT_EXPR,
    1212            2 :                                         TREE_TYPE (init_ctrl),
    1213              :                                         init_ctrl, shift);
    1214            2 :               init_ctrl = gimple_build (&preheader_seq, VIEW_CONVERT_EXPR,
    1215              :                                         ctrl_type, init_ctrl);
    1216              :             }
    1217              : 
    1218              :           /* Get the control value for the next iteration of the loop.  */
    1219           92 :           next_ctrl = gimple_build (&incr_gsi, false, GSI_CONTINUE_LINKING,
    1220              :                                     UNKNOWN_LOCATION,
    1221              :                                     LT_EXPR, ctrl_type, cmp_series, rem);
    1222              : 
    1223           92 :           vect_set_loop_control (loop, ctrl, init_ctrl, next_ctrl);
    1224           92 :         }
    1225              :     }
    1226              : 
    1227              :   /* Emit all accumulated statements.  */
    1228           24 :   add_preheader_seq (loop, preheader_seq);
    1229              : 
    1230              :   /* Adjust the exit test using the decrementing IV.  */
    1231           24 :   tree_code code = (exit_edge->flags & EDGE_TRUE_VALUE) ? LE_EXPR : GT_EXPR;
    1232              :   /* When we peel for alignment with niter_skip != 0 this can
    1233              :      cause niter + niter_skip to wrap and since we are comparing the
    1234              :      value before the decrement here we get a false early exit.
    1235              :      We can't compare the value after decrement either because that
    1236              :      decrement could wrap as well as we're not doing a saturating
    1237              :      decrement.  To avoid this situation we force a larger
    1238              :      iv_type.  */
    1239           24 :   gcond *cond_stmt = gimple_build_cond (code, index_before_incr, iv_step,
    1240              :                                         NULL_TREE, NULL_TREE);
    1241              :   /* The loop iterates (NITERS - 1 + NITERS_SKIP) / VF + 1 times.
    1242              :      Subtract one from this to get the latch count.  */
    1243           24 :   tree niters_minus_one
    1244           24 :     = fold_build2 (PLUS_EXPR, TREE_TYPE (orig_niters), orig_niters,
    1245              :                    build_minus_one_cst (TREE_TYPE (orig_niters)));
    1246           24 :   tree niters_adj2 = fold_convert (iv_type, niters_minus_one);
    1247           24 :   if (niters_skip)
    1248            2 :     niters_adj2 = fold_build2 (PLUS_EXPR, iv_type, niters_minus_one,
    1249              :                                fold_convert (iv_type, niters_skip));
    1250           24 :   loop->nb_iterations = fold_build2 (TRUNC_DIV_EXPR, iv_type,
    1251              :                                      niters_adj2, iv_step);
    1252              : 
    1253           24 :   return cond_stmt;
    1254              : }
    1255              : 
    1256              : 
    1257              : /* Like vect_set_loop_condition, but handle the case in which the vector
    1258              :    loop handles exactly VF scalars per iteration.  Return the branch-back
    1259              :    condition for the caller to insert.  */
    1260              : 
    1261              : static gcond *
    1262        66901 : vect_set_loop_condition_normal (loop_vec_info loop_vinfo, edge exit_edge,
    1263              :                                 class loop *loop, tree niters, tree step,
    1264              :                                 tree final_iv, bool niters_maybe_zero)
    1265              : {
    1266        66901 :   tree indx_before_incr, indx_after_incr;
    1267        66901 :   gcond *cond_stmt;
    1268        66901 :   edge pe = loop_preheader_edge (loop);
    1269        66901 :   gimple_stmt_iterator incr_gsi;
    1270        66901 :   bool insert_after;
    1271        66901 :   enum tree_code code;
    1272        66901 :   tree niters_type = TREE_TYPE (niters);
    1273              : 
    1274        66901 :   tree init, limit;
    1275        66901 :   if (!niters_maybe_zero && integer_onep (step))
    1276              :     {
    1277              :       /* In this case we can use a simple 0-based IV:
    1278              : 
    1279              :          A:
    1280              :            x = 0;
    1281              :            do
    1282              :              {
    1283              :                ...
    1284              :                x += 1;
    1285              :              }
    1286              :            while (x < NITERS);  */
    1287        66901 :       code = (exit_edge->flags & EDGE_TRUE_VALUE) ? GE_EXPR : LT_EXPR;
    1288        66901 :       init = build_zero_cst (niters_type);
    1289        66901 :       limit = niters;
    1290              :     }
    1291              :   else
    1292              :     {
    1293              :       /* The following works for all values of NITERS except 0:
    1294              : 
    1295              :          B:
    1296              :            x = 0;
    1297              :            do
    1298              :              {
    1299              :                ...
    1300              :                x += STEP;
    1301              :              }
    1302              :            while (x <= NITERS - STEP);
    1303              : 
    1304              :          so that the loop continues to iterate if x + STEP - 1 < NITERS
    1305              :          but stops if x + STEP - 1 >= NITERS.
    1306              : 
    1307              :          However, if NITERS is zero, x never hits a value above NITERS - STEP
    1308              :          before wrapping around.  There are two obvious ways of dealing with
    1309              :          this:
    1310              : 
    1311              :          - start at STEP - 1 and compare x before incrementing it
    1312              :          - start at -1 and compare x after incrementing it
    1313              : 
    1314              :          The latter is simpler and is what we use.  The loop in this case
    1315              :          looks like:
    1316              : 
    1317              :          C:
    1318              :            x = -1;
    1319              :            do
    1320              :              {
    1321              :                ...
    1322              :                x += STEP;
    1323              :              }
    1324              :            while (x < NITERS - STEP);
    1325              : 
    1326              :          In both cases the loop limit is NITERS - STEP.  */
    1327            0 :       gimple_seq seq = NULL;
    1328            0 :       limit = force_gimple_operand (niters, &seq, true, NULL_TREE);
    1329            0 :       limit = gimple_build (&seq, MINUS_EXPR, TREE_TYPE (limit), limit, step);
    1330            0 :       if (seq)
    1331              :         {
    1332            0 :           basic_block new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
    1333            0 :           gcc_assert (!new_bb);
    1334              :         }
    1335            0 :       if (niters_maybe_zero)
    1336              :         {
    1337              :           /* Case C.  */
    1338            0 :           code = (exit_edge->flags & EDGE_TRUE_VALUE) ? GE_EXPR : LT_EXPR;
    1339            0 :           init = build_all_ones_cst (niters_type);
    1340              :         }
    1341              :       else
    1342              :         {
    1343              :           /* Case B.  */
    1344            0 :           code = (exit_edge->flags & EDGE_TRUE_VALUE) ? GT_EXPR : LE_EXPR;
    1345            0 :           init = build_zero_cst (niters_type);
    1346              :         }
    1347              :     }
    1348              : 
    1349        66901 :   standard_iv_increment_position (loop, &incr_gsi, &insert_after);
    1350       133802 :   create_iv (init, PLUS_EXPR, step, NULL_TREE, loop,
    1351              :              &incr_gsi, insert_after,
    1352              :              &indx_before_incr, &indx_after_incr,
    1353        66433 :              !loop_vinfo || LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo));
    1354              : 
    1355        66901 :   cond_stmt = gimple_build_cond (code, indx_after_incr, limit, NULL_TREE,
    1356              :                                  NULL_TREE);
    1357              : 
    1358              :   /* Record the number of latch iterations.  */
    1359        66901 :   if (limit == niters)
    1360              :     /* Case A: the loop iterates NITERS times.  Subtract one to get the
    1361              :        latch count.  */
    1362        66901 :     loop->nb_iterations = fold_build2 (MINUS_EXPR, niters_type, niters,
    1363              :                                        build_int_cst (niters_type, 1));
    1364              :   else
    1365              :     /* Case B or C: the loop iterates (NITERS - STEP) / STEP + 1 times.
    1366              :        Subtract one from this to get the latch count.  */
    1367            0 :     loop->nb_iterations = fold_build2 (TRUNC_DIV_EXPR, niters_type,
    1368              :                                        limit, step);
    1369              : 
    1370        66901 :   if (final_iv)
    1371              :     {
    1372            0 :       gassign *assign;
    1373            0 :       tree phi_dest
    1374            0 :         = integer_zerop (init) ? final_iv : copy_ssa_name (indx_after_incr);
    1375              :       /* Make sure to maintain LC SSA form here and elide the subtraction
    1376              :          if the value is zero.  */
    1377            0 :       gphi *phi = create_phi_node (phi_dest, exit_edge->dest);
    1378            0 :       add_phi_arg (phi, indx_after_incr, exit_edge, UNKNOWN_LOCATION);
    1379            0 :       if (!integer_zerop (init))
    1380              :         {
    1381            0 :           assign = gimple_build_assign (final_iv, MINUS_EXPR, phi_dest, init);
    1382            0 :           gimple_stmt_iterator gsi
    1383            0 :             = gsi_after_labels (LOOP_VINFO_MAIN_EXIT (loop_vinfo)->dest);
    1384            0 :           gsi_insert_before (&gsi, assign, GSI_SAME_STMT);
    1385              :         }
    1386              :     }
    1387              : 
    1388        66901 :   return cond_stmt;
    1389              : }
    1390              : 
    1391              : /* If we're using fully-masked loops, make LOOP iterate:
    1392              : 
    1393              :       N == (NITERS - 1) / STEP + 1
    1394              : 
    1395              :    times.  When NITERS is zero, this is equivalent to making the loop
    1396              :    execute (1 << M) / STEP times, where M is the precision of NITERS.
    1397              :    NITERS_MAYBE_ZERO is true if this last case might occur.
    1398              : 
    1399              :    If we're not using fully-masked loops, make LOOP iterate:
    1400              : 
    1401              :       N == (NITERS - STEP) / STEP + 1
    1402              : 
    1403              :    times, where NITERS is known to be outside the range [1, STEP - 1].
    1404              :    This is equivalent to making the loop execute NITERS / STEP times
    1405              :    when NITERS is nonzero and (1 << M) / STEP times otherwise.
    1406              :    NITERS_MAYBE_ZERO again indicates whether this last case might occur.
    1407              : 
    1408              :    If FINAL_IV is nonnull, it is an SSA name that should be set to
    1409              :    N * STEP on exit from the loop.
    1410              : 
    1411              :    Assumption: the exit-condition of LOOP is the last stmt in the loop.  */
    1412              : 
    1413              : void
    1414        66925 : vect_set_loop_condition (class loop *loop, edge loop_e, loop_vec_info loop_vinfo,
    1415              :                          tree niters, tree step, tree final_iv,
    1416              :                          bool niters_maybe_zero)
    1417              : {
    1418        66925 :   gcond *cond_stmt;
    1419        66925 :   gcond *orig_cond = get_loop_exit_condition (loop_e);
    1420        66925 :   gimple_stmt_iterator loop_cond_gsi = gsi_for_stmt (orig_cond);
    1421              : 
    1422              :   /* Check to see whether we will be replacing final_IV below.  Because of the
    1423              :      various replacement strategies (assign vs PHI) just remove it now and
    1424              :      leave the SSA name to be rebuild below.  */
    1425        66925 :   if (final_iv && TREE_CODE (final_iv) == SSA_NAME)
    1426              :     {
    1427            0 :       gimple *def = SSA_NAME_DEF_STMT (final_iv);
    1428            0 :       if (gimple_call_internal_p (def, IFN_VARYING))
    1429              :         {
    1430            0 :           gimple_stmt_iterator gsi = gsi_for_stmt (def);
    1431            0 :           gsi_remove (&gsi, true);
    1432              :         }
    1433              :     }
    1434              : 
    1435        66925 :   if (loop_vinfo && LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    1436              :     {
    1437           24 :       if (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) == vect_partial_vectors_avx512)
    1438           24 :         cond_stmt = vect_set_loop_condition_partial_vectors_avx512 (loop, loop_e,
    1439              :                                                                     loop_vinfo,
    1440              :                                                                     niters,
    1441              :                                                                     niters_maybe_zero);
    1442              :       else
    1443            0 :         cond_stmt = vect_set_loop_condition_partial_vectors (loop, loop_e,
    1444              :                                                              loop_vinfo,
    1445              :                                                              niters,
    1446              :                                                              niters_maybe_zero,
    1447              :                                                              loop_cond_gsi);
    1448              :     }
    1449              :   else
    1450        66901 :     cond_stmt = vect_set_loop_condition_normal (loop_vinfo, loop_e, loop,
    1451              :                                                 niters,
    1452              :                                                 step, final_iv,
    1453              :                                                 niters_maybe_zero);
    1454              : 
    1455              :   /* A peeled early-break loop is entered only when it has at least one
    1456              :      vector iteration to execute.  Test the IV after that iteration rather
    1457              :      than before it, regardless of the style of loop control.  */
    1458        66925 :   if (loop_vinfo && LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
    1459              :     {
    1460              :       /* Move the IV exit test from the header to the latch, so that it
    1461              :          follows the early exits in the loop body.  */
    1462           64 :       basic_block latch = loop->latch;
    1463           64 :       edge latch_e = single_succ_edge (latch);
    1464           64 :       int exit_flags = loop_e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
    1465              : 
    1466           64 :       latch_e->flags &= ~(EDGE_FALLTHRU | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
    1467           64 :       latch_e->flags |= (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE) ^ exit_flags;
    1468           64 :       edge latch_exit_edge = make_edge (latch, loop_e->dest, exit_flags);
    1469           64 :       latch_exit_edge->probability = loop_e->probability;
    1470           64 :       latch_exit_edge->count () = loop_e->count ();
    1471              : 
    1472              :       /* The header exit uses values from before the iteration.  The latch
    1473              :          exit follows the body, so use the backedge values of header PHIs.  The
    1474              :          earlier code in vect_do_peeling corrected the scalar IVs, but the line
    1475              :          below still copies the old reduction values to the new exit.  Correct
    1476              :          these by populating the redirect map with the backedge values before
    1477              :          copying the PHIs.  */
    1478           64 :       for (gphi_iterator gsi = gsi_start_phis (loop->header);
    1479          465 :            !gsi_end_p (gsi); gsi_next (&gsi))
    1480              :         {
    1481          401 :           gphi *phi = gsi.phi ();
    1482          401 :           auto locus = gimple_phi_arg_location_from_edge (phi, latch_e);
    1483          401 :           redirect_edge_var_map_add (latch_exit_edge, gimple_phi_result (phi),
    1484              :                                      PHI_ARG_DEF_FROM_EDGE (phi, latch_e),
    1485              :                                      locus);
    1486              :         }
    1487              : 
    1488           64 :       copy_phi_arg_into_existing_phi (loop_e, latch_exit_edge, true);
    1489              : 
    1490           64 :       if (gphi *vphi = get_virtual_phi (latch_exit_edge->dest))
    1491           29 :         SET_PHI_ARG_DEF_ON_EDGE (vphi, latch_exit_edge,
    1492              :                                  get_live_virtual_operand_on_edge
    1493              :                                    (latch_exit_edge));
    1494           64 :       gimple_stmt_iterator latch_gsi = gsi_last_bb (latch);
    1495           64 :       gsi_insert_after (&latch_gsi, cond_stmt, GSI_NEW_STMT);
    1496           64 :       LOOP_VINFO_MAIN_EXIT (loop_vinfo) = latch_exit_edge;
    1497              : 
    1498           64 :       if (loop_e->flags & EDGE_TRUE_VALUE)
    1499            9 :         gimple_cond_make_false (orig_cond);
    1500              :       else
    1501           55 :         gimple_cond_make_true (orig_cond);
    1502           64 :       update_stmt (orig_cond);
    1503              :     }
    1504              :   else
    1505              :     {
    1506        66861 :       gsi_insert_before (&loop_cond_gsi, cond_stmt, GSI_SAME_STMT);
    1507        66861 :       stmt_vec_info orig_cond_info;
    1508        66861 :       if (loop_vinfo
    1509        66861 :           && (orig_cond_info = loop_vinfo->lookup_stmt (orig_cond)))
    1510        66393 :         loop_vinfo->remove_stmt (orig_cond_info);
    1511              :       else
    1512          468 :         gsi_remove (&loop_cond_gsi, true);
    1513              :     }
    1514              : 
    1515        66925 :   if (loop_vinfo && LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    1516           24 :       && final_iv)
    1517              :     {
    1518            0 :       gassign *assign = gimple_build_assign (final_iv, niters);
    1519            0 :       gsi_insert_on_edge_immediate (LOOP_VINFO_MAIN_EXIT (loop_vinfo), assign);
    1520              :     }
    1521              : 
    1522        66925 :   if (dump_enabled_p ())
    1523        11969 :     dump_printf_loc (MSG_NOTE, vect_location, "New loop exit condition: %G",
    1524              :                      (gimple *) cond_stmt);
    1525        66925 : }
    1526              : 
    1527              : /* Given LOOP this function generates a new copy of it and puts it
    1528              :    on E which is either the entry or exit of LOOP.  If SCALAR_LOOP is
    1529              :    non-NULL, assume LOOP and SCALAR_LOOP are equivalent and copy the
    1530              :    basic blocks from SCALAR_LOOP instead of LOOP, but to either the
    1531              :    entry or exit of LOOP.  If FLOW_LOOPS then connect LOOP to SCALAR_LOOP as a
    1532              :    continuation.  This is correct for cases where one loop continues from the
    1533              :    other like in the vectorizer, but not true for uses in e.g. loop distribution
    1534              :    where the contents of the loop body are split but the iteration space of both
    1535              :    copies remains the same.
    1536              : 
    1537              :    If UPDATED_DOMS is not NULL it is update with the list of basic blocks whose
    1538              :    dominators were updated during the peeling.  When doing early break vectorization
    1539              :    then LOOP_VINFO needs to be provided and is used to keep track of any newly created
    1540              :    memory references that need to be updated should we decide to vectorize.  */
    1541              : 
    1542              : class loop *
    1543        37693 : slpeel_tree_duplicate_loop_to_edge_cfg (class loop *loop, edge loop_exit,
    1544              :                                         class loop *scalar_loop,
    1545              :                                         edge scalar_exit, edge e, edge *new_e,
    1546              :                                         bool flow_loops,
    1547              :                                         vec<basic_block> *updated_doms,
    1548              :                                         bool uncounted_p, bool create_main_e,
    1549              :                                         bool redirect_exits)
    1550              : {
    1551        37693 :   class loop *new_loop;
    1552        37693 :   basic_block *new_bbs, *bbs, *pbbs;
    1553        37693 :   bool at_exit;
    1554        37693 :   bool was_imm_dom;
    1555        37693 :   basic_block exit_dest;
    1556        37693 :   edge exit, new_exit;
    1557        37693 :   bool duplicate_outer_loop = false;
    1558              : 
    1559        37693 :   exit = loop_exit;
    1560        37693 :   at_exit = (e == exit);
    1561        37693 :   if (!at_exit && e != loop_preheader_edge (loop))
    1562              :     return NULL;
    1563              : 
    1564        37693 :   if (scalar_loop == NULL)
    1565              :     {
    1566        36041 :       scalar_loop = loop;
    1567        36041 :       scalar_exit = loop_exit;
    1568              :     }
    1569         1652 :   else if (scalar_loop == loop)
    1570            0 :     scalar_exit = loop_exit;
    1571              :   else
    1572              :     {
    1573              :       /* Loop has been version, match exits up using the aux index.  */
    1574         4956 :       for (edge exit : get_loop_exit_edges (scalar_loop))
    1575         1652 :         if (exit->aux == loop_exit->aux)
    1576              :           {
    1577         1652 :             scalar_exit = exit;
    1578         1652 :             break;
    1579         1652 :           }
    1580              : 
    1581         1652 :       gcc_assert (scalar_exit);
    1582              :     }
    1583              : 
    1584        37693 :   bbs = XNEWVEC (basic_block, scalar_loop->num_nodes + 1);
    1585        37693 :   pbbs = bbs + 1;
    1586        37693 :   get_loop_body_with_size (scalar_loop, pbbs, scalar_loop->num_nodes);
    1587              :   /* Allow duplication of outer loops.  */
    1588        37693 :   if (scalar_loop->inner)
    1589          133 :     duplicate_outer_loop = true;
    1590              : 
    1591              :   /* Generate new loop structure.  */
    1592        37693 :   new_loop = duplicate_loop (scalar_loop, loop_outer (scalar_loop));
    1593        37693 :   duplicate_subloops (scalar_loop, new_loop);
    1594              : 
    1595        37693 :   exit_dest = exit->dest;
    1596        37693 :   was_imm_dom = (get_immediate_dominator (CDI_DOMINATORS,
    1597        37693 :                                           exit_dest) == exit->src ?
    1598              :                  true : false);
    1599              : 
    1600              :   /* Also copy the pre-header, this avoids jumping through hoops to
    1601              :      duplicate the loop entry PHI arguments.  Create an empty
    1602              :      pre-header unconditionally for this.  */
    1603        37693 :   basic_block preheader = split_edge (loop_preheader_edge (scalar_loop));
    1604        37693 :   edge entry_e = single_pred_edge (preheader);
    1605        37693 :   bbs[0] = preheader;
    1606        37693 :   new_bbs = XNEWVEC (basic_block, scalar_loop->num_nodes + 1);
    1607              : 
    1608        37693 :   copy_bbs (bbs, scalar_loop->num_nodes + 1, new_bbs,
    1609              :             &scalar_exit, 1, &new_exit, NULL,
    1610              :             at_exit ? loop->latch : e->src, true);
    1611        37693 :   exit = loop_exit;
    1612        37693 :   basic_block new_preheader = new_bbs[0];
    1613              : 
    1614        37693 :   gcc_assert (new_exit);
    1615              : 
    1616              :   /* Record the new loop exit information.  new_loop doesn't have SCEV data and
    1617              :      so we must initialize the exit information.  */
    1618        37693 :   if (new_e)
    1619        36368 :     *new_e = new_exit;
    1620              : 
    1621              :   /* Before installing PHI arguments make sure that the edges
    1622              :      into them match that of the scalar loop we analyzed.  This
    1623              :      makes sure the SLP tree matches up between the main vectorized
    1624              :      loop and the epilogue vectorized copies.  */
    1625        37693 :   if (single_succ_edge (preheader)->dest_idx
    1626        37693 :       != single_succ_edge (new_bbs[0])->dest_idx)
    1627              :     {
    1628        33345 :       basic_block swap_bb = new_bbs[1];
    1629        33345 :       gcc_assert (EDGE_COUNT (swap_bb->preds) == 2);
    1630        33345 :       std::swap (EDGE_PRED (swap_bb, 0), EDGE_PRED (swap_bb, 1));
    1631        33345 :       EDGE_PRED (swap_bb, 0)->dest_idx = 0;
    1632        33345 :       EDGE_PRED (swap_bb, 1)->dest_idx = 1;
    1633              :     }
    1634        37693 :   if (duplicate_outer_loop)
    1635              :     {
    1636          133 :       class loop *new_inner_loop = get_loop_copy (scalar_loop->inner);
    1637          133 :       if (loop_preheader_edge (scalar_loop)->dest_idx
    1638          133 :           != loop_preheader_edge (new_inner_loop)->dest_idx)
    1639              :         {
    1640          109 :           basic_block swap_bb = new_inner_loop->header;
    1641          109 :           gcc_assert (EDGE_COUNT (swap_bb->preds) == 2);
    1642          109 :           std::swap (EDGE_PRED (swap_bb, 0), EDGE_PRED (swap_bb, 1));
    1643          109 :           EDGE_PRED (swap_bb, 0)->dest_idx = 0;
    1644          109 :           EDGE_PRED (swap_bb, 1)->dest_idx = 1;
    1645              :         }
    1646              :     }
    1647              : 
    1648        37693 :   add_phi_args_after_copy (new_bbs, scalar_loop->num_nodes + 1, NULL);
    1649              : 
    1650              :   /* Skip new preheader since it's deleted if copy loop is added at entry.  */
    1651       156744 :   for (unsigned i = (at_exit ? 0 : 1); i < scalar_loop->num_nodes + 1; i++)
    1652       119051 :     rename_variables_in_bb (new_bbs[i], duplicate_outer_loop);
    1653              : 
    1654              :   /* Rename the exit uses.  */
    1655       152031 :   for (edge exit : get_loop_exit_edges (new_loop))
    1656        38952 :     for (auto gsi = gsi_start_phis (exit->dest);
    1657        90924 :          !gsi_end_p (gsi); gsi_next (&gsi))
    1658              :       {
    1659        51972 :         tree orig_def = PHI_ARG_DEF_FROM_EDGE (gsi.phi (), exit);
    1660        51972 :         rename_use_op (PHI_ARG_DEF_PTR_FROM_EDGE (gsi.phi (), exit));
    1661        51972 :         if (MAY_HAVE_DEBUG_BIND_STMTS)
    1662        23622 :           adjust_debug_stmts (orig_def, PHI_RESULT (gsi.phi ()), exit->dest);
    1663        37693 :       }
    1664              : 
    1665        37693 :   auto loop_exits = get_loop_exit_edges (loop);
    1666        37693 :   bool has_multiple_exits_p = loop_exits.length () > 1;
    1667              : 
    1668              :   /* If REDIRECT_EXITS is false we leave the alternative exits untouched and
    1669              :      treat the duplication as if the loop only had the main exit.  */
    1670        37693 :   bool redirect_multiple_exits_p = redirect_exits && has_multiple_exits_p;
    1671        37693 :   auto_vec<basic_block> doms;
    1672              : 
    1673        37693 :   if (at_exit) /* Add the loop copy at exit.  */
    1674              :     {
    1675        35900 :       if (scalar_loop != loop && new_exit->dest != exit_dest)
    1676              :         {
    1677         1648 :           new_exit = redirect_edge_and_branch (new_exit, exit_dest);
    1678         1648 :           flush_pending_stmts (new_exit);
    1679              :         }
    1680              : 
    1681        35900 :       bool need_virtual_phi = get_virtual_phi (loop->header);
    1682              : 
    1683              :       /* For the main loop exit preserve the LC PHI nodes.  For vectorization
    1684              :          we need them to continue or finalize reductions.  Since we do not
    1685              :          copy the loop exit blocks we have to materialize PHIs at the
    1686              :          new destination before redirecting edges.  */
    1687        35900 :       for (auto gsi_from = gsi_start_phis (loop_exit->dest);
    1688        84724 :            !gsi_end_p (gsi_from); gsi_next (&gsi_from))
    1689              :         {
    1690        48824 :           tree res = gimple_phi_result (*gsi_from);
    1691        48824 :           create_phi_node (copy_ssa_name (res), new_preheader);
    1692              :         }
    1693        35900 :       edge e = redirect_edge_and_branch (loop_exit, new_preheader);
    1694        35900 :       gcc_assert (e == loop_exit);
    1695        35900 :       flush_pending_stmts (loop_exit);
    1696        35900 :       set_immediate_dominator (CDI_DOMINATORS, new_preheader, loop_exit->src);
    1697              : 
    1698              :       /* If we ended up choosing an exit leading to a path not using memory
    1699              :          we can end up without a virtual LC PHI.  Create it when it is
    1700              :          needed because of the epilog loop continuation.  */
    1701        35900 :       if (need_virtual_phi && !get_virtual_phi (loop_exit->dest))
    1702              :         {
    1703            8 :           tree header_def = gimple_phi_result (get_virtual_phi (loop->header));
    1704            8 :           gphi *vphi = create_phi_node (copy_ssa_name (header_def),
    1705              :                                         new_preheader);
    1706            8 :           add_phi_arg (vphi, get_live_virtual_operand_on_edge (loop_exit),
    1707              :                        loop_exit, UNKNOWN_LOCATION);
    1708              :         }
    1709              : 
    1710        35900 :       basic_block main_loop_exit_block = new_preheader;
    1711        35900 :       basic_block alt_loop_exit_block = new_preheader;
    1712              :       /* When we redirect the other exits create the CFG
    1713              :          below to funnel everything through the merge block:
    1714              :                    | loop_exit               | alt1   | altN
    1715              :                    v                         v   ...  v
    1716              :             main_loop_exit_block:       alt_loop_exit_block:
    1717              :                    |                      /
    1718              :                    v                     v
    1719              :             new_preheader:
    1720              :          where in the new preheader we need merge PHIs for
    1721              :          the continuation values into the epilogue header.
    1722              :          Do not bother with exit PHIs for the early exits but
    1723              :          their live virtual operand.  We'll fix up things below.  */
    1724        35900 :       if (redirect_multiple_exits_p || uncounted_p)
    1725              :         {
    1726          698 :           edge loop_e = single_succ_edge (new_preheader);
    1727          698 :           new_preheader = split_edge (loop_e);
    1728              : 
    1729          698 :         if (redirect_exits)
    1730              :           {
    1731          692 :             gphi *vphi = NULL;
    1732          692 :             alt_loop_exit_block = new_preheader;
    1733         3580 :             for (auto exit : loop_exits)
    1734         1504 :               if (exit != loop_exit)
    1735              :                 {
    1736          812 :                   tree vphi_def = NULL_TREE;
    1737          812 :                   if (gphi *evphi = get_virtual_phi (exit->dest))
    1738          495 :                     vphi_def = gimple_phi_arg_def_from_edge (evphi, exit);
    1739          812 :                   edge res
    1740          812 :                     = redirect_edge_and_branch (exit, alt_loop_exit_block);
    1741          812 :                   gcc_assert (res == exit);
    1742          812 :                   redirect_edge_var_map_clear (exit);
    1743              : 
    1744          812 :                   if (alt_loop_exit_block == new_preheader)
    1745          655 :                     alt_loop_exit_block = split_edge (exit);
    1746          812 :                   if (!need_virtual_phi)
    1747          325 :                     continue;
    1748              : 
    1749              :                   /* When the edge has no virtual LC PHI get at the live
    1750              :                      virtual operand by other means.  */
    1751          487 :                   if (!vphi_def)
    1752            2 :                     vphi_def = get_live_virtual_operand_on_edge (exit);
    1753              : 
    1754          487 :                   if (!vphi)
    1755          441 :                     vphi = create_phi_node (copy_ssa_name (vphi_def),
    1756              :                                           alt_loop_exit_block);
    1757              :                   else
    1758              :                     /* Edge redirection might re-allocate the PHI node
    1759              :                        so we have to rediscover it.  */
    1760           46 :                     vphi = get_virtual_phi (alt_loop_exit_block);
    1761          487 :                   add_phi_arg (vphi, vphi_def, exit, UNKNOWN_LOCATION);
    1762              :                 }
    1763              :           }
    1764              : 
    1765          698 :           set_immediate_dominator (CDI_DOMINATORS, new_preheader,
    1766              :                                    loop->header);
    1767              : 
    1768              :           /* Fix up the profile counts of the new exit blocks.
    1769              :              main_loop_exit_block was created by duplicating the
    1770              :              preheader, so needs its count scaling according to the main
    1771              :              exit edge's probability.  The remaining count from the
    1772              :              preheader goes to the alt_loop_exit_block, since all
    1773              :              alternative exits have been redirected there.  */
    1774          698 :           main_loop_exit_block->count = loop_exit->count ();
    1775          698 :           alt_loop_exit_block->count
    1776          698 :             = preheader->count - main_loop_exit_block->count;
    1777              :         }
    1778              : 
    1779              :       /* Adjust the epilog loop PHI entry values to continue iteration.
    1780              :          This adds remaining necessary LC PHI nodes to the main exit
    1781              :          and creates merge PHIs when we have multiple exits with
    1782              :          their appropriate continuation.  */
    1783        35900 :       if (flow_loops)
    1784              :         {
    1785        35900 :           edge loop_entry = single_succ_edge (new_preheader);
    1786        35900 :           bool peeled_iters = (uncounted_p
    1787        35900 :                                || single_pred (loop->latch) != loop_exit->src);
    1788              : 
    1789              :           /* Record the new SSA names in the cache so that we can skip
    1790              :              materializing them again when we fill in the rest of the LC SSA
    1791              :              variables.  */
    1792        35900 :           hash_map <tree, tree> new_phi_args;
    1793        35900 :           for (auto psi = gsi_start_phis (main_loop_exit_block);
    1794        84732 :                !gsi_end_p (psi); gsi_next (&psi))
    1795              :             {
    1796        48832 :               gphi *phi = *psi;
    1797        48832 :               tree new_arg = gimple_phi_arg_def_from_edge (phi, loop_exit);
    1798        48832 :               if (TREE_CODE (new_arg) != SSA_NAME)
    1799          402 :                 continue;
    1800              : 
    1801              :               /* If the loop doesn't have a virtual def then only possibly keep
    1802              :                  the epilog LC PHI for it and avoid creating new defs.  */
    1803        48523 :               if (virtual_operand_p (new_arg) && !need_virtual_phi)
    1804              :                 {
    1805           93 :                   auto gsi = gsi_for_stmt (phi);
    1806           93 :                   remove_phi_node (&gsi, true);
    1807           93 :                   continue;
    1808           93 :                 }
    1809              : 
    1810              :               /* If we decided not to remove the PHI node we should also not
    1811              :                  rematerialize it later on.  */
    1812        48430 :               new_phi_args.put (new_arg, gimple_phi_result (phi));
    1813              :             }
    1814              : 
    1815              :           /* Create the merge PHI nodes in new_preheader and populate the
    1816              :              arguments for the exits.  */
    1817        35900 :           if (redirect_multiple_exits_p)
    1818              :             {
    1819          655 :               for (auto gsi_from = gsi_start_phis (loop->header),
    1820          655 :                    gsi_to = gsi_start_phis (new_loop->header);
    1821         2365 :                    !gsi_end_p (gsi_from) && !gsi_end_p (gsi_to);
    1822         1710 :                    gsi_next (&gsi_from), gsi_next (&gsi_to))
    1823              :                 {
    1824         1710 :                   gimple *from_phi = gsi_stmt (gsi_from);
    1825         1710 :                   gimple *to_phi = gsi_stmt (gsi_to);
    1826              : 
    1827              :                   /* When the vector loop is peeled then we need to use the
    1828              :                      value at start of the loop, otherwise the main loop exit
    1829              :                      should use the final iter value.  */
    1830         1710 :                   tree new_arg;
    1831         1710 :                   if (peeled_iters)
    1832          118 :                     new_arg = gimple_phi_result (from_phi);
    1833              :                   else
    1834         1592 :                     new_arg = PHI_ARG_DEF_FROM_EDGE (from_phi,
    1835              :                                                      loop_latch_edge (loop));
    1836              : 
    1837              :                   /* Check if we've already created a new phi node during edge
    1838              :                      redirection and re-use it if so.  Otherwise create a
    1839              :                      LC PHI node to feed the merge PHI.  */
    1840         1710 :                   tree *res;
    1841         3420 :                   if (virtual_operand_p (new_arg))
    1842              :                     {
    1843              :                       /* Use the existing virtual LC SSA from exit block.  */
    1844          441 :                       gphi *vphi = get_virtual_phi (main_loop_exit_block);
    1845          441 :                       new_arg = gimple_phi_result (vphi);
    1846              :                     }
    1847         1269 :                   else if ((res = new_phi_args.get (new_arg)))
    1848          108 :                     new_arg = *res;
    1849              :                   else
    1850              :                     {
    1851              :                       /* Create the LC PHI node for the exit.  */
    1852         1161 :                       tree new_def = copy_ssa_name (new_arg);
    1853         1161 :                       gphi *lc_phi
    1854         1161 :                           = create_phi_node (new_def, main_loop_exit_block);
    1855         1161 :                       SET_PHI_ARG_DEF (lc_phi, 0, new_arg);
    1856         1161 :                       new_arg = new_def;
    1857              :                     }
    1858              : 
    1859              :                   /* Create the PHI node in the merge block merging the
    1860              :                      main and early exit values.  */
    1861         1710 :                   tree new_res = copy_ssa_name (gimple_phi_result (from_phi));
    1862         1710 :                   gphi *lcssa_phi = create_phi_node (new_res, new_preheader);
    1863         1710 :                   edge main_e = single_succ_edge (main_loop_exit_block);
    1864         1710 :                   SET_PHI_ARG_DEF_ON_EDGE (lcssa_phi, main_e, new_arg);
    1865              : 
    1866              :                   /* And adjust the epilog entry value.  */
    1867         1710 :                   adjust_phi_and_debug_stmts (to_phi, loop_entry, new_res);
    1868              :                 }
    1869              :             }
    1870              : 
    1871          655 :           if (redirect_multiple_exits_p)
    1872              :             {
    1873              :               /* After creating the merge PHIs handle the early exits those
    1874              :                  should use the values at the start of the loop.  */
    1875          655 :               for (auto gsi_from = gsi_start_phis (loop->header),
    1876          655 :                    gsi_to = gsi_start_phis (new_preheader);
    1877         2365 :                    !gsi_end_p (gsi_from) && !gsi_end_p (gsi_to);
    1878         1710 :                    gsi_next (&gsi_from), gsi_next (&gsi_to))
    1879              :                 {
    1880         1710 :                   gimple *from_phi = gsi_stmt (gsi_from);
    1881         1710 :                   gimple *to_phi = gsi_stmt (gsi_to);
    1882              : 
    1883              :                   /* Now update the virtual PHI nodes with the right value.  */
    1884         1710 :                   tree alt_arg = gimple_phi_result (from_phi);
    1885         3420 :                   if (virtual_operand_p (alt_arg))
    1886              :                     {
    1887          441 :                       gphi *vphi = get_virtual_phi (alt_loop_exit_block);
    1888          441 :                       alt_arg = gimple_phi_result (vphi);
    1889              :                     }
    1890              :                   /* For other live args we didn't create LC PHI nodes.
    1891              :                      Do so here.  */
    1892              :                   else
    1893              :                     {
    1894         1269 :                       tree alt_def = copy_ssa_name (alt_arg);
    1895         1269 :                       gphi *lc_phi
    1896         1269 :                         = create_phi_node (alt_def, alt_loop_exit_block);
    1897         4120 :                       for (unsigned i = 0; i < gimple_phi_num_args (lc_phi);
    1898              :                            ++i)
    1899         1582 :                         SET_PHI_ARG_DEF (lc_phi, i, alt_arg);
    1900              :                       alt_arg = alt_def;
    1901              :                     }
    1902              : 
    1903              :                   /* The merge PHIs live in NEW_PREHEADER; their
    1904              :                      alternative argument always comes from the
    1905              :                      successor edge of ALT_LOOP_EXIT_BLOCK.  */
    1906         1710 :                   edge alt_e = single_succ_edge (alt_loop_exit_block);
    1907         1710 :                   SET_PHI_ARG_DEF_ON_EDGE (to_phi, alt_e, alt_arg);
    1908              :                 }
    1909              :             }
    1910              : 
    1911              :           /* For the single exit case only create the missing LC PHI nodes
    1912              :              for the continuation of the loop IVs that are not also already
    1913              :              reductions and thus had LC PHI nodes on the exit already.  When
    1914              :              we are not redirecting the alternative exits the layout is:
    1915              : 
    1916              :                    loop_exit ---> new_preheader ---> epilog
    1917              :                    alt_exit ---------------> original dest
    1918              :            */
    1919          655 :           if (!redirect_multiple_exits_p)
    1920              :             {
    1921        35245 :               for (auto gsi_from = gsi_start_phis (loop->header),
    1922        35245 :                    gsi_to = gsi_start_phis (new_loop->header);
    1923       134049 :                    !gsi_end_p (gsi_from) && !gsi_end_p (gsi_to);
    1924        98804 :                    gsi_next (&gsi_from), gsi_next (&gsi_to))
    1925              :                 {
    1926        98804 :                   gimple *from_phi = gsi_stmt (gsi_from);
    1927        98804 :                   gimple *to_phi = gsi_stmt (gsi_to);
    1928        98804 :                   tree new_arg;
    1929              : 
    1930              :                   /* Use the value on the exiting path.  When the exit is from
    1931              :                      the latch edge we want the post-iteration value on that
    1932              :                      edge; when the exit is from the loop header (before the
    1933              :                      latch ever executes) we must use the current header value,
    1934              :                      otherwise we pick up a name that was never defined.  */
    1935        98804 :                   if (!has_multiple_exits_p && !uncounted_p)
    1936        98460 :                     new_arg = PHI_ARG_DEF_FROM_EDGE (from_phi,
    1937              :                                                      loop_latch_edge (loop));
    1938              :                   else
    1939          344 :                     new_arg = gimple_phi_result (from_phi);
    1940              : 
    1941              :                   /* Re-use the virtual LC PHI we already built when we are not
    1942              :                      redirecting the other exits to avoid creating duplicate
    1943              :                      virtual SSA names.  */
    1944       197608 :                   if (virtual_operand_p (new_arg))
    1945              :                     {
    1946        27206 :                       if (gphi *vphi = get_virtual_phi (main_loop_exit_block))
    1947              :                         {
    1948        27206 :                           adjust_phi_and_debug_stmts (to_phi, loop_entry,
    1949              :                                                       gimple_phi_result (vphi));
    1950        45400 :                           continue;
    1951              :                         }
    1952              :                     }
    1953              : 
    1954              :                   /* Check if we've already created a new phi node during edge
    1955              :                      redirection.  If we have, only propagate the value
    1956              :                      downwards.  */
    1957        71598 :                   if (tree *res = new_phi_args.get (new_arg))
    1958              :                     {
    1959              :                       /* Check if the new dest block already contains a use.  */
    1960        18194 :                       gimple *stmt = SSA_NAME_DEF_STMT (*res);
    1961              : 
    1962              :                       /* If the value already exist, just update the destination
    1963              :                          and if it doesn't we want a new node.  */
    1964        18194 :                       if (gimple_bb (stmt) == main_loop_exit_block)
    1965              :                         {
    1966        18194 :                           adjust_phi_and_debug_stmts (to_phi, loop_entry, *res);
    1967        18194 :                           continue;
    1968              :                         }
    1969              :                       else
    1970            0 :                         new_arg = *res;
    1971              :                     }
    1972              : 
    1973        53404 :                   tree new_res = copy_ssa_name (gimple_phi_result (from_phi));
    1974        53404 :                   gphi *lcssa_phi = create_phi_node (new_res, main_loop_exit_block);
    1975        53404 :                   SET_PHI_ARG_DEF (lcssa_phi, loop_exit->dest_idx, new_arg);
    1976        53404 :                   adjust_phi_and_debug_stmts (to_phi, loop_entry, new_res);
    1977              :                 }
    1978              :             }
    1979        35900 :         }
    1980              : 
    1981        35900 :       if (was_imm_dom || duplicate_outer_loop)
    1982        35617 :         set_immediate_dominator (CDI_DOMINATORS, exit_dest, new_exit->src);
    1983              : 
    1984              :       /* And remove the non-necessary forwarder again.  Keep the other
    1985              :          one so we have a proper pre-header for the loop at the exit edge.  */
    1986        35900 :       redirect_edge_pred (single_succ_edge (preheader),
    1987              :                           single_pred (preheader));
    1988        35900 :       delete_basic_block (preheader);
    1989        35900 :       set_immediate_dominator (CDI_DOMINATORS, scalar_loop->header,
    1990        35900 :                                loop_preheader_edge (scalar_loop)->src);
    1991              : 
    1992              :       /* Finally after wiring the new epilogue we need to update its main exit
    1993              :          to the original function exit we recorded.  Other exits are already
    1994              :          correct.  */
    1995        35900 :       if (has_multiple_exits_p || uncounted_p)
    1996              :         {
    1997          913 :           class loop *update_loop = new_loop;
    1998          913 :           doms = get_all_dominated_blocks (CDI_DOMINATORS, loop->header);
    1999        20097 :           for (unsigned i = 0; i < doms.length (); ++i)
    2000        19184 :             if (flow_bb_inside_loop_p (loop, doms[i]))
    2001         2840 :               doms.unordered_remove (i);
    2002              : 
    2003         4679 :           for (edge e : get_loop_exit_edges (update_loop))
    2004              :             {
    2005         1940 :               edge ex;
    2006         1940 :               edge_iterator ei;
    2007         3917 :               FOR_EACH_EDGE (ex, ei, e->dest->succs)
    2008              :                 {
    2009              :                   /* Find the first non-fallthrough block as fall-throughs can't
    2010              :                      dominate other blocks.  */
    2011         1977 :                   if (single_succ_p (ex->dest))
    2012              :                     {
    2013         1098 :                       doms.safe_push (ex->dest);
    2014         1098 :                       ex = single_succ_edge (ex->dest);
    2015              :                     }
    2016         1977 :                   doms.safe_push (ex->dest);
    2017              :                 }
    2018         1940 :               doms.safe_push (e->dest);
    2019          913 :             }
    2020              : 
    2021          913 :           iterate_fix_dominators (CDI_DOMINATORS, doms, false);
    2022          913 :           if (updated_doms)
    2023          913 :             updated_doms->safe_splice (doms);
    2024              :         }
    2025              :     }
    2026              :   else /* Add the copy at entry.  */
    2027              :     {
    2028              :       /* Copy the current loop LC PHI nodes between the original loop exit
    2029              :          block and the new loop header.  This allows us to later split the
    2030              :          preheader block and still find the right LC nodes.  */
    2031         1793 :       if (flow_loops)
    2032          468 :         for (auto gsi_from = gsi_start_phis (new_loop->header),
    2033          468 :              gsi_to = gsi_start_phis (loop->header);
    2034         1441 :              !gsi_end_p (gsi_from) && !gsi_end_p (gsi_to);
    2035          973 :              gsi_next (&gsi_from), gsi_next (&gsi_to))
    2036              :           {
    2037          973 :             gimple *from_phi = gsi_stmt (gsi_from);
    2038          973 :             gimple *to_phi = gsi_stmt (gsi_to);
    2039          973 :             tree new_arg = PHI_ARG_DEF_FROM_EDGE (from_phi,
    2040              :                                                   loop_latch_edge (new_loop));
    2041          973 :             adjust_phi_and_debug_stmts (to_phi, loop_preheader_edge (loop),
    2042              :                                         new_arg);
    2043              :           }
    2044              : 
    2045         1793 :       if (scalar_loop != loop)
    2046              :         {
    2047              :           /* Remove the non-necessary forwarder of scalar_loop again.  */
    2048            4 :           redirect_edge_pred (single_succ_edge (preheader),
    2049              :                               single_pred (preheader));
    2050            4 :           delete_basic_block (preheader);
    2051            4 :           set_immediate_dominator (CDI_DOMINATORS, scalar_loop->header,
    2052            4 :                                    loop_preheader_edge (scalar_loop)->src);
    2053            4 :           preheader = split_edge (loop_preheader_edge (loop));
    2054            4 :           entry_e = single_pred_edge (preheader);
    2055              :         }
    2056              : 
    2057         1793 :       redirect_edge_and_branch_force (entry_e, new_preheader);
    2058         1793 :       flush_pending_stmts (entry_e);
    2059         1793 :       set_immediate_dominator (CDI_DOMINATORS, new_preheader, entry_e->src);
    2060              : 
    2061              : 
    2062              :       /* `vect_set_loop_condition' replaces the condition in the main exit of
    2063              :          loop.  For counted loops, this is the IV counting exit, so in the case
    2064              :          of the prolog loop, we are replacing the old IV counting exit limit of
    2065              :          total loop niters for the new limit of the prolog niters, as desired.
    2066              :          For uncounted loops, we don't have an IV-counting exit to replace, so
    2067              :          we add a dummy exit to be consumed by `vect_set_loop_condition' later
    2068              :          on.  */
    2069         1793 :       if (create_main_e)
    2070              :         {
    2071           40 :           edge to_latch_e = single_pred_edge (new_loop->latch);
    2072           40 :           bool latch_is_false = to_latch_e->flags & EDGE_FALSE_VALUE ? true
    2073              :                                                                      : false;
    2074              : 
    2075              :           /* Add new bb for duplicate exit.  */
    2076           40 :           basic_block bbcond = split_edge (to_latch_e);
    2077           40 :           gimple_stmt_iterator a = gsi_last_bb (bbcond);
    2078              : 
    2079              :           /* Fix flags for the edge leading to the latch.  */
    2080           40 :           to_latch_e = find_edge (bbcond, new_loop->latch);
    2081           40 :           to_latch_e->flags &= ~EDGE_FALLTHRU;
    2082           40 :           to_latch_e->flags |= latch_is_false ? EDGE_FALSE_VALUE
    2083              :                                               : EDGE_TRUE_VALUE;
    2084              : 
    2085              :           /* Build the condition.  */
    2086           40 :           tree cone = build_int_cst (sizetype, 1);
    2087           40 :           tree czero = build_int_cst (sizetype, 0);
    2088           40 :           gcond *cond_copy = gimple_build_cond (NE_EXPR, cone, czero, NULL_TREE,
    2089              :                                                 NULL_TREE);
    2090              : 
    2091           40 :           gsi_insert_after (&a, cond_copy, GSI_NEW_STMT);
    2092              : 
    2093              :           /* Add edge for exiting the loop via new condition.  */
    2094           56 :           edge dup_exit = make_edge (bbcond, new_exit->dest, latch_is_false
    2095              :                                 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE);
    2096              : 
    2097           40 :           profile_probability probability = profile_probability::even ();
    2098           40 :           to_latch_e->probability = dup_exit->probability = probability;
    2099              : 
    2100           40 :           set_immediate_dominator (CDI_DOMINATORS, dup_exit->src,
    2101              :                                    new_exit->src);
    2102           40 :           new_exit = dup_exit;
    2103           40 :           *new_e = new_exit;
    2104              :         }
    2105              : 
    2106         1793 :       redirect_edge_and_branch_force (new_exit, preheader);
    2107         1793 :       flush_pending_stmts (new_exit);
    2108         1793 :       set_immediate_dominator (CDI_DOMINATORS, preheader, new_exit->src);
    2109              : 
    2110              :       /* And remove the non-necessary forwarder again.  Keep the other
    2111              :          one so we have a proper pre-header for the loop at the exit edge.  */
    2112         1793 :       redirect_edge_pred (single_succ_edge (new_preheader),
    2113              :                           single_pred (new_preheader));
    2114         1793 :       delete_basic_block (new_preheader);
    2115         1793 :       set_immediate_dominator (CDI_DOMINATORS, new_loop->header,
    2116         1793 :                                loop_preheader_edge (new_loop)->src);
    2117              : 
    2118              :       /* Update dominators for multiple exits.  */
    2119         1793 :       if (has_multiple_exits_p || create_main_e)
    2120              :         {
    2121         1224 :           for (edge alt_e : loop_exits)
    2122              :             {
    2123          480 :               if ((alt_e == loop_exit) && !create_main_e)
    2124          208 :                 continue;
    2125          272 :               basic_block old_dom
    2126          272 :                 = get_immediate_dominator (CDI_DOMINATORS, alt_e->dest);
    2127          272 :               if (flow_bb_inside_loop_p (loop, old_dom))
    2128              :                 {
    2129          113 :                   auto_vec<basic_block, 8> queue;
    2130          113 :                   for (auto son = first_dom_son (CDI_DOMINATORS, old_dom);
    2131          363 :                        son; son = next_dom_son (CDI_DOMINATORS, son))
    2132          250 :                     if (!flow_bb_inside_loop_p (loop, son))
    2133          137 :                       queue.safe_push (son);
    2134          476 :                   for (auto son : queue)
    2135          137 :                     set_immediate_dominator (CDI_DOMINATORS,
    2136              :                                              son, get_bb_copy (old_dom));
    2137          113 :                 }
    2138              :             }
    2139              :         }
    2140              : 
    2141              :       /* When loop_exit != scalar_exit due to if-conversion loop versioning,
    2142              :          the `scalar_exit' now has two incoming edges, one from the if-converted
    2143              :          and one from the peeled prolog loop.  It is therefore dominated by a
    2144              :          common block between these.  Update its dominator accordingly.  */
    2145          248 :       if (create_main_e && loop_exit != scalar_exit)
    2146            0 :         set_immediate_dominator (CDI_DOMINATORS, scalar_exit->dest,
    2147              :                                  recompute_dominator (CDI_DOMINATORS,
    2148              :                                                       scalar_exit->dest));
    2149              :     }
    2150              : 
    2151        37693 :   free (new_bbs);
    2152        37693 :   free (bbs);
    2153              : 
    2154        37693 :   checking_verify_dominators (CDI_DOMINATORS);
    2155              : 
    2156        37693 :   return new_loop;
    2157        37693 : }
    2158              : 
    2159              : 
    2160              : /* Given the condition expression COND, put it as the last statement of
    2161              :    GUARD_BB; set both edges' probability; set dominator of GUARD_TO to
    2162              :    DOM_BB; return the skip edge.  GUARD_TO is the target basic block to
    2163              :    skip the loop.  PROBABILITY is the skip edge's probability.  Mark the
    2164              :    new edge as irreducible if IRREDUCIBLE_P is true.  */
    2165              : 
    2166              : static edge
    2167        54365 : slpeel_add_loop_guard (basic_block guard_bb, tree cond,
    2168              :                        basic_block guard_to, basic_block dom_bb,
    2169              :                        profile_probability probability, bool irreducible_p)
    2170              : {
    2171        54365 :   gimple_stmt_iterator gsi;
    2172        54365 :   edge new_e, enter_e;
    2173        54365 :   gcond *cond_stmt;
    2174        54365 :   gimple_seq gimplify_stmt_list = NULL;
    2175              : 
    2176        54365 :   enter_e = EDGE_SUCC (guard_bb, 0);
    2177        54365 :   enter_e->flags &= ~EDGE_FALLTHRU;
    2178        54365 :   enter_e->flags |= EDGE_FALSE_VALUE;
    2179        54365 :   gsi = gsi_last_bb (guard_bb);
    2180              : 
    2181        54365 :   cond = force_gimple_operand_1 (cond, &gimplify_stmt_list,
    2182              :                                  is_gimple_condexpr_for_cond, NULL_TREE);
    2183        54365 :   if (gimplify_stmt_list)
    2184        24443 :     gsi_insert_seq_after (&gsi, gimplify_stmt_list, GSI_NEW_STMT);
    2185              : 
    2186        54365 :   cond_stmt = gimple_build_cond_from_tree (cond, NULL_TREE, NULL_TREE);
    2187        54365 :   gsi = gsi_last_bb (guard_bb);
    2188        54365 :   gsi_insert_after (&gsi, cond_stmt, GSI_NEW_STMT);
    2189              : 
    2190              :   /* Add new edge to connect guard block to the merge/loop-exit block.  */
    2191        54365 :   new_e = make_edge (guard_bb, guard_to, EDGE_TRUE_VALUE);
    2192              : 
    2193        54365 :   new_e->probability = probability;
    2194        54365 :   if (irreducible_p)
    2195           14 :     new_e->flags |= EDGE_IRREDUCIBLE_LOOP;
    2196              : 
    2197        54365 :   enter_e->probability = probability.invert ();
    2198        54365 :   set_immediate_dominator (CDI_DOMINATORS, guard_to, dom_bb);
    2199              : 
    2200              :   /* Split enter_e to preserve LOOPS_HAVE_PREHEADERS.  */
    2201        54365 :   if (enter_e->dest->loop_father->header == enter_e->dest)
    2202          517 :     split_edge (enter_e);
    2203              : 
    2204        54365 :   return new_e;
    2205              : }
    2206              : 
    2207              : 
    2208              : /* This function verifies that the following restrictions apply to LOOP:
    2209              :    (1) it consists of exactly 2 basic blocks - header, and an empty latch
    2210              :        for innermost loop and 5 basic blocks for outer-loop.
    2211              :    (2) it is single entry, single exit
    2212              :    (3) its exit condition is the last stmt in the header
    2213              :    (4) E is the entry/exit edge of LOOP.
    2214              :  */
    2215              : 
    2216              : bool
    2217       538130 : slpeel_can_duplicate_loop_p (const class loop *loop, const_edge exit_e,
    2218              :                              const_edge e)
    2219              : {
    2220       538130 :   edge entry_e = loop_preheader_edge (loop);
    2221       538130 :   gcond *orig_cond = get_loop_exit_condition (exit_e);
    2222       538130 :   gimple_stmt_iterator loop_exit_gsi = gsi_last_bb (exit_e->src);
    2223              : 
    2224              :   /* All loops have an outer scope; the only case loop->outer is NULL is for
    2225              :      the function itself.  */
    2226       538130 :   if (!loop_outer (loop)
    2227       538130 :       || !empty_block_p (loop->latch)
    2228              :       || !exit_e
    2229              :       /* Verify that new loop exit condition can be trivially modified.  */
    2230       538130 :       || (!orig_cond || orig_cond != gsi_stmt (loop_exit_gsi))
    2231      1076260 :       || (e != exit_e && e != entry_e))
    2232              :     return false;
    2233              : 
    2234       538130 :   basic_block *bbs = XNEWVEC (basic_block, loop->num_nodes);
    2235       538130 :   get_loop_body_with_size (loop, bbs, loop->num_nodes);
    2236       538130 :   bool ret = can_copy_bbs_p (bbs, loop->num_nodes);
    2237       538130 :   free (bbs);
    2238       538130 :   return ret;
    2239              : }
    2240              : 
    2241              : /* Function find_loop_location.
    2242              : 
    2243              :    Extract the location of the loop in the source code.
    2244              :    If the loop is not well formed for vectorization, an estimated
    2245              :    location is calculated.
    2246              :    Return the loop location if succeed and NULL if not.  */
    2247              : 
    2248              : dump_user_location_t
    2249      3725594 : find_loop_location (class loop *loop)
    2250              : {
    2251      3725594 :   gimple *stmt = NULL;
    2252      3725594 :   basic_block bb;
    2253      3725594 :   gimple_stmt_iterator si;
    2254              : 
    2255      3725594 :   if (!loop)
    2256            0 :     return dump_user_location_t ();
    2257              : 
    2258              :   /* For the root of the loop tree return the function location.  */
    2259      3725594 :   if (!loop_outer (loop))
    2260            0 :     return dump_user_location_t::from_function_decl (cfun->decl);
    2261              : 
    2262      3725594 :   if (loops_state_satisfies_p (LOOPS_HAVE_RECORDED_EXITS))
    2263              :     {
    2264              :       /* We only care about the loop location, so use any exit with location
    2265              :          information.  */
    2266     11692752 :       for (edge e : get_loop_exit_edges (loop))
    2267              :         {
    2268      3823538 :           stmt = get_loop_exit_condition (e);
    2269              : 
    2270      3823538 :           if (stmt
    2271      3823538 :               && LOCATION_LOCUS (gimple_location (stmt)) > BUILTINS_LOCATION)
    2272      3247450 :             return stmt;
    2273      3725594 :         }
    2274              :     }
    2275              : 
    2276              :   /* If we got here the loop is probably not "well formed",
    2277              :      try to estimate the loop location */
    2278              : 
    2279       478144 :   if (!loop->header)
    2280            0 :     return dump_user_location_t ();
    2281              : 
    2282       478144 :   bb = loop->header;
    2283              : 
    2284      1731758 :   for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
    2285              :     {
    2286      1128710 :       stmt = gsi_stmt (si);
    2287      1128710 :       if (LOCATION_LOCUS (gimple_location (stmt)) > BUILTINS_LOCATION)
    2288       353240 :         return stmt;
    2289              :     }
    2290              : 
    2291       124904 :   return dump_user_location_t ();
    2292              : }
    2293              : 
    2294              : /* Return true if the phi described by STMT_INFO defines an IV of the
    2295              :    loop to be vectorized.  */
    2296              : 
    2297              : static bool
    2298      1443871 : iv_phi_p (stmt_vec_info stmt_info)
    2299              : {
    2300      1443871 :   gphi *phi = as_a <gphi *> (stmt_info->stmt);
    2301      2887742 :   if (virtual_operand_p (PHI_RESULT (phi)))
    2302              :     return false;
    2303              : 
    2304      1144844 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    2305      1144844 :       || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    2306       162331 :     return false;
    2307              : 
    2308              :   return true;
    2309              : }
    2310              : 
    2311              : /* Return true if vectorizer can peel for nonlinear iv.  */
    2312              : static bool
    2313         8452 : vect_can_peel_nonlinear_iv_p (loop_vec_info loop_vinfo,
    2314              :                               stmt_vec_info stmt_info)
    2315              : {
    2316         8452 :   enum vect_induction_op_type induction_type
    2317              :     = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
    2318         8452 :   tree niters_skip;
    2319              :   /* Init_expr will be update by vect_update_ivs_after_vectorizer,
    2320              :      if niters or vf is unknown:
    2321              :      For shift, when shift mount >= precision, there would be UD.
    2322              :      For mult, don't known how to generate
    2323              :      init_expr * pow (step, niters) for variable niters.
    2324              :      For neg unknown niters are ok, since niters of vectorized main loop
    2325              :      will always be multiple of 2.
    2326              :      See also PR113163,  PR114196 and PR114485.  */
    2327         8452 :   if (!LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ()
    2328         8452 :       || LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2329         8452 :       || (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    2330         3479 :           && induction_type != vect_step_op_neg))
    2331              :     {
    2332         3280 :       if (dump_enabled_p ())
    2333           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2334              :                          "Peeling for epilogue is not supported"
    2335              :                          " for this nonlinear induction"
    2336              :                          " when iteration count is unknown or"
    2337              :                          " when using partial vectorization.\n");
    2338              :       return false;
    2339              :     }
    2340              : 
    2341         5172 :   if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    2342          512 :       && (induction_type == vect_step_op_mul
    2343              :           || induction_type == vect_step_op_shl
    2344          512 :           || induction_type == vect_step_op_shr))
    2345              :     {
    2346          512 :       if (dump_enabled_p ())
    2347          412 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2348              :                          "Peeling for is not supported for nonlinear %s"
    2349              :                          " induction using partial vectorization.\n",
    2350              :                          induction_type == vect_step_op_mul
    2351              :                          ? "mult" : "shift");
    2352              :       return false;
    2353              :     }
    2354              : 
    2355              :   /* Avoid compile time hog on vect_peel_nonlinear_iv_init.  */
    2356         4660 :   if (induction_type == vect_step_op_mul)
    2357              :     {
    2358          407 :       tree step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
    2359          407 :       tree type = TREE_TYPE (step_expr);
    2360              : 
    2361          808 :       if (wi::exact_log2 (wi::to_wide (step_expr)) == -1
    2362          407 :           && LOOP_VINFO_INT_NITERS(loop_vinfo) >= TYPE_PRECISION (type))
    2363              :         {
    2364            6 :           if (dump_enabled_p ())
    2365            6 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2366              :                              "Avoid compile time hog on"
    2367              :                              " vect_peel_nonlinear_iv_init"
    2368              :                              " for nonlinear induction vec_step_op_mul"
    2369              :                              " when iteration count is too big.\n");
    2370              :           return false;
    2371              :         }
    2372              :     }
    2373              : 
    2374              :   /* Also doesn't support peel for neg when niter is variable.
    2375              :      ??? generate something like niter_expr & 1 ? init_expr : -init_expr?  */
    2376         4654 :   niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
    2377         4654 :   if ((niters_skip != NULL_TREE
    2378            0 :        && (TREE_CODE (niters_skip) != INTEGER_CST
    2379            0 :            || (HOST_WIDE_INT) TREE_INT_CST_LOW (niters_skip) < 0))
    2380         4654 :       || (!vect_use_loop_mask_for_alignment_p (loop_vinfo)
    2381         4654 :           && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0))
    2382              :     {
    2383            4 :       if (dump_enabled_p ())
    2384            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2385              :                          "Peeling for alignment is not supported"
    2386              :                          " for nonlinear induction when niters_skip"
    2387              :                          " is not constant.\n");
    2388              :       return false;
    2389              :     }
    2390              : 
    2391              :   return true;
    2392              : }
    2393              : 
    2394              : /* Function vect_can_advance_ivs_p
    2395              : 
    2396              :    In case the number of iterations that LOOP iterates is unknown at compile
    2397              :    time, an epilog loop will be generated, and the loop induction variables
    2398              :    (IVs) will be "advanced" to the value they are supposed to take just before
    2399              :    the epilog loop.  Here we check that the access function of the loop IVs
    2400              :    and the expression that represents the loop bound are simple enough.
    2401              :    These restrictions will be relaxed in the future.  */
    2402              : 
    2403              : bool
    2404       542727 : vect_can_advance_ivs_p (loop_vec_info loop_vinfo)
    2405              : {
    2406       542727 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    2407       542727 :   basic_block bb = loop->header;
    2408       542727 :   gphi_iterator gsi;
    2409              : 
    2410              :   /* Analyze phi functions of the loop header.  */
    2411              : 
    2412       542727 :   if (dump_enabled_p ())
    2413        28156 :     dump_printf_loc (MSG_NOTE, vect_location, "vect_can_advance_ivs_p:\n");
    2414      1879252 :   for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
    2415              :     {
    2416      1341647 :       tree evolution_part;
    2417      1341647 :       enum vect_induction_op_type induction_type;
    2418              : 
    2419      1341647 :       gphi *phi = gsi.phi ();
    2420      1341647 :       stmt_vec_info phi_info = loop_vinfo->lookup_stmt (phi);
    2421      1341647 :       if (dump_enabled_p ())
    2422        78924 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
    2423              :                          phi_info->stmt);
    2424              : 
    2425              :       /* Skip virtual phi's. The data dependences that are associated with
    2426              :          virtual defs/uses (i.e., memory accesses) are analyzed elsewhere.
    2427              : 
    2428              :          Skip reduction phis.  */
    2429      1341647 :       if (!iv_phi_p (phi_info))
    2430              :         {
    2431       415443 :           if (dump_enabled_p ())
    2432        27988 :             dump_printf_loc (MSG_NOTE, vect_location,
    2433              :                              "reduc or virtual phi. skip.\n");
    2434       415443 :           continue;
    2435              :         }
    2436              : 
    2437       926204 :       induction_type = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (phi_info);
    2438       926204 :       if (induction_type != vect_step_op_add)
    2439              :         {
    2440         8452 :           if (!vect_can_peel_nonlinear_iv_p (loop_vinfo, phi_info))
    2441              :             return false;
    2442              : 
    2443         4650 :           continue;
    2444              :         }
    2445              : 
    2446              :       /* Analyze the evolution function.  */
    2447              : 
    2448       917752 :       evolution_part = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
    2449       917752 :       if (evolution_part == NULL_TREE)
    2450              :         {
    2451         1304 :           if (dump_enabled_p ())
    2452           81 :             dump_printf (MSG_MISSED_OPTIMIZATION,
    2453              :                          "No access function or evolution.\n");
    2454              :           return false;
    2455              :         }
    2456              : 
    2457              :       /* FORNOW: We do not transform initial conditions of IVs
    2458              :          which evolution functions are not invariants in the loop.  */
    2459              : 
    2460       916448 :       if (!expr_invariant_in_loop_p (loop, evolution_part))
    2461              :         {
    2462           16 :           if (dump_enabled_p ())
    2463            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2464              :                              "evolution not invariant in loop.\n");
    2465              :           return false;
    2466              :         }
    2467              : 
    2468              :       /* FORNOW: We do not transform initial conditions of IVs
    2469              :          which evolution functions are a polynomial of degree >= 2.  */
    2470              : 
    2471      2252957 :       if (tree_is_chrec (evolution_part))
    2472              :         {
    2473            0 :           if (dump_enabled_p ())
    2474            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2475              :                              "evolution is chrec.\n");
    2476              :           return false;
    2477              :         }
    2478              :     }
    2479              : 
    2480              :   return true;
    2481              : }
    2482              : 
    2483              : 
    2484              : /*   Function vect_update_ivs_after_vectorizer.
    2485              : 
    2486              :      "Advance" the induction variables of LOOP to the value they should take
    2487              :      after the execution of LOOP.  This is currently necessary because the
    2488              :      vectorizer does not handle induction variables that are used after the
    2489              :      loop.  Such a situation occurs when the last iterations of LOOP are
    2490              :      peeled, because:
    2491              :      1. We introduced new uses after LOOP for IVs that were not originally used
    2492              :         after LOOP: the IVs of LOOP are now used by an epilog loop.
    2493              :      2. LOOP is going to be vectorized; this means that it will iterate N/VF
    2494              :         times, whereas the loop IVs should be bumped N times.
    2495              : 
    2496              :      Input:
    2497              :      - LOOP - a loop that is going to be vectorized. The last few iterations
    2498              :               of LOOP were peeled.
    2499              :      - NITERS - the number of iterations that LOOP executes (before it is
    2500              :                 vectorized). i.e, the number of times the ivs should be bumped.
    2501              :      - UPDATE_E - a successor edge of LOOP->exit that is on the (only) path
    2502              :                   coming out from LOOP on which there are uses of the LOOP ivs
    2503              :                   (this is the path from LOOP->exit to epilog_loop->preheader).
    2504              : 
    2505              :                   The new definitions of the ivs are placed in LOOP->exit.
    2506              :                   The phi args associated with the edge UPDATE_E in the bb
    2507              :                   UPDATE_E->dest are updated accordingly.
    2508              : 
    2509              :      - EARLY_EXIT_P - Indicates whether the exit is an early exit rather than
    2510              :                       the main latch exit.
    2511              : 
    2512              :      Assumption 1: Like the rest of the vectorizer, this function assumes
    2513              :      a single loop exit that has a single predecessor.
    2514              : 
    2515              :      Assumption 2: The phi nodes in the LOOP header and in update_bb are
    2516              :      organized in the same order.
    2517              : 
    2518              :      Assumption 3: The access function of the ivs is simple enough (see
    2519              :      vect_can_advance_ivs_p).  This assumption will be relaxed in the future.
    2520              : 
    2521              :      Assumption 4: Exactly one of the successors of LOOP exit-bb is on a path
    2522              :      coming out of LOOP on which the ivs of LOOP are used (this is the path
    2523              :      that leads to the epilog loop; other paths skip the epilog loop).  This
    2524              :      path starts with the edge UPDATE_E, and its destination (denoted update_bb)
    2525              :      needs to have its phis updated.
    2526              :  */
    2527              : 
    2528              : static void
    2529        36555 : vect_update_ivs_after_vectorizer (loop_vec_info loop_vinfo,
    2530              :                                   tree niters, edge update_e,
    2531              :                                   bool early_exit_p)
    2532              : {
    2533        36555 :   gphi_iterator gsi, gsi1;
    2534        36555 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    2535        36555 :   basic_block update_bb = update_e->dest;
    2536        36555 :   basic_block exit_bb = update_e->src;
    2537              :   /* Check to see if this is an empty loop pre-header block.  If it exists
    2538              :      we need to use the edge from that block -> loop header for updates but
    2539              :      must use the original exit_bb to add any new adjustment because there
    2540              :      can be a skip_epilog edge bypassing the epilog and so the loop pre-header
    2541              :      too.  */
    2542        36647 :   if (empty_block_p (update_bb) && single_succ_p (update_bb))
    2543              :     {
    2544           92 :       update_e = single_succ_edge (update_bb);
    2545           92 :       update_bb = update_e->dest;
    2546              :     }
    2547        36555 :   gimple_stmt_iterator last_gsi = gsi_last_bb (exit_bb);
    2548              : 
    2549        36555 :   for (gsi = gsi_start_phis (loop->header), gsi1 = gsi_start_phis (update_bb);
    2550       138779 :        !gsi_end_p (gsi) && !gsi_end_p (gsi1);
    2551       102224 :        gsi_next (&gsi), gsi_next (&gsi1))
    2552              :     {
    2553       102224 :       tree init_expr;
    2554       102224 :       tree step_expr;
    2555       102224 :       tree type;
    2556       102224 :       tree var, ni, ni_name;
    2557              : 
    2558       102224 :       gphi *phi = gsi.phi ();
    2559       102224 :       gphi *phi1 = gsi1.phi ();
    2560       102224 :       stmt_vec_info phi_info = loop_vinfo->lookup_stmt (phi);
    2561       102224 :       if (dump_enabled_p ())
    2562        13483 :         dump_printf_loc (MSG_NOTE, vect_location,
    2563              :                          "vect_update_ivs_after_vectorizer: phi: %G",
    2564              :                          (gimple *) phi);
    2565              : 
    2566              :       /* Skip reduction and virtual phis.  */
    2567       102224 :       if (!iv_phi_p (phi_info))
    2568              :         {
    2569        45915 :           if (dump_enabled_p ())
    2570         5279 :             dump_printf_loc (MSG_NOTE, vect_location,
    2571              :                              "reduc or virtual phi. skip.\n");
    2572        45915 :           continue;
    2573              :         }
    2574              : 
    2575        56309 :       type = TREE_TYPE (gimple_phi_result (phi));
    2576        56309 :       step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
    2577        56309 :       step_expr = unshare_expr (step_expr);
    2578              : 
    2579              :       /* FORNOW: We do not support IVs whose evolution function is a polynomial
    2580              :          of degree >= 2 or exponential.  */
    2581        56309 :       gcc_assert (!tree_is_chrec (step_expr));
    2582              : 
    2583        56309 :       init_expr = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
    2584        56309 :       gimple_seq stmts = NULL;
    2585        56309 :       enum vect_induction_op_type induction_type
    2586              :         = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (phi_info);
    2587              : 
    2588        56309 :       if (induction_type == vect_step_op_add)
    2589              :         {
    2590              :           /* Use an unsigned type because we compute 'off' without
    2591              :              accounting for 'init_expr', thus the computation might
    2592              :              overflow.  Note we can also have FP inductions.  */
    2593       112352 :           tree ctype = (INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
    2594       112346 :                         ? unsigned_type_for (TREE_TYPE (step_expr))
    2595        56176 :                         : TREE_TYPE (step_expr));
    2596        56176 :           tree off = fold_build2 (MULT_EXPR, ctype,
    2597              :                                   fold_convert (ctype, niters),
    2598              :                                   fold_convert (ctype, step_expr));
    2599        56176 :           ni = fold_convert (type,
    2600              :                              fold_build2 (PLUS_EXPR, ctype,
    2601              :                                           fold_convert (ctype, init_expr),
    2602              :                                           off));
    2603              :         }
    2604              :       /* Don't bother call vect_peel_nonlinear_iv_init.  */
    2605          133 :       else if (induction_type == vect_step_op_neg)
    2606              :         ni = init_expr;
    2607              :       else
    2608           83 :         ni = vect_peel_nonlinear_iv_init (&stmts, init_expr,
    2609              :                                           niters, step_expr,
    2610              :                                           induction_type, early_exit_p);
    2611              : 
    2612        56309 :       var = create_tmp_var (type, "tmp");
    2613              : 
    2614        56309 :       gimple_seq new_stmts = NULL;
    2615        56309 :       ni_name = force_gimple_operand (ni, &new_stmts, false, var);
    2616              : 
    2617              :       /* Exit_bb shouldn't be empty, but we also can't insert after a ctrl
    2618              :          statements.  */
    2619        56309 :       if (!gsi_end_p (last_gsi) && !is_ctrl_stmt (gsi_stmt (last_gsi)))
    2620              :         {
    2621          319 :           gsi_insert_seq_after (&last_gsi, stmts, GSI_SAME_STMT);
    2622          319 :           gsi_insert_seq_after (&last_gsi, new_stmts, GSI_SAME_STMT);
    2623              :         }
    2624              :       else
    2625              :         {
    2626        55990 :           gsi_insert_seq_before (&last_gsi, stmts, GSI_SAME_STMT);
    2627        55990 :           gsi_insert_seq_before (&last_gsi, new_stmts, GSI_SAME_STMT);
    2628              :         }
    2629              : 
    2630              :       /* Update the PHI argument on the requested edge.  */
    2631        56309 :       adjust_phi_and_debug_stmts (phi1, update_e, ni_name);
    2632              :     }
    2633        36555 : }
    2634              : 
    2635              : /* Return a gimple value containing the misalignment (measured in vector
    2636              :    elements) for the loop described by LOOP_VINFO, i.e. how many elements
    2637              :    it is away from a perfectly aligned address.  Add any new statements
    2638              :    to SEQ.  */
    2639              : 
    2640              : static tree
    2641          223 : get_misalign_in_elems (gimple **seq, loop_vec_info loop_vinfo)
    2642              : {
    2643          223 :   dr_vec_info *dr_info = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
    2644          223 :   stmt_vec_info stmt_info = dr_info->stmt;
    2645          223 :   tree vectype = STMT_VINFO_VECTYPE (stmt_info);
    2646              : 
    2647          223 :   poly_uint64 target_align = DR_TARGET_ALIGNMENT (dr_info);
    2648          223 :   unsigned HOST_WIDE_INT target_align_c;
    2649          223 :   tree target_align_minus_1;
    2650              : 
    2651          223 :   bool negative = tree_int_cst_compare (DR_STEP (dr_info->dr),
    2652          223 :                                         size_zero_node) < 0;
    2653          223 :   tree offset
    2654          223 :     = size_int (vect_get_misalign_offset (negative, vectype, stmt_info,
    2655              :                                           loop_vinfo));
    2656          223 :   tree start_addr = vect_create_addr_base_for_vector_ref (loop_vinfo,
    2657              :                                                           stmt_info, seq,
    2658              :                                                           offset);
    2659          223 :   tree type = unsigned_type_for (TREE_TYPE (start_addr));
    2660          223 :   if (target_align.is_constant (&target_align_c))
    2661          223 :     target_align_minus_1 = build_int_cst (type, target_align_c - 1);
    2662              :   else
    2663              :     {
    2664              :       tree vla = build_int_cst (type, target_align);
    2665              :       target_align_minus_1 = fold_build2 (MINUS_EXPR, type, vla,
    2666              :                                           build_int_cst (type, 1));
    2667              :     }
    2668              : 
    2669          223 :   auto elem_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
    2670          446 :   tree elem_size_log = build_int_cst (type, exact_log2 (elem_size));
    2671              : 
    2672              :   /* Create:  misalign_in_bytes = addr & (target_align - 1).  */
    2673          223 :   tree int_start_addr = fold_convert (type, start_addr);
    2674          223 :   tree misalign_in_bytes = fold_build2 (BIT_AND_EXPR, type, int_start_addr,
    2675              :                                         target_align_minus_1);
    2676              : 
    2677              :   /* Create:  misalign_in_elems = misalign_in_bytes / element_size.  */
    2678          223 :   tree misalign_in_elems = fold_build2 (RSHIFT_EXPR, type, misalign_in_bytes,
    2679              :                                         elem_size_log);
    2680              : 
    2681          223 :   return misalign_in_elems;
    2682              : }
    2683              : 
    2684              : /* Function vect_gen_prolog_loop_niters
    2685              : 
    2686              :    Generate the number of iterations which should be peeled as prolog for the
    2687              :    loop represented by LOOP_VINFO.  It is calculated as the misalignment of
    2688              :    DR - the data reference recorded in LOOP_VINFO_UNALIGNED_DR (LOOP_VINFO).
    2689              :    As a result, after the execution of this loop, the data reference DR will
    2690              :    refer to an aligned location.  The following computation is generated:
    2691              : 
    2692              :    If the misalignment of DR is known at compile time:
    2693              :      addr_mis = int mis = DR_MISALIGNMENT (dr);
    2694              :    Else, compute address misalignment in bytes:
    2695              :      addr_mis = addr & (target_align - 1)
    2696              : 
    2697              :    prolog_niters = ((VF - addr_mis/elem_size)&(VF-1))/step
    2698              : 
    2699              :    (elem_size = element type size; an element is the scalar element whose type
    2700              :    is the inner type of the vectype)
    2701              : 
    2702              :    The computations will be emitted at the end of BB.  We also compute and
    2703              :    store upper bound (included) of the result in BOUND.
    2704              : 
    2705              :    When the step of the data-ref in the loop is not 1 (as in interleaved data
    2706              :    and SLP), the number of iterations of the prolog must be divided by the step
    2707              :    (which is equal to the size of interleaved group).
    2708              : 
    2709              :    The above formulas assume that VF == number of elements in the vector. This
    2710              :    may not hold when there are multiple-types in the loop.
    2711              :    In this case, for some data-references in the loop the VF does not represent
    2712              :    the number of elements that fit in the vector.  Therefore, instead of VF we
    2713              :    use TYPE_VECTOR_SUBPARTS.  */
    2714              : 
    2715              : static tree
    2716          468 : vect_gen_prolog_loop_niters (loop_vec_info loop_vinfo,
    2717              :                              basic_block bb, poly_int64 *bound)
    2718              : {
    2719          468 :   dr_vec_info *dr_info = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
    2720          468 :   tree var;
    2721          468 :   tree niters_type
    2722          468 :     = LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo) ? sizetype
    2723          468 :                                                  : TREE_TYPE (LOOP_VINFO_NITERS
    2724              :                                                               (loop_vinfo));
    2725          468 :   gimple_seq stmts = NULL, new_stmts = NULL;
    2726          468 :   tree iters, iters_name;
    2727          468 :   stmt_vec_info stmt_info = dr_info->stmt;
    2728          468 :   tree vectype = STMT_VINFO_VECTYPE (stmt_info);
    2729          468 :   poly_uint64 target_align = DR_TARGET_ALIGNMENT (dr_info);
    2730              : 
    2731          468 :   if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
    2732              :     {
    2733          245 :       int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    2734              : 
    2735          245 :       if (dump_enabled_p ())
    2736          234 :         dump_printf_loc (MSG_NOTE, vect_location,
    2737              :                          "known peeling = %d.\n", npeel);
    2738              : 
    2739          245 :       iters = build_int_cst (niters_type, npeel);
    2740          245 :       *bound = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    2741              :     }
    2742              :   else
    2743              :     {
    2744          223 :       tree misalign_in_elems = get_misalign_in_elems (&stmts, loop_vinfo);
    2745          223 :       tree type = TREE_TYPE (misalign_in_elems);
    2746          223 :       auto elem_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
    2747              :       /* We only do prolog peeling if the target alignment is known at compile
    2748              :          time.  */
    2749          223 :       poly_uint64 align_in_elems =
    2750          223 :         exact_div (target_align, elem_size);
    2751          223 :       tree align_in_elems_minus_1 =
    2752          223 :         build_int_cst (type, align_in_elems - 1);
    2753          223 :       tree align_in_elems_tree = build_int_cst (type, align_in_elems);
    2754              : 
    2755              :       /* Create:  (niters_type) ((align_in_elems - misalign_in_elems)
    2756              :                                  & (align_in_elems - 1)).  */
    2757          223 :       bool negative = tree_int_cst_compare (DR_STEP (dr_info->dr),
    2758          223 :                                             size_zero_node) < 0;
    2759          223 :       if (negative)
    2760            9 :         iters = fold_build2 (MINUS_EXPR, type, misalign_in_elems,
    2761              :                              align_in_elems_tree);
    2762              :       else
    2763          214 :         iters = fold_build2 (MINUS_EXPR, type, align_in_elems_tree,
    2764              :                              misalign_in_elems);
    2765          223 :       iters = fold_build2 (BIT_AND_EXPR, type, iters, align_in_elems_minus_1);
    2766          223 :       iters = fold_convert (niters_type, iters);
    2767          223 :       *bound = align_in_elems;
    2768              :     }
    2769              : 
    2770              :   /* Alignment peeling cannot consume more scalar iterations than the loop
    2771              :      actually has.  If the requested peel count is larger than the scalar
    2772              :      iteration count, limit the peeled iterations to niters.  Otherwise we would
    2773              :      model the prologue as executing iterations that the original loop would
    2774              :      never execute.  */
    2775          468 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2776            0 :       && !LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    2777              :     {
    2778            0 :       tree niters = LOOP_VINFO_NITERS (loop_vinfo);
    2779            0 :       if (!types_compatible_p (niters_type, TREE_TYPE (niters)))
    2780            0 :        niters = fold_convert (niters_type, niters);
    2781            0 :       iters = fold_build2 (MIN_EXPR, niters_type, iters, niters);
    2782              :     }
    2783              : 
    2784          468 :   if (dump_enabled_p ())
    2785          314 :     dump_printf_loc (MSG_NOTE, vect_location,
    2786              :                      "niters for prolog loop: %T\n", iters);
    2787              : 
    2788          468 :   var = create_tmp_var (niters_type, "prolog_loop_niters");
    2789          468 :   iters_name = force_gimple_operand (iters, &new_stmts, false, var);
    2790              : 
    2791          468 :   if (new_stmts)
    2792          223 :     gimple_seq_add_seq (&stmts, new_stmts);
    2793          468 :   if (stmts)
    2794              :     {
    2795          223 :       gcc_assert (single_succ_p (bb));
    2796          223 :       gimple_stmt_iterator gsi = gsi_last_bb (bb);
    2797          223 :       if (gsi_end_p (gsi))
    2798           57 :         gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
    2799              :       else
    2800          166 :         gsi_insert_seq_after (&gsi, stmts, GSI_SAME_STMT);
    2801              :     }
    2802          468 :   return iters_name;
    2803              : }
    2804              : 
    2805              : 
    2806              : /* Function vect_update_init_of_dr
    2807              : 
    2808              :    If CODE is PLUS, the vector loop starts NITERS iterations after the
    2809              :    scalar one, otherwise CODE is MINUS and the vector loop starts NITERS
    2810              :    iterations before the scalar one (using masking to skip inactive
    2811              :    elements).  This function updates the information recorded in DR to
    2812              :    account for the difference.  Specifically, it updates the OFFSET
    2813              :    field of DR_INFO.  */
    2814              : 
    2815              : static void
    2816        26123 : vect_update_init_of_dr (dr_vec_info *dr_info, tree niters, tree_code code)
    2817              : {
    2818        26123 :   struct data_reference *dr = dr_info->dr;
    2819        26123 :   tree offset = dr_info->offset;
    2820        26123 :   if (!offset)
    2821        26123 :     offset = build_zero_cst (sizetype);
    2822              : 
    2823        26123 :   niters = fold_build2 (MULT_EXPR, sizetype,
    2824              :                         fold_convert (sizetype, niters),
    2825              :                         fold_convert (sizetype, DR_STEP (dr)));
    2826        26123 :   offset = fold_build2 (code, sizetype,
    2827              :                         fold_convert (sizetype, offset), niters);
    2828        26123 :   dr_info->offset = offset;
    2829        26123 : }
    2830              : 
    2831              : 
    2832              : /* Function vect_update_inits_of_drs
    2833              : 
    2834              :    Apply vect_update_inits_of_dr to all accesses in LOOP_VINFO.
    2835              :    CODE and NITERS are as for vect_update_inits_of_dr.  */
    2836              : 
    2837              : void
    2838         7847 : vect_update_inits_of_drs (loop_vec_info loop_vinfo, tree niters,
    2839              :                           tree_code code)
    2840              : {
    2841         7847 :   unsigned int i;
    2842         7847 :   vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
    2843         7847 :   struct data_reference *dr;
    2844              : 
    2845         7847 :   DUMP_VECT_SCOPE ("vect_update_inits_of_dr");
    2846              : 
    2847              :   /* Adjust niters to sizetype.  We used to insert the stmts on loop preheader
    2848              :      here, but since we might use these niters to update the epilogues niters
    2849              :      and data references we can't insert them here as this definition might not
    2850              :      always dominate its uses.  */
    2851         7847 :   if (!types_compatible_p (sizetype, TREE_TYPE (niters)))
    2852         5128 :     niters = fold_convert (sizetype, niters);
    2853              : 
    2854        42196 :   FOR_EACH_VEC_ELT (datarefs, i, dr)
    2855              :     {
    2856        26617 :       dr_vec_info *dr_info = loop_vinfo->lookup_dr (dr);
    2857        26617 :       if (!STMT_VINFO_GATHER_SCATTER_P (dr_info->stmt)
    2858        26123 :           && !STMT_VINFO_SIMD_LANE_ACCESS_P (dr_info->stmt))
    2859        26123 :         vect_update_init_of_dr (dr_info, niters, code);
    2860              :     }
    2861         7847 : }
    2862              : 
    2863              : /* For the information recorded in LOOP_VINFO prepare the loop for peeling
    2864              :    by masking.  This involves calculating the number of iterations to
    2865              :    be peeled and then aligning all memory references appropriately.  */
    2866              : 
    2867              : void
    2868            2 : vect_prepare_for_masked_peels (loop_vec_info loop_vinfo)
    2869              : {
    2870            2 :   tree misalign_in_elems;
    2871            2 :   tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
    2872              : 
    2873            2 :   gcc_assert (vect_use_loop_mask_for_alignment_p (loop_vinfo));
    2874              : 
    2875              :   /* From the information recorded in LOOP_VINFO get the number of iterations
    2876              :      that need to be skipped via masking.  */
    2877            2 :   if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
    2878              :     {
    2879            2 :       poly_int64 misalign = (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
    2880            2 :                              - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo));
    2881            2 :       misalign_in_elems = build_int_cst (type, misalign);
    2882              :     }
    2883              :   else
    2884              :     {
    2885            0 :       gimple_seq seq1 = NULL, seq2 = NULL;
    2886            0 :       misalign_in_elems = get_misalign_in_elems (&seq1, loop_vinfo);
    2887            0 :       misalign_in_elems = fold_convert (type, misalign_in_elems);
    2888            0 :       misalign_in_elems = force_gimple_operand (misalign_in_elems,
    2889              :                                                 &seq2, true, NULL_TREE);
    2890            0 :       gimple_seq_add_seq (&seq1, seq2);
    2891            0 :       if (seq1)
    2892              :         {
    2893            0 :           edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
    2894            0 :           basic_block new_bb = gsi_insert_seq_on_edge_immediate (pe, seq1);
    2895            0 :           gcc_assert (!new_bb);
    2896              :         }
    2897              :     }
    2898              : 
    2899            2 :   if (dump_enabled_p ())
    2900            1 :     dump_printf_loc (MSG_NOTE, vect_location,
    2901              :                      "misalignment for fully-masked loop: %T\n",
    2902              :                      misalign_in_elems);
    2903              : 
    2904            2 :   LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo) = misalign_in_elems;
    2905              : 
    2906            2 :   vect_update_inits_of_drs (loop_vinfo, misalign_in_elems, MINUS_EXPR);
    2907            2 : }
    2908              : 
    2909              : /* This function builds ni_name = number of iterations.  Statements
    2910              :    are emitted on the loop preheader edge.  If NEW_VAR_P is not NULL, set
    2911              :    it to TRUE if new ssa_var is generated.  */
    2912              : 
    2913              : tree
    2914        66982 : vect_build_loop_niters (loop_vec_info loop_vinfo, bool *new_var_p)
    2915              : {
    2916        66982 :   if (LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    2917              :     return NULL_TREE;
    2918        66885 :   tree ni = unshare_expr (LOOP_VINFO_NITERS (loop_vinfo));
    2919        66885 :   if (TREE_CODE (ni) == INTEGER_CST)
    2920              :     return ni;
    2921              :   else
    2922              :     {
    2923        27897 :       tree ni_name, var;
    2924        27897 :       gimple_seq stmts = NULL;
    2925        27897 :       edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
    2926              : 
    2927        27897 :       var = create_tmp_var (TREE_TYPE (ni), "niters");
    2928        27897 :       ni_name = force_gimple_operand (ni, &stmts, false, var);
    2929        27897 :       if (stmts)
    2930              :         {
    2931        26781 :           gsi_insert_seq_on_edge_immediate (pe, stmts);
    2932        26781 :           if (new_var_p != NULL)
    2933          241 :             *new_var_p = true;
    2934              :         }
    2935              : 
    2936        27897 :       return ni_name;
    2937              :     }
    2938              : }
    2939              : 
    2940              : /* Calculate the number of iterations above which vectorized loop will be
    2941              :    preferred than scalar loop.  NITERS_PROLOG is the number of iterations
    2942              :    of prolog loop.  If it's integer const, the integer number is also passed
    2943              :    in INT_NITERS_PROLOG.  BOUND_PROLOG is the upper bound (inclusive) of the
    2944              :    number of iterations of the prolog loop.  BOUND_EPILOG is the corresponding
    2945              :    value for the epilog loop.  If CHECK_PROFITABILITY is true, TH is the
    2946              :    threshold below which the scalar (rather than vectorized) loop will be
    2947              :    executed.  This function stores the upper bound (inclusive) of the result
    2948              :    in BOUND_SCALAR.  */
    2949              : 
    2950              : static tree
    2951        26795 : vect_gen_scalar_loop_niters (tree niters_prolog, int int_niters_prolog,
    2952              :                              poly_int64 bound_prolog, poly_int64 bound_epilog,
    2953              :                              int th, poly_uint64 *bound_scalar,
    2954              :                              bool check_profitability)
    2955              : {
    2956        26795 :   tree type = TREE_TYPE (niters_prolog);
    2957        26795 :   tree niters = fold_build2 (PLUS_EXPR, type, niters_prolog,
    2958              :                              build_int_cst (type, bound_epilog));
    2959              : 
    2960        26795 :   *bound_scalar = bound_prolog + bound_epilog;
    2961        26795 :   if (check_profitability)
    2962              :     {
    2963              :       /* TH indicates the minimum niters of vectorized loop, while we
    2964              :          compute the maximum niters of scalar loop.  */
    2965        16490 :       th--;
    2966              :       /* Peeling for constant times.  */
    2967        16490 :       if (int_niters_prolog >= 0)
    2968              :         {
    2969        16451 :           *bound_scalar = upper_bound (int_niters_prolog + bound_epilog, th);
    2970        16451 :           return build_int_cst (type, *bound_scalar);
    2971              :         }
    2972              :       /* Peeling an unknown number of times.  Note that both BOUND_PROLOG
    2973              :          and BOUND_EPILOG are inclusive upper bounds.  */
    2974           39 :       if (known_ge (th, bound_prolog + bound_epilog))
    2975              :         {
    2976            0 :           *bound_scalar = th;
    2977            0 :           return build_int_cst (type, th);
    2978              :         }
    2979              :       /* Need to do runtime comparison.  */
    2980           39 :       else if (maybe_gt (th, bound_epilog))
    2981              :         {
    2982           39 :           *bound_scalar = upper_bound (*bound_scalar, th);
    2983           39 :           return fold_build2 (MAX_EXPR, type,
    2984              :                               build_int_cst (type, th), niters);
    2985              :         }
    2986              :     }
    2987              :   return niters;
    2988              : }
    2989              : 
    2990              : /* NITERS is the number of times that the original scalar loop executes
    2991              :    after peeling.  Work out the maximum number of iterations N that can
    2992              :    be handled by the vectorized form of the loop and then either:
    2993              : 
    2994              :    a) set *STEP_VECTOR_PTR to the vectorization factor and generate:
    2995              : 
    2996              :         niters_vector = N
    2997              : 
    2998              :    b) set *STEP_VECTOR_PTR to one and generate:
    2999              : 
    3000              :         niters_vector = N / vf
    3001              : 
    3002              :    In both cases, store niters_vector in *NITERS_VECTOR_PTR and add
    3003              :    any new statements on the loop preheader edge.  NITERS_NO_OVERFLOW
    3004              :    is true if NITERS doesn't overflow (i.e. if NITERS is always nonzero).
    3005              : 
    3006              :    Case (a) is used for LOOP_VINFO_USING_PARTIAL_VECTORS_P or if VF is
    3007              :    variable.  As stated above, NITERS_VECTOR then equals the number
    3008              :    of scalar iterations and vect_set_loop_condition will handle the
    3009              :    step.  As opposed to (b) we don't know anything about NITER_VECTOR's
    3010              :    range here.
    3011              : */
    3012              : 
    3013              : void
    3014        36665 : vect_gen_vector_loop_niters (loop_vec_info loop_vinfo, tree niters,
    3015              :                              tree *niters_vector_ptr, tree *step_vector_ptr,
    3016              :                              bool niters_no_overflow)
    3017              : {
    3018        36665 :   tree ni_minus_gap, var;
    3019        36665 :   tree niters_vector, step_vector;
    3020        36665 :   tree type = niters ? TREE_TYPE (niters) : sizetype;
    3021        36665 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    3022        36665 :   edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
    3023              : 
    3024              :   /* With a counting exit before the loop body, the final scalar iteration
    3025              :      only tests that exit.  Exclude it from both the vector trip count and
    3026              :      the masks, since the vector loop tests its bound after executing the
    3027              :      body.  */
    3028        36665 :   if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
    3029           64 :     niters = fold_build2 (MINUS_EXPR, type, niters, build_one_cst (type));
    3030              : 
    3031              :   /* If epilogue loop is required because of data accesses with gaps, we
    3032              :      subtract one iteration from the total number of iterations here for
    3033              :      correct calculation of RATIO.  */
    3034        36665 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
    3035              :     {
    3036          403 :       ni_minus_gap = fold_build2 (MINUS_EXPR, type, niters,
    3037              :                                   build_one_cst (type));
    3038          403 :       if (!is_gimple_val (ni_minus_gap))
    3039              :         {
    3040          190 :           var = create_tmp_var (type, "ni_gap");
    3041          190 :           gimple *stmts = NULL;
    3042          190 :           ni_minus_gap = force_gimple_operand (ni_minus_gap, &stmts,
    3043              :                                                true, var);
    3044          190 :           gsi_insert_seq_on_edge_immediate (pe, stmts);
    3045              :         }
    3046              :     }
    3047              :   else
    3048              :     ni_minus_gap = niters;
    3049              : 
    3050              :   /* To silence some unexpected warnings, simply initialize to 0. */
    3051        36665 :   unsigned HOST_WIDE_INT const_vf = 0;
    3052        36665 :   if (vf.is_constant (&const_vf)
    3053        36665 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    3054        36641 :       && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    3055              :     {
    3056              :       /* Create: niters / vf, which is equivalent to niters >> log2(vf) when
    3057              :                  vf is a power of two, and when not we approximate using a
    3058              :                  truncating division.  */
    3059              :       /* If it's known that niters == number of latch executions + 1 doesn't
    3060              :          overflow, we can generate niters / vf; otherwise we generate
    3061              :          (niters - vf) / vf + 1 by using the fact that we know ratio
    3062              :          will be at least one.  */
    3063        36641 :       tree var_vf = build_int_cst (type, const_vf);
    3064        36641 :       if (niters_no_overflow)
    3065        36429 :         niters_vector = fold_build2 (TRUNC_DIV_EXPR, type, ni_minus_gap,
    3066              :                                      var_vf);
    3067              :       else
    3068          212 :         niters_vector
    3069          212 :           = fold_build2 (PLUS_EXPR, type,
    3070              :                          fold_build2 (TRUNC_DIV_EXPR, type,
    3071              :                                       fold_build2 (MINUS_EXPR, type,
    3072              :                                                    ni_minus_gap,
    3073              :                                                    var_vf),
    3074              :                                       var_vf),
    3075              :                          build_int_cst (type, 1));
    3076        36641 :       step_vector = build_one_cst (type);
    3077              :     }
    3078              :   else
    3079              :     {
    3080           24 :       niters_vector = ni_minus_gap;
    3081           24 :       step_vector = build_int_cst (type, vf);
    3082              :     }
    3083              : 
    3084        36665 :   if (!is_gimple_val (niters_vector))
    3085              :     {
    3086        27648 :       var = create_tmp_var (type, "bnd");
    3087        27648 :       gimple_seq stmts = NULL;
    3088        27648 :       niters_vector = force_gimple_operand (niters_vector, &stmts, true, var);
    3089        27648 :       gsi_insert_seq_on_edge_immediate (pe, stmts);
    3090              :       /* Peeling algorithm guarantees that vector loop bound is at least ONE,
    3091              :          we set range information to make niters analyzer's life easier.
    3092              :          Note the number of latch iteration value can be TYPE_MAX_VALUE so
    3093              :          we have to represent the vector niter TYPE_MAX_VALUE + 1 / vf.  */
    3094        27648 :       if (stmts != NULL
    3095        27648 :           && integer_onep (step_vector))
    3096              :         {
    3097        27629 :           if (niters_no_overflow)
    3098              :             {
    3099        27435 :               int_range<1> vr (type,
    3100        54870 :                                wi::one (TYPE_PRECISION (type)),
    3101        54870 :                                wi::div_trunc (wi::max_value
    3102        27435 :                                               (TYPE_PRECISION (type),
    3103        27435 :                                                TYPE_SIGN (type)),
    3104              :                                               const_vf,
    3105        54870 :                                               TYPE_SIGN (type)));
    3106        27435 :               set_range_info (niters_vector, vr);
    3107        27435 :             }
    3108              :           /* For VF == 1 the vector IV might also overflow so we cannot
    3109              :              assert a minimum value of 1.  */
    3110          194 :           else if (const_vf > 1)
    3111              :             {
    3112          158 :               int_range<1> vr (type,
    3113          316 :                                wi::one (TYPE_PRECISION (type)),
    3114          474 :                                wi::rshift (wi::max_value (TYPE_PRECISION (type),
    3115          158 :                                                           TYPE_SIGN (type))
    3116          316 :                                            - (const_vf - 1),
    3117          316 :                                            exact_log2 (const_vf), TYPE_SIGN (type))
    3118          632 :                                + 1);
    3119          158 :               set_range_info (niters_vector, vr);
    3120          158 :             }
    3121              :         }
    3122              :     }
    3123        36665 :   *niters_vector_ptr = niters_vector;
    3124        36665 :   *step_vector_ptr = step_vector;
    3125              : 
    3126        36665 :   return;
    3127              : }
    3128              : 
    3129              : /* Finds the amount IV's should be incremented by each iteration.
    3130              :    Stored in LOOP_VINFO_IV_INCREMENT.  */
    3131              : 
    3132              : tree
    3133        66514 : vect_get_loop_iv_increment (loop_vec_info loop_vinfo)
    3134              : {
    3135        66514 :   if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    3136              :     {
    3137              :       /* For now, set this as varying.
    3138              :          Fill this in later when building the loop controls.  */
    3139            0 :       tree iv_increment = make_temp_ssa_name (sizetype, NULL, "iv_increment");
    3140              : 
    3141            0 :       gcall *varying_call = gimple_build_call_internal (IFN_VARYING, 0);
    3142            0 :       gimple_call_set_lhs (varying_call, iv_increment);
    3143              : 
    3144            0 :       gimple_stmt_iterator gsi = gsi_after_labels (loop_vinfo->loop->header);
    3145            0 :       gsi_insert_before (&gsi, varying_call, GSI_NEW_STMT);
    3146              : 
    3147            0 :       return iv_increment;
    3148              :     }
    3149              :   else
    3150        66514 :     return build_int_cst (sizetype, LOOP_VINFO_VECT_FACTOR (loop_vinfo));
    3151              : }
    3152              : 
    3153              : /* Given NITERS_VECTOR which is the number of iterations for vectorized
    3154              :    loop specified by LOOP_VINFO after vectorization, compute the number
    3155              :    of iterations before vectorization (niters_vector * vf) and store it
    3156              :    to NITERS_VECTOR_MULT_VF_PTR.  */
    3157              : 
    3158              : static void
    3159        35843 : vect_gen_vector_loop_niters_mult_vf (loop_vec_info loop_vinfo,
    3160              :                                      tree niters_vector,
    3161              :                                      tree *niters_vector_mult_vf_ptr)
    3162              : {
    3163              :   /* We should be using a step_vector of VF if VF is variable.  */
    3164        35843 :   int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo).to_constant ();
    3165        35843 :   tree type = TREE_TYPE (niters_vector);
    3166        35843 :   tree tree_vf = build_int_cst (type, vf);
    3167        35843 :   basic_block exit_bb = LOOP_VINFO_MAIN_EXIT (loop_vinfo)->dest;
    3168              : 
    3169        35843 :   gcc_assert (niters_vector_mult_vf_ptr != NULL);
    3170        35843 :   tree niters_vector_mult_vf = fold_build2 (MULT_EXPR, type,
    3171              :                                             niters_vector, tree_vf);
    3172              : 
    3173        35843 :   if (!is_gimple_val (niters_vector_mult_vf))
    3174              :     {
    3175        26851 :       tree var = create_tmp_var (type, "niters_vector_mult_vf");
    3176        26851 :       gimple_seq stmts = NULL;
    3177        26851 :       niters_vector_mult_vf = force_gimple_operand (niters_vector_mult_vf,
    3178              :                                                     &stmts, true, var);
    3179        26851 :       gimple_stmt_iterator gsi = gsi_start_bb (exit_bb);
    3180        26851 :       gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
    3181              :     }
    3182        35843 :   *niters_vector_mult_vf_ptr = niters_vector_mult_vf;
    3183        35843 : }
    3184              : 
    3185              : /* Function slpeel_add_loop_guard adds guard skipping from the beginning
    3186              :    of SKIP_LOOP to the beginning of UPDATE_LOOP.  GUARD_EDGE and MERGE_EDGE
    3187              :    are two pred edges of the merge point before UPDATE_LOOP.  The two loops
    3188              :    appear like below:
    3189              : 
    3190              :        guard_bb:
    3191              :          if (cond)
    3192              :            goto merge_bb;
    3193              :          else
    3194              :            goto skip_loop;
    3195              : 
    3196              :      skip_loop:
    3197              :        header_a:
    3198              :          i_1 = PHI<i_0, i_2>;
    3199              :          ...
    3200              :          i_2 = i_1 + 1;
    3201              :          if (cond_a)
    3202              :            goto latch_a;
    3203              :          else
    3204              :            goto exit_a;
    3205              :        latch_a:
    3206              :          goto header_a;
    3207              : 
    3208              :        exit_a:
    3209              :          i_5 = PHI<i_2>;
    3210              : 
    3211              :        merge_bb:
    3212              :          ;; PHI (i_x = PHI<i_0, i_5>) to be created at merge point.
    3213              : 
    3214              :      update_loop:
    3215              :        header_b:
    3216              :          i_3 = PHI<i_5, i_4>;  ;; Use of i_5 to be replaced with i_x.
    3217              :          ...
    3218              :          i_4 = i_3 + 1;
    3219              :          if (cond_b)
    3220              :            goto latch_b;
    3221              :          else
    3222              :            goto exit_bb;
    3223              :        latch_b:
    3224              :          goto header_b;
    3225              : 
    3226              :        exit_bb:
    3227              : 
    3228              :    This function creates PHI nodes at merge_bb and replaces the use of i_5
    3229              :    in the update_loop's PHI node with the result of new PHI result.  */
    3230              : 
    3231              : static void
    3232        27263 : slpeel_update_phi_nodes_for_guard1 (class loop *skip_loop,
    3233              :                                     class loop *update_loop,
    3234              :                                     edge guard_edge, edge merge_edge)
    3235              : {
    3236        27263 :   location_t merge_loc, guard_loc;
    3237        27263 :   edge orig_e = loop_preheader_edge (skip_loop);
    3238        27263 :   edge update_e = loop_preheader_edge (update_loop);
    3239        27263 :   gphi_iterator gsi_orig, gsi_update;
    3240              : 
    3241        27263 :   for ((gsi_orig = gsi_start_phis (skip_loop->header),
    3242        27263 :         gsi_update = gsi_start_phis (update_loop->header));
    3243        99382 :        !gsi_end_p (gsi_orig) && !gsi_end_p (gsi_update);
    3244        72119 :        gsi_next (&gsi_orig), gsi_next (&gsi_update))
    3245              :     {
    3246        72119 :       gphi *orig_phi = gsi_orig.phi ();
    3247        72119 :       gphi *update_phi = gsi_update.phi ();
    3248              : 
    3249              :       /* Generate new phi node at merge bb of the guard.  */
    3250        72119 :       tree new_res = copy_ssa_name (PHI_RESULT (orig_phi));
    3251        72119 :       gphi *new_phi = create_phi_node (new_res, guard_edge->dest);
    3252              : 
    3253              :       /* Merge bb has two incoming edges: GUARD_EDGE and MERGE_EDGE.  Set the
    3254              :          args in NEW_PHI for these edges.  */
    3255        72119 :       tree merge_arg = PHI_ARG_DEF_FROM_EDGE (update_phi, update_e);
    3256        72119 :       tree guard_arg = PHI_ARG_DEF_FROM_EDGE (orig_phi, orig_e);
    3257        72119 :       merge_loc = gimple_phi_arg_location_from_edge (update_phi, update_e);
    3258        72119 :       guard_loc = gimple_phi_arg_location_from_edge (orig_phi, orig_e);
    3259        72119 :       add_phi_arg (new_phi, merge_arg, merge_edge, merge_loc);
    3260        72119 :       add_phi_arg (new_phi, guard_arg, guard_edge, guard_loc);
    3261              : 
    3262              :       /* Update phi in UPDATE_PHI.  */
    3263        72119 :       adjust_phi_and_debug_stmts (update_phi, update_e, new_res);
    3264              :     }
    3265        27263 : }
    3266              : 
    3267              : /* LOOP_VINFO is an epilogue loop whose corresponding main loop can be skipped.
    3268              :    Return a value that equals:
    3269              : 
    3270              :    - MAIN_LOOP_VALUE when LOOP_VINFO is entered from the main loop and
    3271              :    - SKIP_VALUE when the main loop is skipped.  */
    3272              : 
    3273              : tree
    3274         3795 : vect_get_main_loop_result (loop_vec_info loop_vinfo, tree main_loop_value,
    3275              :                            tree skip_value)
    3276              : {
    3277         3795 :   gcc_assert (loop_vinfo->main_loop_edge);
    3278              : 
    3279         3795 :   tree phi_result = make_ssa_name (TREE_TYPE (main_loop_value));
    3280         3795 :   basic_block bb = loop_vinfo->main_loop_edge->dest;
    3281         3795 :   gphi *new_phi = create_phi_node (phi_result, bb);
    3282         3795 :   add_phi_arg (new_phi, main_loop_value, loop_vinfo->main_loop_edge,
    3283              :                UNKNOWN_LOCATION);
    3284         3795 :   add_phi_arg (new_phi, skip_value,
    3285              :                loop_vinfo->skip_main_loop_edge, UNKNOWN_LOCATION);
    3286         3795 :   return phi_result;
    3287              : }
    3288              : 
    3289              : /* Function vect_do_peeling.
    3290              : 
    3291              :    Input:
    3292              :    - LOOP_VINFO: Represent a loop to be vectorized, which looks like:
    3293              : 
    3294              :        preheader:
    3295              :      LOOP:
    3296              :        header_bb:
    3297              :          loop_body
    3298              :          if (exit_loop_cond) goto exit_bb
    3299              :          else                goto header_bb
    3300              :        exit_bb:
    3301              : 
    3302              :    - NITERS: The number of iterations of the loop.
    3303              :    - NITERSM1: The number of iterations of the loop's latch.
    3304              :    - NITERS_NO_OVERFLOW: No overflow in computing NITERS.
    3305              :    - TH, CHECK_PROFITABILITY: Threshold of niters to vectorize loop if
    3306              :                               CHECK_PROFITABILITY is true.
    3307              :    Output:
    3308              :    - *NITERS_VECTOR and *STEP_VECTOR describe how the main loop should
    3309              :      iterate after vectorization; see vect_set_loop_condition for details.
    3310              :    - *NITERS_VECTOR_MULT_VF_VAR is either null or an SSA name that
    3311              :      should be set to the number of scalar iterations handled by the
    3312              :      vector loop.  The SSA name is only used on exit from the loop.
    3313              : 
    3314              :    This function peels prolog and epilog from the loop, adds guards skipping
    3315              :    PROLOG and EPILOG for various conditions.  As a result, the changed CFG
    3316              :    would look like:
    3317              : 
    3318              :        guard_bb_1:
    3319              :          if (prefer_scalar_loop) goto merge_bb_1
    3320              :          else                    goto guard_bb_2
    3321              : 
    3322              :        guard_bb_2:
    3323              :          if (skip_prolog) goto merge_bb_2
    3324              :          else             goto prolog_preheader
    3325              : 
    3326              :        prolog_preheader:
    3327              :      PROLOG:
    3328              :        prolog_header_bb:
    3329              :          prolog_body
    3330              :          if (exit_prolog_cond) goto prolog_exit_bb
    3331              :          else                  goto prolog_header_bb
    3332              :        prolog_exit_bb:
    3333              : 
    3334              :        merge_bb_2:
    3335              : 
    3336              :        vector_preheader:
    3337              :      VECTOR LOOP:
    3338              :        vector_header_bb:
    3339              :          vector_body
    3340              :          if (exit_vector_cond) goto vector_exit_bb
    3341              :          else                  goto vector_header_bb
    3342              :        vector_exit_bb:
    3343              : 
    3344              :        guard_bb_3:
    3345              :          if (skip_epilog) goto merge_bb_3
    3346              :          else             goto epilog_preheader
    3347              : 
    3348              :        merge_bb_1:
    3349              : 
    3350              :        epilog_preheader:
    3351              :      EPILOG:
    3352              :        epilog_header_bb:
    3353              :          epilog_body
    3354              :          if (exit_epilog_cond) goto merge_bb_3
    3355              :          else                  goto epilog_header_bb
    3356              : 
    3357              :        merge_bb_3:
    3358              : 
    3359              :    Note this function peels prolog and epilog only if it's necessary,
    3360              :    as well as guards.
    3361              :    This function returns the epilogue loop if a decision was made to vectorize
    3362              :    it, otherwise NULL.
    3363              : 
    3364              :    The analysis resulting in this epilogue loop's loop_vec_info was performed
    3365              :    in the same vect_analyze_loop call as the main loop's.  At that time
    3366              :    vect_analyze_loop constructs a list of accepted loop_vec_info's for lower
    3367              :    vectorization factors than the main loop.  This list is chained in the
    3368              :    loop's loop_vec_info in the 'epilogue_vinfo' member.  When we decide to
    3369              :    vectorize the epilogue loop for a lower vectorization factor, the
    3370              :    loop_vec_info in epilogue_vinfo is updated and linked to the epilogue loop.
    3371              :    This is later used to vectorize the epilogue.
    3372              :    The reason the loop_vec_info needs updating is that it was
    3373              :    constructed based on the original main loop, and the epilogue loop is a
    3374              :    copy of this loop, so all links pointing to statements in the original loop
    3375              :    need updating.  Furthermore, these loop_vec_infos share the
    3376              :    data_reference's records, which will also need to be updated.
    3377              : 
    3378              :    TODO: Guard for prefer_scalar_loop should be emitted along with
    3379              :    versioning conditions if loop versioning is needed.  */
    3380              : 
    3381              : 
    3382              : class loop *
    3383        66514 : vect_do_peeling (loop_vec_info loop_vinfo, tree niters, tree nitersm1,
    3384              :                  tree *niters_vector, tree *step_vector,
    3385              :                  tree *niters_vector_mult_vf_var, int th,
    3386              :                  bool check_profitability, bool niters_no_overflow,
    3387              :                  tree *advance)
    3388              : {
    3389        66514 :   edge e, guard_e;
    3390        66514 :   tree type = niters ? TREE_TYPE (niters) : sizetype;
    3391        66514 :   tree guard_cond;
    3392        66514 :   basic_block guard_bb, guard_to;
    3393        66514 :   profile_probability prob_prolog, prob_vector, prob_epilog;
    3394        66514 :   int estimated_vf;
    3395        66514 :   int prolog_peeling = 0;
    3396        66514 :   bool vect_epilogues = loop_vinfo->epilogue_vinfo != NULL;
    3397        66514 :   bool uncounted_p = LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo);
    3398              : 
    3399        66514 :   if (!vect_use_loop_mask_for_alignment_p (loop_vinfo))
    3400        66512 :     prolog_peeling = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    3401              : 
    3402        66514 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    3403        66514 :   poly_uint64 bound_epilog = 0;
    3404        66514 :   if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    3405        66490 :       && LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
    3406        35530 :     bound_epilog += vf - 1;
    3407        66514 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
    3408          403 :     bound_epilog += 1;
    3409              : 
    3410              :   /* For early breaks the scalar loop needs to execute at most VF times
    3411              :      to find the element that caused the break.  */
    3412        66514 :   if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    3413        66514 :       && (LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo)
    3414          819 :           || LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo)))
    3415              :     bound_epilog = vf;
    3416              : 
    3417        66514 :   bool epilog_peeling = maybe_ne (bound_epilog, 0U);
    3418        66514 :   poly_uint64 bound_scalar = bound_epilog;
    3419              : 
    3420        66514 :   if (!LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo) && dump_enabled_p ())
    3421         8720 :     dump_printf_loc (MSG_NOTE, vect_location,
    3422              :                      "early break does not require epilog.\n");
    3423              : 
    3424        66514 :   if (!prolog_peeling && !epilog_peeling)
    3425              :     return NULL;
    3426              : 
    3427              :   /* Before doing any peeling make sure to reset debug binds outside of
    3428              :      the loop referring to defs not in LC SSA.  */
    3429        35939 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    3430        35939 :   reset_debug_uses_outside_loop (loop, LOOP_VINFO_BBS (loop_vinfo),
    3431              :                                  loop->num_nodes);
    3432              : 
    3433        35939 :   prob_vector = profile_probability::guessed_always ().apply_scale (9, 10);
    3434        35939 :   estimated_vf = vect_vf_for_cost (loop_vinfo);
    3435        35939 :   if (estimated_vf == 2)
    3436         7886 :     estimated_vf = 3;
    3437        35939 :   prob_prolog = prob_epilog = profile_probability::guessed_always ()
    3438        35939 :                         .apply_scale (estimated_vf - 1, estimated_vf);
    3439              : 
    3440        35939 :   class loop *prolog = NULL, *epilog = NULL;
    3441        35939 :   class loop *first_loop = loop;
    3442        35939 :   bool irred_flag = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
    3443              : 
    3444              :   /* SSA form needs to be up-to-date since we are going to manually
    3445              :      update SSA form in slpeel_tree_duplicate_loop_to_edge_cfg and delete all
    3446              :      update SSA state after that, so we have to make sure to not lose any
    3447              :      pending update needs.  */
    3448        35939 :   gcc_assert (!need_ssa_update_p (cfun));
    3449              : 
    3450              :   /* If we're vectorizing an epilogue loop, we have ensured that the
    3451              :      virtual operand is in SSA form throughout the vectorized main loop.
    3452              :      Normally it is possible to trace the updated
    3453              :      vector-stmt vdefs back to scalar-stmt vdefs and vector-stmt vuses
    3454              :      back to scalar-stmt vuses, meaning that the effect of the SSA update
    3455              :      remains local to the main loop.  However, there are rare cases in
    3456              :      which the vectorized loop should have vdefs even when the original scalar
    3457              :      loop didn't.  For example, vectorizing a load with IFN_LOAD_LANES
    3458              :      introduces clobbers of the temporary vector array, which in turn
    3459              :      needs new vdefs.  If the scalar loop doesn't write to memory, these
    3460              :      new vdefs will be the only ones in the vector loop.
    3461              :      We are currently deferring updating virtual SSA form and creating
    3462              :      of a virtual PHI for this case so we do not have to make sure the
    3463              :      newly introduced virtual def is in LCSSA form.  */
    3464              : 
    3465        35939 :   if (MAY_HAVE_DEBUG_BIND_STMTS)
    3466              :     {
    3467        12920 :       gcc_assert (!adjust_vec.exists ());
    3468        12920 :       adjust_vec.create (32);
    3469              :     }
    3470        35939 :   initialize_original_copy_tables ();
    3471              : 
    3472              :   /* Record the anchor bb at which the guard should be placed if the scalar
    3473              :      loop might be preferred.  */
    3474        35939 :   basic_block anchor = loop_preheader_edge (loop)->src;
    3475              : 
    3476              :   /* Generate the number of iterations for the prolog loop.  We do this here
    3477              :      so that we can also get the upper bound on the number of iterations.  */
    3478        35939 :   tree niters_prolog;
    3479        35939 :   poly_int64 bound_prolog = 0;
    3480        35939 :   if (prolog_peeling)
    3481              :     {
    3482          468 :       niters_prolog = vect_gen_prolog_loop_niters (loop_vinfo, anchor,
    3483              :                                                    &bound_prolog);
    3484              :       /* If algonment peeling is known, we will always execute prolog.  */
    3485          468 :       if (TREE_CODE (niters_prolog) == INTEGER_CST)
    3486          245 :         prob_prolog = profile_probability::always ();
    3487              :     }
    3488              :   else
    3489        35471 :     niters_prolog = build_int_cst (type, 0);
    3490              : 
    3491        35939 :   loop_vec_info epilogue_vinfo = loop_vinfo->epilogue_vinfo;
    3492        35939 :   tree niters_vector_mult_vf = NULL_TREE;
    3493              :   /* Saving NITERs before the loop, as this may be changed by prologue.  */
    3494        35939 :   tree before_loop_niters = LOOP_VINFO_NITERS (loop_vinfo);
    3495        35939 :   edge update_e = NULL, skip_e = NULL;
    3496        35939 :   unsigned int lowest_vf = constant_lower_bound (vf);
    3497              :   /* Prolog loop may be skipped.  */
    3498        35939 :   bool skip_prolog = (prolog_peeling != 0);
    3499              : 
    3500              :   /* A peeled early-break loop tests its counted exit once without running
    3501              :      the body, so full vectors need one more scalar iteration.  */
    3502        35939 :   auto min_niters = bound_prolog + bound_epilog;
    3503        71814 :   if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo)
    3504        35996 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    3505          121 :     min_niters += 1;
    3506              : 
    3507              :   /* Skip this loop to epilog when there are not enough iterations to enter this
    3508              :      vectorized loop.  If true we should perform runtime checks on the NITERS
    3509              :      to check whether we should skip the current vectorized loop.  If we know
    3510              :      the number of scalar iterations we may choose to add a runtime check if
    3511              :      this number "maybe" smaller than the number of iterations required
    3512              :      when we know the number of scalar iterations may potentially
    3513              :      be smaller than the number of iterations required to enter this loop, for
    3514              :      this we use the upper bounds on the prolog and epilog peeling.  When we
    3515              :      don't know the number of iterations and don't require versioning it is
    3516              :      because we have asserted that there are enough scalar iterations to enter
    3517              :      the main loop, so this skip is not necessary.  When we are versioning then
    3518              :      we only add such a skip if we have chosen to vectorize the epilogue.  */
    3519        35939 :   bool skip_vector = false;
    3520        35939 :   if (!uncounted_p)
    3521         9041 :     skip_vector = (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    3522        44923 :                    ? maybe_lt (LOOP_VINFO_INT_NITERS (loop_vinfo), min_niters)
    3523        26900 :                    : (!LOOP_VINFO_USE_VERSIONING_WITHOUT_PEELING (loop_vinfo)
    3524          108 :                       || vect_epilogues));
    3525              : 
    3526              :   /* Epilog loop must be executed if the number of iterations for epilog
    3527              :      loop is known at compile time, otherwise we need to add a check at
    3528              :      the end of vector loop and skip to the end of epilog loop.  */
    3529        35939 :   bool skip_epilog = (prolog_peeling < 0
    3530        35716 :                       || !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    3531        35939 :                       || !vf.is_constant ());
    3532              :   /* PEELING_FOR_GAPS and peeling for early breaks are special because epilog
    3533              :      loop must be executed.  */
    3534        35939 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    3535        35536 :       || LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3536         1324 :     skip_epilog = false;
    3537              : 
    3538        35939 :   class loop *scalar_loop = LOOP_VINFO_SCALAR_LOOP (loop_vinfo);
    3539        35939 :   auto_vec<profile_count> original_counts;
    3540        35939 :   basic_block *original_bbs = NULL;
    3541              : 
    3542        35939 :   if (skip_vector)
    3543              :     {
    3544        26795 :       split_edge (loop_preheader_edge (loop));
    3545              : 
    3546        26795 :       if (epilog_peeling && (vect_epilogues || scalar_loop == NULL))
    3547              :         {
    3548        25660 :           original_bbs = get_loop_body (loop);
    3549       103087 :           for (unsigned int i = 0; i < loop->num_nodes; i++)
    3550        51767 :             original_counts.safe_push(original_bbs[i]->count);
    3551              :         }
    3552              : 
    3553              :       /* Due to the order in which we peel prolog and epilog, we first
    3554              :          propagate probability to the whole loop.  The purpose is to
    3555              :          avoid adjusting probabilities of both prolog and vector loops
    3556              :          separately.  Note in this case, the probability of epilog loop
    3557              :          needs to be scaled back later.  */
    3558        26795 :       basic_block bb_before_loop = loop_preheader_edge (loop)->src;
    3559        26795 :       if (prob_vector.initialized_p ())
    3560              :         {
    3561        26795 :           scale_bbs_frequencies (&bb_before_loop, 1, prob_vector);
    3562        26795 :           scale_loop_profile (loop, prob_vector, -1);
    3563              :         }
    3564              :     }
    3565              : 
    3566        35939 :   if (vect_epilogues)
    3567              :     {
    3568              :       /* Make sure to set the epilogue's epilogue scalar loop, such that we can
    3569              :          use the original scalar loop as remaining epilogue if necessary.  */
    3570         7377 :       LOOP_VINFO_SCALAR_LOOP (epilogue_vinfo)
    3571         7377 :         = LOOP_VINFO_SCALAR_LOOP (loop_vinfo);
    3572         7377 :       LOOP_VINFO_SCALAR_MAIN_EXIT (epilogue_vinfo)
    3573         7377 :         = LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo);
    3574              :     }
    3575              : 
    3576        35939 :   if (prolog_peeling)
    3577              :     {
    3578          468 :       e = loop_preheader_edge (loop);
    3579          468 :       edge exit_e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    3580          468 :       gcc_checking_assert (slpeel_can_duplicate_loop_p (loop, exit_e, e)
    3581              :                            && (!LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo)
    3582              :                                || uncounted_p));
    3583              : 
    3584              :       /* Peel prolog and put it on preheader edge of loop.  */
    3585          468 :       edge scalar_e = LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo);
    3586          468 :       edge prolog_e = NULL;
    3587          468 :       prolog = slpeel_tree_duplicate_loop_to_edge_cfg (loop, exit_e,
    3588              :                                                        scalar_loop, scalar_e,
    3589              :                                                        e, &prolog_e, true, NULL,
    3590              :                                                        uncounted_p, uncounted_p,
    3591              :                                                        false);
    3592              : 
    3593          468 :       gcc_assert (prolog);
    3594          468 :       prolog->force_vectorize = false;
    3595              :       /* Assumptions are only versioned for the main exit, others might
    3596              :          still be taken, so do not mislead later passes.  */
    3597          468 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3598          248 :         loop_constraint_clear (prolog, LOOP_C_FINITE);
    3599              : 
    3600          468 :       first_loop = prolog;
    3601          468 :       reset_original_copy_tables ();
    3602              : 
    3603              :       /* Update the number of iterations for prolog loop.  */
    3604          468 :       tree step_prolog = build_one_cst (TREE_TYPE (niters_prolog));
    3605          468 :       vect_set_loop_condition (prolog, prolog_e, NULL, niters_prolog,
    3606              :                                step_prolog, NULL_TREE, false);
    3607              : 
    3608              :       /* Skip the prolog loop.  */
    3609          468 :       if (skip_prolog)
    3610              :         {
    3611          468 :           guard_cond = fold_build2 (EQ_EXPR, boolean_type_node,
    3612              :                                     niters_prolog, build_int_cst (type, 0));
    3613          468 :           guard_bb = loop_preheader_edge (prolog)->src;
    3614          468 :           basic_block bb_after_prolog = loop_preheader_edge (loop)->src;
    3615          468 :           guard_to = split_edge (loop_preheader_edge (loop));
    3616          468 :           guard_e = slpeel_add_loop_guard (guard_bb, guard_cond,
    3617              :                                            guard_to, guard_bb,
    3618              :                                            prob_prolog.invert (),
    3619              :                                            irred_flag);
    3620         2144 :           for (edge alt_e : get_loop_exit_edges (prolog))
    3621              :             {
    3622          740 :               if (alt_e == prolog_e)
    3623          468 :                 continue;
    3624          272 :               basic_block old_dom
    3625          272 :                 = get_immediate_dominator (CDI_DOMINATORS, alt_e->dest);
    3626          272 :               if (flow_bb_inside_loop_p (prolog, old_dom))
    3627              :                 {
    3628          113 :                   auto_vec<basic_block, 8> queue;
    3629          113 :                   for (auto son = first_dom_son (CDI_DOMINATORS, old_dom);
    3630          363 :                        son; son = next_dom_son (CDI_DOMINATORS, son))
    3631          250 :                     if (!flow_bb_inside_loop_p (prolog, son))
    3632          137 :                       queue.safe_push (son);
    3633          476 :                   for (auto son : queue)
    3634          137 :                     set_immediate_dominator (CDI_DOMINATORS, son, guard_bb);
    3635          113 :                 }
    3636          468 :             }
    3637              : 
    3638          468 :           e = EDGE_PRED (guard_to, 0);
    3639          468 :           e = (e != guard_e ? e : EDGE_PRED (guard_to, 1));
    3640          468 :           slpeel_update_phi_nodes_for_guard1 (prolog, loop, guard_e, e);
    3641              : 
    3642          468 :           scale_bbs_frequencies (&bb_after_prolog, 1, prob_prolog);
    3643          468 :           scale_loop_profile (prolog, prob_prolog,
    3644          468 :                               estimated_poly_value (bound_prolog) - 1);
    3645              :         }
    3646              : 
    3647              :       /* Update init address of DRs.  */
    3648          468 :       vect_update_inits_of_drs (loop_vinfo, niters_prolog, PLUS_EXPR);
    3649          468 :       if (!uncounted_p)
    3650              :         {
    3651              :           /* Update niters for vector loop.  */
    3652          428 :           LOOP_VINFO_NITERS (loop_vinfo)
    3653          428 :             = fold_build2 (MINUS_EXPR, type, niters, niters_prolog);
    3654          428 :           LOOP_VINFO_NITERSM1 (loop_vinfo)
    3655          428 :             = fold_build2 (MINUS_EXPR, type,
    3656              :                            LOOP_VINFO_NITERSM1 (loop_vinfo), niters_prolog);
    3657              :         }
    3658          468 :       bool new_var_p = false;
    3659          468 :       niters = vect_build_loop_niters (loop_vinfo, &new_var_p);
    3660              :       /* Without partial vectors, it's guaranteed that vector loop bound
    3661              :          before vectorization is at least VF, so set range information for
    3662              :          newly generated var.  */
    3663          468 :       if (new_var_p
    3664          241 :           && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    3665              :         {
    3666          241 :           int_range<1> vr (type,
    3667          482 :                            wi::to_wide (build_int_cst (type, lowest_vf)),
    3668          482 :                            wi::to_wide (TYPE_MAX_VALUE (type)));
    3669          241 :           set_range_info (niters, vr);
    3670          241 :         }
    3671              : 
    3672              :       /* Prolog iterates at most bound_prolog times, latch iterates at
    3673              :          most bound_prolog - 1 times.  */
    3674          468 :       if (bound_prolog.is_constant ())
    3675          468 :         record_niter_bound (prolog, bound_prolog.to_constant () - 1, false,
    3676              :                             true);
    3677          468 :       delete_update_ssa ();
    3678          468 :       adjust_vec_debug_stmts ();
    3679          468 :       scev_reset ();
    3680              :     }
    3681        35939 :   basic_block bb_before_epilog = NULL;
    3682              : 
    3683        35939 :   if (epilog_peeling)
    3684              :     {
    3685        35900 :       e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    3686        35900 :       gcc_checking_assert (slpeel_can_duplicate_loop_p (loop, e, e));
    3687              : 
    3688              :       /* Peel epilog and put it on exit edge of loop.  If we are vectorizing
    3689              :          said epilog then we should use a copy of the main loop as a starting
    3690              :          point.  This loop may have already had some preliminary transformations
    3691              :          to allow for more optimal vectorization, for example if-conversion.
    3692              :          If we are not vectorizing the epilog then we should use the scalar loop
    3693              :          as the transformations mentioned above make less or no sense when not
    3694              :          vectorizing.  */
    3695        35900 :       edge scalar_e = LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo);
    3696        35900 :       epilog = vect_epilogues ? get_loop_copy (loop) : scalar_loop;
    3697         7377 :       edge epilog_e = vect_epilogues ? e : scalar_e;
    3698        35900 :       edge new_epilog_e = NULL;
    3699        35900 :       auto_vec<basic_block> doms;
    3700        35900 :       bool early_break_peel_p = LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo);
    3701        35900 :       epilog
    3702        35900 :         = slpeel_tree_duplicate_loop_to_edge_cfg (loop, e, epilog, epilog_e, e,
    3703              :                                                   &new_epilog_e, true, &doms,
    3704              :                                                   uncounted_p, false,
    3705              :                                                   early_break_peel_p);
    3706              : 
    3707        35900 :       LOOP_VINFO_EPILOGUE_MAIN_EXIT (loop_vinfo) = new_epilog_e;
    3708        35900 :       gcc_assert (epilog);
    3709        35900 :       gcc_assert (new_epilog_e);
    3710        35900 :       epilog->force_vectorize = false;
    3711              :       /* Assumptions are only versioned for the main exit, others might
    3712              :          still be taken, so do not mislead later passes.  */
    3713        35900 :       if (!vect_epilogues && LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3714          913 :         loop_constraint_clear (epilog, LOOP_C_FINITE);
    3715        35900 :       bb_before_epilog = loop_preheader_edge (epilog)->src;
    3716              : 
    3717              :       /* Scalar version loop may be preferred.  In this case, add guard
    3718              :          and skip to epilog.  Note this only happens when the number of
    3719              :          iterations of loop is unknown at compile time, otherwise this
    3720              :          won't be vectorized.  */
    3721        35900 :       if (skip_vector)
    3722              :         {
    3723              :           /* Additional epilogue iteration is peeled if gap exists.  */
    3724        53590 :           tree t = vect_gen_scalar_loop_niters (niters_prolog, prolog_peeling,
    3725        26795 :                                                 bound_prolog, bound_epilog,
    3726              :                                                 th, &bound_scalar,
    3727              :                                                 check_profitability);
    3728              :           /* Build guard against NITERSM1 since NITERS may overflow.  */
    3729        26795 :           guard_cond = fold_build2 (LT_EXPR, boolean_type_node, nitersm1, t);
    3730        26795 :           guard_bb = anchor;
    3731        26795 :           guard_to = split_edge (loop_preheader_edge (epilog));
    3732        26795 :           guard_e = slpeel_add_loop_guard (guard_bb, guard_cond,
    3733              :                                            guard_to, guard_bb,
    3734              :                                            prob_vector.invert (),
    3735              :                                            irred_flag);
    3736        26795 :           skip_e = guard_e;
    3737        26795 :           e = EDGE_PRED (guard_to, 0);
    3738        26795 :           e = (e != guard_e ? e : EDGE_PRED (guard_to, 1));
    3739              : 
    3740              :           /* Handle any remaining dominator updates needed after
    3741              :              inserting the loop skip edge above.  */
    3742        26795 :           if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    3743          298 :               && prolog_peeling)
    3744              :             {
    3745              :               /* Adding a skip edge to skip a loop with multiple exits
    3746              :                  means the dominator of the join blocks for all exits shifts
    3747              :                  from the prolog skip guard to the loop skip guard.  */
    3748          168 :               auto prolog_skip_bb
    3749          168 :                 = single_pred (loop_preheader_edge (prolog)->src);
    3750          168 :               auto needs_update
    3751          168 :                 = get_dominated_by (CDI_DOMINATORS, prolog_skip_bb);
    3752              : 
    3753              :               /* Update everything except for the immediate children of
    3754              :                  the prolog skip block (the prolog and vector preheaders).
    3755              :                  Those should remain dominated by the prolog skip block itself,
    3756              :                  since the loop guard edge goes to the epilogue.  */
    3757          900 :               for (auto bb : needs_update)
    3758          396 :                 if (bb != EDGE_SUCC (prolog_skip_bb, 0)->dest
    3759          396 :                     && bb != EDGE_SUCC (prolog_skip_bb, 1)->dest)
    3760           60 :                   set_immediate_dominator (CDI_DOMINATORS, bb, guard_bb);
    3761          168 :             }
    3762              : 
    3763        26795 :           slpeel_update_phi_nodes_for_guard1 (first_loop, epilog, guard_e, e);
    3764              : 
    3765              :           /* Simply propagate profile info from guard_bb to guard_to which is
    3766              :              a merge point of control flow.  */
    3767        26795 :           profile_count old_count = guard_to->count;
    3768        26795 :           guard_to->count = guard_bb->count;
    3769              : 
    3770              :           /* Restore the counts of the epilog loop if we didn't use the scalar loop. */
    3771        26795 :           if (vect_epilogues || scalar_loop == NULL)
    3772              :             {
    3773        25660 :               gcc_assert(epilog->num_nodes == loop->num_nodes);
    3774        25660 :               basic_block *bbs = get_loop_body (epilog);
    3775       103087 :               for (unsigned int i = 0; i < epilog->num_nodes; i++)
    3776              :                 {
    3777        51767 :                   gcc_assert(get_bb_original (bbs[i]) == original_bbs[i]);
    3778        51767 :                   bbs[i]->count = original_counts[i];
    3779              :                 }
    3780        25660 :               free (bbs);
    3781        25660 :               free (original_bbs);
    3782              :             }
    3783         1135 :           else if (old_count.nonzero_p ())
    3784         1135 :             scale_loop_profile (epilog, guard_to->count.probability_in (old_count), -1);
    3785              : 
    3786              :           /* Only need to handle basic block before epilog loop if it's not
    3787              :              the guard_bb, which is the case when skip_vector is true.  */
    3788        26795 :           if (guard_bb != bb_before_epilog && single_pred_p (bb_before_epilog))
    3789        26648 :             bb_before_epilog->count = single_pred_edge (bb_before_epilog)->count ();
    3790        26795 :           bb_before_epilog = loop_preheader_edge (epilog)->src;
    3791              :         }
    3792              : 
    3793        35900 :       if (!uncounted_p)
    3794              :         {
    3795              :           /* If loop is peeled for non-zero constant times, now niters refers to
    3796              :              orig_niters - prolog_peeling, it won't overflow even the
    3797              :              orig_niters overflows.  */
    3798        35843 :           niters_no_overflow |= (prolog_peeling > 0);
    3799        35843 :           vect_gen_vector_loop_niters (loop_vinfo, niters,
    3800              :                                        niters_vector, step_vector,
    3801              :                                        niters_no_overflow);
    3802        35843 :           if (!integer_onep (*step_vector))
    3803              :             {
    3804              :               /* On exit from the loop we will have an easy way of calculating
    3805              :                  NITERS_VECTOR / STEP * STEP.  Install a dummy definition
    3806              :                  until then.  */
    3807            0 :               niters_vector_mult_vf
    3808            0 :                 = make_ssa_name (TREE_TYPE (*niters_vector));
    3809            0 :               edge exit_e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    3810            0 :               gimple_stmt_iterator loop_cond_gsi
    3811            0 :                 = gsi_after_labels (exit_e->dest);
    3812              : 
    3813            0 :               gcall *tmp = gimple_build_call_internal (IFN_VARYING, 0);
    3814            0 :               gimple_call_set_lhs (tmp, niters_vector_mult_vf);
    3815            0 :               gsi_insert_before (&loop_cond_gsi, tmp, GSI_SAME_STMT);
    3816            0 :               *niters_vector_mult_vf_var = niters_vector_mult_vf;
    3817              :             }
    3818              :           else
    3819        35843 :             vect_gen_vector_loop_niters_mult_vf (loop_vinfo, *niters_vector,
    3820              :                                                  &niters_vector_mult_vf);
    3821              :           /* Update IVs of original loop as if they were advanced by
    3822              :              niters_vector_mult_vf steps.  */
    3823        35843 :           gcc_checking_assert (vect_can_advance_ivs_p (loop_vinfo));
    3824        35843 :           update_e = skip_vector ? e : loop_preheader_edge (epilog);
    3825              :         }
    3826        35900 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3827          913 :         update_e = single_succ_edge (LOOP_VINFO_MAIN_EXIT (loop_vinfo)->dest);
    3828              : 
    3829              :       /* If we have a peeled vector iteration we will never skip the epilog loop
    3830              :          and we can simplify the cfg a lot by not doing the edge split.  */
    3831        35900 :       if (skip_epilog
    3832        35900 :           || (LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    3833          913 :               && !LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo)))
    3834              :         {
    3835        27102 :           guard_cond = fold_build2 (EQ_EXPR, boolean_type_node,
    3836              :                                     niters, niters_vector_mult_vf);
    3837              : 
    3838        27102 :           guard_bb = LOOP_VINFO_MAIN_EXIT (loop_vinfo)->dest;
    3839        27102 :           edge epilog_e = LOOP_VINFO_EPILOGUE_MAIN_EXIT (loop_vinfo);
    3840        27102 :           guard_to = epilog_e->dest;
    3841        27617 :           guard_e = slpeel_add_loop_guard (guard_bb, guard_cond, guard_to,
    3842              :                                            skip_vector ? anchor : guard_bb,
    3843              :                                            prob_epilog.invert (),
    3844              :                                            irred_flag);
    3845              : 
    3846        27102 :           doms.safe_push (guard_to);
    3847        27102 :           if (vect_epilogues)
    3848         5987 :             epilogue_vinfo->skip_this_loop_edge = guard_e;
    3849        27102 :           edge main_iv = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    3850        27102 :           gphi_iterator gsi2 = gsi_start_phis (main_iv->dest);
    3851        27102 :           for (gphi_iterator gsi = gsi_start_phis (guard_to);
    3852        65735 :                !gsi_end_p (gsi); gsi_next (&gsi))
    3853              :             {
    3854              :               /* We are expecting all of the PHIs we have on epilog_e
    3855              :                  to be also on the main loop exit.  But sometimes
    3856              :                  a stray virtual definition can appear at epilog_e
    3857              :                  which we can then take as the same on all exits,
    3858              :                  we've removed the LC SSA PHI on the main exit before
    3859              :                  so we wouldn't need to create a loop PHI for it.  */
    3860        38633 :               if (virtual_operand_p (gimple_phi_result (*gsi))
    3861        38633 :                   && (gsi_end_p (gsi2)
    3862        40190 :                       || !virtual_operand_p (gimple_phi_result (*gsi2))))
    3863          178 :                 add_phi_arg (*gsi,
    3864           89 :                              gimple_phi_arg_def_from_edge (*gsi, epilog_e),
    3865              :                              guard_e, UNKNOWN_LOCATION);
    3866              :               else
    3867              :                 {
    3868        38544 :                   add_phi_arg (*gsi, gimple_phi_result (*gsi2), guard_e,
    3869              :                                UNKNOWN_LOCATION);
    3870        38544 :                   gsi_next (&gsi2);
    3871              :                 }
    3872              :             }
    3873              : 
    3874              :           /* Only need to handle basic block before epilog loop if it's not
    3875              :              the guard_bb, which is the case when skip_vector is true.  */
    3876        27102 :           if (guard_bb != bb_before_epilog)
    3877              :             {
    3878        27053 :               prob_epilog = prob_vector * prob_epilog + prob_vector.invert ();
    3879              : 
    3880        27053 :               scale_bbs_frequencies (&bb_before_epilog, 1, prob_epilog);
    3881              :             }
    3882        27102 :           scale_loop_profile (epilog, prob_epilog, -1);
    3883              :         }
    3884              : 
    3885              :       /* A counted main exit follows the completed vector iteration.
    3886              :          Uncounted loops must replay the exiting iteration to find the
    3887              :          scalar exit.  */
    3888        35900 :       tree vector_iters_vf = niters_vector_mult_vf;
    3889        35900 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3890              :         {
    3891          913 :           tree tmp_niters_vf
    3892          913 :             = make_ssa_name (LOOP_VINFO_EARLY_BRK_IV_TYPE (loop_vinfo));
    3893          913 :           gcall *tmp_call = gimple_build_call_internal (IFN_VARYING, 0);
    3894          913 :           gimple_call_set_lhs (tmp_call, tmp_niters_vf);
    3895          913 :           auto header_gsi = gsi_after_labels (loop->header);
    3896          913 :           gsi_insert_before (&header_gsi, tmp_call, GSI_SAME_STMT);
    3897              : 
    3898           57 :           if (!(LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo)
    3899         1027 :                 && get_loop_exit_edges (loop).length () == 1)
    3900          927 :               && LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo))
    3901              :             {
    3902          655 :               basic_block exit_bb = NULL;
    3903          655 :               edge update_e = NULL;
    3904              : 
    3905              :               /* Identify the early exit merge block.  I wish we had stored
    3906              :                  this.  */
    3907         1965 :               for (auto e : get_loop_exit_edges (loop))
    3908          655 :                 if (e != LOOP_VINFO_MAIN_EXIT (loop_vinfo))
    3909              :                   {
    3910          655 :                     exit_bb = e->dest;
    3911          655 :                     update_e = single_succ_edge (exit_bb);
    3912          655 :                     break;
    3913          655 :                   }
    3914          655 :               vect_update_ivs_after_vectorizer (loop_vinfo, tmp_niters_vf,
    3915              :                                                 update_e, true);
    3916              :             }
    3917          913 :           if (uncounted_p)
    3918           57 :             vector_iters_vf = tmp_niters_vf;
    3919              : 
    3920          913 :           LOOP_VINFO_EARLY_BRK_NITERS_VAR (loop_vinfo) = tmp_niters_vf;
    3921              :         }
    3922              : 
    3923        35900 :       vect_update_ivs_after_vectorizer (loop_vinfo, vector_iters_vf,
    3924              :                                         update_e, uncounted_p);
    3925              : 
    3926              :       /* Recalculate the dominators after adding the guard edge.  */
    3927        35900 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3928          913 :         iterate_fix_dominators (CDI_DOMINATORS, doms, false);
    3929              : 
    3930              :       /* When we do not have a loop-around edge to the epilog we know
    3931              :          the vector loop covered at least VF scalar iterations unless
    3932              :          we have early breaks.
    3933              :          Update any known upper bound with this knowledge.  */
    3934        35900 :       if (! skip_vector
    3935         9105 :           && ! LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    3936              :         {
    3937         8490 :           if (epilog->any_upper_bound)
    3938         8490 :             epilog->nb_iterations_upper_bound -= lowest_vf;
    3939         8490 :           if (epilog->any_likely_upper_bound)
    3940         8490 :             epilog->nb_iterations_likely_upper_bound -= lowest_vf;
    3941         8490 :           if (epilog->any_estimate)
    3942         8485 :             epilog->nb_iterations_estimate -= lowest_vf;
    3943              :         }
    3944              : 
    3945        35900 :       unsigned HOST_WIDE_INT bound;
    3946        35900 :       if (bound_scalar.is_constant (&bound))
    3947              :         {
    3948        35900 :           gcc_assert (bound != 0);
    3949              :           /* Adjust the upper bound by the extra peeled vector iteration if we
    3950              :              are an epilogue of an peeled vect loop and not VLA.  For VLA the
    3951              :              loop bounds are unknown.  */
    3952        71736 :           if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo)
    3953        35900 :               && vf.is_constant ())
    3954          121 :             bound += vf.to_constant ();
    3955              :           /* -1 to convert loop iterations to latch iterations.  */
    3956        35900 :           record_niter_bound (epilog, bound - 1, false, true);
    3957        35900 :           scale_loop_profile (epilog, profile_probability::always (),
    3958              :                               bound - 1);
    3959              :         }
    3960              : 
    3961        35900 :       delete_update_ssa ();
    3962        35900 :       adjust_vec_debug_stmts ();
    3963        35900 :       scev_reset ();
    3964        35900 :     }
    3965              : 
    3966        35939 :   if (vect_epilogues)
    3967              :     {
    3968         7377 :       epilog->aux = epilogue_vinfo;
    3969         7377 :       LOOP_VINFO_LOOP (epilogue_vinfo) = epilog;
    3970         7377 :       LOOP_VINFO_MAIN_EXIT (epilogue_vinfo)
    3971         7377 :         = LOOP_VINFO_EPILOGUE_MAIN_EXIT (loop_vinfo);
    3972              : 
    3973              :       /* We now must calculate the number of NITERS performed by the previous
    3974              :          loop and EPILOGUE_NITERS to be performed by the epilogue.  */
    3975         7377 :       tree niters = fold_build2 (PLUS_EXPR, TREE_TYPE (niters_vector_mult_vf),
    3976              :                                  niters_prolog, niters_vector_mult_vf);
    3977              : 
    3978              :       /* If skip_vector we may skip the previous loop, we insert a phi-node to
    3979              :          determine whether we are coming from the previous vectorized loop
    3980              :          using the update_e edge or the skip_vector basic block using the
    3981              :          skip_e edge.  */
    3982         7377 :       if (skip_vector)
    3983              :         {
    3984         6058 :           gcc_assert (update_e != NULL && skip_e != NULL);
    3985         6058 :           gphi *new_phi = create_phi_node (make_ssa_name (TREE_TYPE (niters)),
    3986              :                                            update_e->dest);
    3987         6058 :           tree new_ssa = make_ssa_name (TREE_TYPE (niters));
    3988         6058 :           gimple *stmt = gimple_build_assign (new_ssa, niters);
    3989         6058 :           gimple_stmt_iterator gsi;
    3990         6058 :           if (TREE_CODE (niters_vector_mult_vf) == SSA_NAME
    3991         6058 :               && SSA_NAME_DEF_STMT (niters_vector_mult_vf)->bb != NULL)
    3992              :             {
    3993         6058 :               gsi = gsi_for_stmt (SSA_NAME_DEF_STMT (niters_vector_mult_vf));
    3994         6058 :               gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
    3995              :             }
    3996              :           else
    3997              :             {
    3998            0 :               gsi = gsi_last_bb (update_e->src);
    3999            0 :               gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
    4000              :             }
    4001              : 
    4002         6058 :           niters = new_ssa;
    4003         6058 :           add_phi_arg (new_phi, niters, update_e, UNKNOWN_LOCATION);
    4004         6058 :           add_phi_arg (new_phi, build_zero_cst (TREE_TYPE (niters)), skip_e,
    4005              :                        UNKNOWN_LOCATION);
    4006         6058 :           niters = PHI_RESULT (new_phi);
    4007         6058 :           epilogue_vinfo->main_loop_edge = update_e;
    4008         6058 :           epilogue_vinfo->skip_main_loop_edge = skip_e;
    4009              :         }
    4010              : 
    4011              :       /* Set ADVANCE to the number of iterations performed by the previous
    4012              :          loop and its prologue.  */
    4013         7377 :       *advance = niters;
    4014              : 
    4015              :       /* Subtract the number of iterations performed by the vectorized loop
    4016              :          from the number of total iterations.  */
    4017         7377 :       tree epilogue_niters = fold_build2 (MINUS_EXPR, TREE_TYPE (niters),
    4018              :                                           before_loop_niters,
    4019              :                                           niters);
    4020              : 
    4021         7377 :       LOOP_VINFO_NITERS (epilogue_vinfo) = epilogue_niters;
    4022         7377 :       LOOP_VINFO_NITERSM1 (epilogue_vinfo)
    4023         7377 :         = fold_build2 (MINUS_EXPR, TREE_TYPE (epilogue_niters),
    4024              :                        epilogue_niters,
    4025              :                        build_one_cst (TREE_TYPE (epilogue_niters)));
    4026              :     }
    4027              : 
    4028        35939 :   adjust_vec.release ();
    4029        35939 :   free_original_copy_tables ();
    4030              : 
    4031        35939 :   return vect_epilogues ? epilog : NULL;
    4032        35939 : }
    4033              : 
    4034              : /* Set *COND_EXPR to a tree that is true when both the original *COND_EXPR
    4035              :    and PART_COND_EXPR are true.  Treat a null *COND_EXPR as "true".  */
    4036              : 
    4037              : static void
    4038          327 : chain_cond_expr (tree *cond_expr, tree part_cond_expr)
    4039              : {
    4040          327 :   if (*cond_expr)
    4041          320 :     *cond_expr = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
    4042              :                               *cond_expr, part_cond_expr);
    4043              :   else
    4044            7 :     *cond_expr = part_cond_expr;
    4045          327 : }
    4046              : 
    4047              : /* Function vect_create_cond_for_align_checks.
    4048              : 
    4049              :    Create a conditional expression that represents the alignment checks for
    4050              :    all of data references (array element references) whose alignment must be
    4051              :    checked at runtime.
    4052              : 
    4053              :    Input:
    4054              :    COND_EXPR  - input conditional expression.  New conditions will be chained
    4055              :                 with logical AND operation.
    4056              :    LOOP_VINFO - three fields of the loop information are used.
    4057              :                 LOOP_VINFO_PTR_MASK is the mask used to check the alignment.
    4058              :                 LOOP_VINFO_MAY_MISALIGN_STMTS contains the refs to be checked.
    4059              :                 LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT indicates which check applies.
    4060              : 
    4061              :    Output:
    4062              :    COND_EXPR_STMT_LIST - statements needed to construct the conditional
    4063              :                          expression.
    4064              :    The returned value is the conditional expression to be used in the if
    4065              :    statement that controls which version of the loop gets executed at runtime.
    4066              : 
    4067              :    Based on the boolean value of LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT, we decide
    4068              :    which type of check should be applied and create two different expressions
    4069              :    accordingly.
    4070              :      1) When LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT is false, we see if all data refs
    4071              :         to be checked are already aligned to an alignment boundary.  We create
    4072              :         an expression of "(a_1 | a_2 | a_3 | ... | a_n) & mask", where "a_i" is
    4073              :         the address of i'th data reference.
    4074              :      2) When LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT is true, we see if all data refs
    4075              :         can be aligned to a boundary after a certain amount of peeling, in other
    4076              :         words, their addresses have the same bottom bits according to the mask.
    4077              :         We create "((a_1 ^ a_2) | (a_2 ^ a_3) | ... | (a_n-1 ^ a_n)) & mask",
    4078              :         where "a_i" is the address of i'th data reference.
    4079              : 
    4080              :    Both algorithms make two assumptions:
    4081              :      1) The number of bytes "n" in a vector is a power of 2.
    4082              :      2) An address "a" is aligned if a%n is zero and that this
    4083              :         test can be done as a&(n-1) == 0.  For example, for 16
    4084              :         byte vectors the test is a&0xf == 0.  */
    4085              : 
    4086              : static void
    4087           82 : vect_create_cond_for_align_checks (loop_vec_info loop_vinfo,
    4088              :                                    tree *cond_expr,
    4089              :                                    gimple_seq *cond_expr_stmt_list)
    4090              : {
    4091           82 :   const vec<stmt_vec_info> &may_misalign_stmts
    4092              :     = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo);
    4093           82 :   stmt_vec_info stmt_info;
    4094           82 :   poly_uint64 mask = LOOP_VINFO_PTR_MASK (loop_vinfo);
    4095           82 :   tree mask_cst;
    4096           82 :   unsigned int i;
    4097           82 :   tree int_ptrsize_type;
    4098           82 :   char tmp_name[30];
    4099           82 :   tree or_tmp_name = NULL_TREE;
    4100           82 :   tree prev_addr_tmp_name = NULL_TREE;
    4101           82 :   tree and_tmp_name;
    4102           82 :   gimple *and_stmt;
    4103           82 :   tree ptrsize_zero;
    4104           82 :   tree part_cond_expr;
    4105              : 
    4106           82 :   gcc_assert (known_ne (mask, 0U));
    4107              : 
    4108           82 :   int_ptrsize_type = signed_type_for (ptr_type_node);
    4109              : 
    4110              :   /* If LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT is true, we should have at least two
    4111              :      datarefs to check the mutual alignment.  */
    4112           82 :   gcc_assert (may_misalign_stmts.length () > 1
    4113              :               || !LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT (loop_vinfo));
    4114              : 
    4115          311 :   FOR_EACH_VEC_ELT (may_misalign_stmts, i, stmt_info)
    4116              :     {
    4117          147 :       gimple_seq new_stmt_list = NULL;
    4118          147 :       tree addr_base;
    4119          147 :       tree addr_tmp_name;
    4120          147 :       tree xor_tmp_name;
    4121          147 :       tree new_or_tmp_name;
    4122          147 :       gimple *addr_stmt, *or_stmt, *xor_stmt;
    4123          147 :       tree vectype = STMT_VINFO_VECTYPE (stmt_info);
    4124          147 :       bool negative = tree_int_cst_compare
    4125          147 :         (DR_STEP (STMT_VINFO_DATA_REF (stmt_info)), size_zero_node) < 0;
    4126          147 :       tree offset
    4127          147 :         = size_int (vect_get_misalign_offset (negative, vectype, stmt_info,
    4128              :                                               loop_vinfo));
    4129              : 
    4130              :       /* create: addr_tmp = (int)(address_of_first_vector) */
    4131          147 :       addr_base =
    4132          147 :         vect_create_addr_base_for_vector_ref (loop_vinfo,
    4133              :                                               stmt_info, &new_stmt_list,
    4134              :                                               offset);
    4135          147 :       if (new_stmt_list != NULL)
    4136           67 :         gimple_seq_add_seq (cond_expr_stmt_list, new_stmt_list);
    4137              : 
    4138          147 :       sprintf (tmp_name, "addr2int%d", i);
    4139          147 :       addr_tmp_name = make_temp_ssa_name (int_ptrsize_type, NULL, tmp_name);
    4140          147 :       addr_stmt = gimple_build_assign (addr_tmp_name, NOP_EXPR, addr_base);
    4141          147 :       gimple_seq_add_stmt (cond_expr_stmt_list, addr_stmt);
    4142              : 
    4143          147 :       if (LOOP_VINFO_ALLOW_MUTUAL_ALIGNMENT (loop_vinfo))
    4144              :         {
    4145              :           /* Create "((a_1 ^ a_2) | (a_2 ^ a_3) | ... | (a_n-1 ^ a_n)) & mask"
    4146              :              to check mutual alignment.  */
    4147           36 :           if (prev_addr_tmp_name != NULL_TREE)
    4148              :             {
    4149           18 :               sprintf (tmp_name, "xorptrs%d_%d", i - 1, i);
    4150           18 :               xor_tmp_name = make_temp_ssa_name (int_ptrsize_type, NULL,
    4151              :                                                  tmp_name);
    4152           18 :               xor_stmt = gimple_build_assign (xor_tmp_name, BIT_XOR_EXPR,
    4153              :                                               prev_addr_tmp_name,
    4154              :                                               addr_tmp_name);
    4155           18 :               gimple_seq_add_stmt (cond_expr_stmt_list, xor_stmt);
    4156           18 :               if (or_tmp_name == NULL_TREE)
    4157              :                 {
    4158              :                   /* Create the 1st XOR when the 2nd data ref is seen.  */
    4159              :                   or_tmp_name = xor_tmp_name;
    4160              :                 }
    4161              :               else
    4162              :                 {
    4163              :                   /* Create: or_tmp = or_tmp | new_xor_tmp.  */
    4164            0 :                   sprintf (tmp_name, "orxors%d", i - 1);
    4165            0 :                   new_or_tmp_name = make_temp_ssa_name (int_ptrsize_type, NULL,
    4166              :                                                         tmp_name);
    4167            0 :                   or_stmt = gimple_build_assign (new_or_tmp_name, BIT_IOR_EXPR,
    4168              :                                                  or_tmp_name, xor_tmp_name);
    4169            0 :                   gimple_seq_add_stmt (cond_expr_stmt_list, or_stmt);
    4170            0 :                   or_tmp_name = new_or_tmp_name;
    4171              :                 }
    4172              :             }
    4173              :           prev_addr_tmp_name = addr_tmp_name;
    4174              :         }
    4175              :       else
    4176              :         {
    4177              :           /* Create: "(a_1 | a_2 | a_3 | ... | a_n) & mask" to check if all
    4178              :              addresses are already aligned.  */
    4179          111 :           if (or_tmp_name != NULL_TREE)
    4180              :             {
    4181              :               /* Create: or_tmp = or_tmp | addr_tmp.  */
    4182           47 :               sprintf (tmp_name, "orptrs%d", i);
    4183           47 :               new_or_tmp_name = make_temp_ssa_name (int_ptrsize_type, NULL,
    4184              :                                                     tmp_name);
    4185           47 :               or_stmt = gimple_build_assign (new_or_tmp_name, BIT_IOR_EXPR,
    4186              :                                              or_tmp_name, addr_tmp_name);
    4187           47 :               gimple_seq_add_stmt (cond_expr_stmt_list, or_stmt);
    4188           47 :               or_tmp_name = new_or_tmp_name;
    4189              :             }
    4190              :           else
    4191              :             or_tmp_name = addr_tmp_name;
    4192              :         }
    4193              : 
    4194              :     } /* end for i */
    4195              : 
    4196           82 :   mask_cst = build_int_cst (int_ptrsize_type, mask);
    4197              : 
    4198              :   /* create: and_tmp = or_tmp & mask  */
    4199           82 :   and_tmp_name = make_temp_ssa_name (int_ptrsize_type, NULL, "andmask");
    4200              : 
    4201           82 :   and_stmt = gimple_build_assign (and_tmp_name, BIT_AND_EXPR,
    4202              :                                   or_tmp_name, mask_cst);
    4203           82 :   gimple_seq_add_stmt (cond_expr_stmt_list, and_stmt);
    4204              : 
    4205              :   /* Make and_tmp the left operand of the conditional test against zero.
    4206              :      if and_tmp has a nonzero bit then some address is unaligned.  */
    4207           82 :   ptrsize_zero = build_int_cst (int_ptrsize_type, 0);
    4208           82 :   part_cond_expr = fold_build2 (EQ_EXPR, boolean_type_node,
    4209              :                                 and_tmp_name, ptrsize_zero);
    4210           82 :   chain_cond_expr (cond_expr, part_cond_expr);
    4211           82 : }
    4212              : 
    4213              : /* Function vect_create_cond_for_vla_spec_read.
    4214              : 
    4215              :    Create a conditional expression that represents the run-time checks with
    4216              :    max speculative read amount in VLA modes.  We check two things:
    4217              :      1) if the max speculative read amount exceeds the min page size
    4218              :      2) if the VF is power-of-2 - done by checking the max read amount instead
    4219              : 
    4220              :    Input:
    4221              :    COND_EXPR  - input conditional expression.  New conditions will be chained
    4222              :                 with logical AND operation.
    4223              :    LOOP_VINFO - field LOOP_VINFO_MAX_SPEC_READ_AMOUNT contains the max
    4224              :                 possible speculative read amount in VLA modes.
    4225              : 
    4226              :    Output:
    4227              :    COND_EXPR - conditional expression.
    4228              : 
    4229              :    The returned COND_EXPR is the conditional expression to be used in the
    4230              :    if statement that controls which version of the loop gets executed at
    4231              :    runtime.  */
    4232              : 
    4233              : static void
    4234            0 : vect_create_cond_for_vla_spec_read (loop_vec_info loop_vinfo, tree *cond_expr)
    4235              : {
    4236            0 :   poly_uint64 read_amount_poly = LOOP_VINFO_MAX_SPEC_READ_AMOUNT (loop_vinfo);
    4237            0 :   tree amount = build_int_cst (long_unsigned_type_node, read_amount_poly);
    4238              : 
    4239              :   /* Both the read amount and the VF must be variants, and the read amount must
    4240              :      be a constant power-of-2 multiple of the VF.  */
    4241            0 :   unsigned HOST_WIDE_INT multiple;
    4242            0 :   gcc_assert (!read_amount_poly.is_constant ()
    4243              :               && !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ()
    4244              :               && constant_multiple_p (read_amount_poly,
    4245              :                                       LOOP_VINFO_VECT_FACTOR (loop_vinfo),
    4246              :                                       &multiple)
    4247              :               && pow2p_hwi (multiple));
    4248              : 
    4249              :   tree cst_ul_zero = build_int_cstu (long_unsigned_type_node, 0U);
    4250              :   tree cst_ul_one = build_int_cstu (long_unsigned_type_node, 1U);
    4251              :   tree cst_ul_pagesize = build_int_cstu (long_unsigned_type_node,
    4252              :                                          (unsigned long) param_min_pagesize);
    4253              : 
    4254              :   /* Create an expression of "amount & (amount - 1) == 0".  */
    4255              :   tree amount_m1 = fold_build2 (MINUS_EXPR, long_unsigned_type_node,
    4256              :                                 amount, cst_ul_one);
    4257              :   tree amount_and_expr = fold_build2 (BIT_AND_EXPR, long_unsigned_type_node,
    4258              :                                       amount, amount_m1);
    4259              :   tree powof2_cond_expr = fold_build2 (EQ_EXPR, boolean_type_node,
    4260              :                                        amount_and_expr, cst_ul_zero);
    4261              :   chain_cond_expr (cond_expr, powof2_cond_expr);
    4262              : 
    4263              :   /* Create an expression of "amount <= cst_ul_pagesize".  */
    4264              :   tree pagesize_cond_expr = fold_build2 (LE_EXPR, boolean_type_node,
    4265              :                                          amount, cst_ul_pagesize);
    4266              :   chain_cond_expr (cond_expr, pagesize_cond_expr);
    4267              : }
    4268              : 
    4269              : /* If LOOP_VINFO_CHECK_UNEQUAL_ADDRS contains <A1, B1>, ..., <An, Bn>,
    4270              :    create a tree representation of: (&A1 != &B1) && ... && (&An != &Bn).
    4271              :    Set *COND_EXPR to a tree that is true when both the original *COND_EXPR
    4272              :    and this new condition are true.  Treat a null *COND_EXPR as "true".  */
    4273              : 
    4274              : static void
    4275         3401 : vect_create_cond_for_unequal_addrs (loop_vec_info loop_vinfo, tree *cond_expr)
    4276              : {
    4277         3401 :   const vec<vec_object_pair> &pairs
    4278              :     = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo);
    4279         3401 :   unsigned int i;
    4280         3401 :   vec_object_pair *pair;
    4281         3413 :   FOR_EACH_VEC_ELT (pairs, i, pair)
    4282              :     {
    4283           12 :       tree addr1 = build_fold_addr_expr (pair->first);
    4284           12 :       tree addr2 = build_fold_addr_expr (pair->second);
    4285           12 :       tree part_cond_expr = fold_build2 (NE_EXPR, boolean_type_node,
    4286              :                                          addr1, addr2);
    4287           12 :       chain_cond_expr (cond_expr, part_cond_expr);
    4288              :     }
    4289         3401 : }
    4290              : 
    4291              : /* Create an expression that is true when all lower-bound conditions for
    4292              :    the vectorized loop are met.  Chain this condition with *COND_EXPR.  */
    4293              : 
    4294              : static void
    4295         3401 : vect_create_cond_for_lower_bounds (loop_vec_info loop_vinfo, tree *cond_expr)
    4296              : {
    4297         3401 :   const vec<vec_lower_bound> &lower_bounds
    4298              :     = LOOP_VINFO_LOWER_BOUNDS (loop_vinfo);
    4299         3634 :   for (unsigned int i = 0; i < lower_bounds.length (); ++i)
    4300              :     {
    4301          233 :       tree expr = lower_bounds[i].expr;
    4302          233 :       tree type = unsigned_type_for (TREE_TYPE (expr));
    4303          233 :       expr = fold_convert (type, expr);
    4304          233 :       poly_uint64 bound = lower_bounds[i].min_value;
    4305          233 :       if (!lower_bounds[i].unsigned_p)
    4306              :         {
    4307           73 :           expr = fold_build2 (PLUS_EXPR, type, expr,
    4308              :                               build_int_cstu (type, bound - 1));
    4309           73 :           bound += bound - 1;
    4310              :         }
    4311          233 :       tree part_cond_expr = fold_build2 (GE_EXPR, boolean_type_node, expr,
    4312              :                                          build_int_cstu (type, bound));
    4313          233 :       chain_cond_expr (cond_expr, part_cond_expr);
    4314              :     }
    4315         3401 : }
    4316              : 
    4317              : /* Function vect_create_cond_for_alias_checks.
    4318              : 
    4319              :    Create a conditional expression that represents the run-time checks for
    4320              :    overlapping of address ranges represented by a list of data references
    4321              :    relations passed as input.
    4322              : 
    4323              :    Input:
    4324              :    COND_EXPR  - input conditional expression.  New conditions will be chained
    4325              :                 with logical AND operation.  If it is NULL, then the function
    4326              :                 is used to return the number of alias checks.
    4327              :    LOOP_VINFO - field LOOP_VINFO_MAY_ALIAS_STMTS contains the list of ddrs
    4328              :                 to be checked.
    4329              : 
    4330              :    Output:
    4331              :    COND_EXPR - conditional expression.
    4332              : 
    4333              :    The returned COND_EXPR is the conditional expression to be used in the if
    4334              :    statement that controls which version of the loop gets executed at runtime.
    4335              : */
    4336              : 
    4337              : void
    4338         3401 : vect_create_cond_for_alias_checks (loop_vec_info loop_vinfo, tree * cond_expr)
    4339              : {
    4340         3401 :   const vec<dr_with_seg_len_pair_t> &comp_alias_ddrs =
    4341              :     LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo);
    4342              : 
    4343         3401 :   if (comp_alias_ddrs.is_empty ())
    4344              :     return;
    4345              : 
    4346         3288 :   create_runtime_alias_checks (LOOP_VINFO_LOOP (loop_vinfo),
    4347              :                                &comp_alias_ddrs, cond_expr);
    4348         3288 :   if (dump_enabled_p ())
    4349         1382 :     dump_printf_loc (MSG_NOTE, vect_location,
    4350              :                      "created %u versioning for alias checks.\n",
    4351              :                      comp_alias_ddrs.length ());
    4352              : }
    4353              : 
    4354              : 
    4355              : /* Function vect_loop_versioning.
    4356              : 
    4357              :    If the loop has data references that may or may not be aligned or/and
    4358              :    has data reference relations whose independence was not proven then
    4359              :    two versions of the loop need to be generated, one which is vectorized
    4360              :    and one which isn't.  A test is then generated to control which of the
    4361              :    loops is executed.  The test checks for the alignment of all of the
    4362              :    data references that may or may not be aligned.  An additional
    4363              :    sequence of runtime tests is generated for each pairs of DDRs whose
    4364              :    independence was not proven.  The vectorized version of loop is
    4365              :    executed only if both alias and alignment tests are passed.
    4366              : 
    4367              :    The test generated to check which version of loop is executed
    4368              :    is modified to also check for profitability as indicated by the
    4369              :    cost model threshold TH.
    4370              : 
    4371              :    The versioning precondition(s) are placed in *COND_EXPR and
    4372              :    *COND_EXPR_STMT_LIST.  */
    4373              : 
    4374              : class loop *
    4375         3965 : vect_loop_versioning (loop_vec_info loop_vinfo,
    4376              :                       gimple *loop_vectorized_call)
    4377              : {
    4378         3965 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *nloop;
    4379         3965 :   class loop *scalar_loop = LOOP_VINFO_SCALAR_LOOP (loop_vinfo);
    4380         3965 :   basic_block condition_bb;
    4381         3965 :   gphi_iterator gsi;
    4382         3965 :   gimple_stmt_iterator cond_exp_gsi;
    4383         3965 :   basic_block merge_bb;
    4384         3965 :   basic_block new_exit_bb;
    4385         3965 :   edge new_exit_e, e;
    4386         3965 :   gphi *orig_phi, *new_phi;
    4387         3965 :   tree cond_expr = NULL_TREE;
    4388         3965 :   tree arg;
    4389         3965 :   profile_probability prob = profile_probability::likely ();
    4390         3965 :   gimple_seq gimplify_stmt_list = NULL;
    4391         3965 :   tree scalar_loop_iters = LOOP_VINFO_NITERSM1 (loop_vinfo);
    4392         3965 :   bool version_align = LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo);
    4393         3965 :   bool version_spec_read = LOOP_REQUIRES_VERSIONING_FOR_SPEC_READ (loop_vinfo);
    4394         3965 :   bool version_alias = LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo);
    4395         3965 :   bool version_niter = LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo);
    4396         3965 :   poly_uint64 versioning_threshold
    4397              :     = LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo);
    4398         3965 :   tree version_simd_if_cond
    4399              :     = LOOP_REQUIRES_VERSIONING_FOR_SIMD_IF_COND (loop_vinfo);
    4400         3965 :   unsigned th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
    4401         3965 :   bool uncounted_p = LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo);
    4402              : 
    4403              :   /* Start with the niter assumptions so they are split out together
    4404              :      with the cost model check, short-circuiting all other checks
    4405              :      since niter information is not valid when the assumptions do not
    4406              :      hold.  */
    4407         3965 :   if (version_niter)
    4408          478 :     cond_expr = LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo);
    4409              : 
    4410         3965 :   if (!uncounted_p
    4411              :       && vect_apply_runtime_profitability_check_p (loop_vinfo)
    4412              :       && !ordered_p (th, versioning_threshold))
    4413              :     {
    4414              :       tree expr = fold_build2 (GE_EXPR, boolean_type_node, scalar_loop_iters,
    4415              :                                build_int_cst (TREE_TYPE (scalar_loop_iters),
    4416              :                                               th - 1));
    4417              :       if (cond_expr)
    4418              :         cond_expr = fold_build2 (BIT_AND_EXPR, boolean_type_node,
    4419              :                                  expr, cond_expr);
    4420              :       else
    4421              :         cond_expr = expr;
    4422              :     }
    4423              : 
    4424         3965 :   if (!uncounted_p && maybe_ne (versioning_threshold, 0U))
    4425              :     {
    4426         3949 :       tree expr = fold_build2 (GE_EXPR, boolean_type_node, scalar_loop_iters,
    4427              :                                build_int_cst (TREE_TYPE (scalar_loop_iters),
    4428              :                                               versioning_threshold - 1));
    4429         3949 :       if (cond_expr)
    4430          478 :         cond_expr = fold_build2 (BIT_AND_EXPR, boolean_type_node,
    4431              :                                  expr, cond_expr);
    4432              :       else
    4433         3471 :         cond_expr = expr;
    4434              :     }
    4435              : 
    4436         3965 :   tree cost_name = NULL_TREE;
    4437         3965 :   gimple_seq cond_expr_stmt_list = NULL;
    4438         3965 :   profile_probability prob2 = profile_probability::always ();
    4439         3965 :   if (cond_expr
    4440         3949 :       && EXPR_P (cond_expr)
    4441         2853 :       && (version_niter
    4442         2853 :           || version_align
    4443              :           || version_alias
    4444         2328 :           || version_simd_if_cond))
    4445              :     {
    4446         2853 :       cost_name = cond_expr = force_gimple_operand_1 (unshare_expr (cond_expr),
    4447              :                                                       &cond_expr_stmt_list,
    4448              :                                                       is_gimple_val, NULL_TREE);
    4449              :       /* Split prob () into two so that the overall probability of passing
    4450              :          both the cost-model and versioning checks is the orig prob.  */
    4451         2853 :       prob2 = prob = prob.sqrt ();
    4452              :       /* Rewrite to defined if there was an niter versioning condition.
    4453              :          ???  We fail to be more selective with respect to niter may_be_zero
    4454              :          and assumptions.  */
    4455         2853 :       if (version_niter)
    4456         4264 :         for (auto gsi = gsi_start (cond_expr_stmt_list); !gsi_end_p (gsi);
    4457         3308 :              gsi_next (&gsi))
    4458         3308 :           if (gimple_needing_rewrite_undefined (gsi_stmt (gsi)))
    4459          117 :             rewrite_to_defined_unconditional (&gsi);
    4460              :     }
    4461              : 
    4462         3965 :   if (cond_expr)
    4463              :     {
    4464         3949 :       gimple_seq tem = NULL;
    4465         3949 :       cond_expr = force_gimple_operand_1 (unshare_expr (cond_expr),
    4466              :                                           &tem, is_gimple_condexpr_for_cond,
    4467              :                                           NULL_TREE);
    4468         3949 :       gimple_seq_add_seq (&cond_expr_stmt_list, tem);
    4469              :     }
    4470              : 
    4471         3965 :   if (version_align)
    4472           82 :     vect_create_cond_for_align_checks (loop_vinfo, &cond_expr,
    4473              :                                        &cond_expr_stmt_list);
    4474              : 
    4475         3965 :   if (version_spec_read)
    4476            0 :     vect_create_cond_for_vla_spec_read (loop_vinfo, &cond_expr);
    4477              : 
    4478         3965 :   if (version_alias)
    4479              :     {
    4480         3401 :       vect_create_cond_for_unequal_addrs (loop_vinfo, &cond_expr);
    4481         3401 :       vect_create_cond_for_lower_bounds (loop_vinfo, &cond_expr);
    4482         3401 :       vect_create_cond_for_alias_checks (loop_vinfo, &cond_expr);
    4483              :     }
    4484              : 
    4485         3965 :   if (version_simd_if_cond)
    4486              :     {
    4487           62 :       gcc_assert (dom_info_available_p (CDI_DOMINATORS));
    4488           62 :       if (flag_checking)
    4489           62 :         if (basic_block bb
    4490           62 :             = gimple_bb (SSA_NAME_DEF_STMT (version_simd_if_cond)))
    4491           62 :           gcc_assert (bb != loop->header
    4492              :                       && dominated_by_p (CDI_DOMINATORS, loop->header, bb)
    4493              :                       && (scalar_loop == NULL
    4494              :                           || (bb != scalar_loop->header
    4495              :                               && dominated_by_p (CDI_DOMINATORS,
    4496              :                                                  scalar_loop->header, bb))));
    4497           62 :       tree zero = build_zero_cst (TREE_TYPE (version_simd_if_cond));
    4498           62 :       tree c = fold_build2 (NE_EXPR, boolean_type_node,
    4499              :                             version_simd_if_cond, zero);
    4500           62 :       if (cond_expr)
    4501           62 :         cond_expr = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
    4502              :                                  c, cond_expr);
    4503              :       else
    4504              :         cond_expr = c;
    4505           62 :       if (dump_enabled_p ())
    4506            5 :         dump_printf_loc (MSG_NOTE, vect_location,
    4507              :                          "created versioning for simd if condition check.\n");
    4508              :     }
    4509              : 
    4510         3965 :   cond_expr = force_gimple_operand_1 (unshare_expr (cond_expr),
    4511              :                                       &gimplify_stmt_list,
    4512              :                                       is_gimple_condexpr_for_cond, NULL_TREE);
    4513         3965 :   gimple_seq_add_seq (&cond_expr_stmt_list, gimplify_stmt_list);
    4514              : 
    4515              :   /* Compute the outermost loop cond_expr and cond_expr_stmt_list are
    4516              :      invariant in.  */
    4517         3965 :   class loop *outermost = outermost_invariant_loop_for_expr (loop, cond_expr);
    4518         3965 :   for (gimple_stmt_iterator gsi = gsi_start (cond_expr_stmt_list);
    4519        71882 :        !gsi_end_p (gsi); gsi_next (&gsi))
    4520              :     {
    4521        67917 :       gimple *stmt = gsi_stmt (gsi);
    4522        67917 :       update_stmt (stmt);
    4523        67917 :       ssa_op_iter iter;
    4524        67917 :       use_operand_p use_p;
    4525        67917 :       basic_block def_bb;
    4526       156370 :       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
    4527        88453 :         if ((def_bb = gimple_bb (SSA_NAME_DEF_STMT (USE_FROM_PTR (use_p))))
    4528        88453 :             && flow_bb_inside_loop_p (outermost, def_bb))
    4529         2664 :           outermost = superloop_at_depth (loop, bb_loop_depth (def_bb) + 1);
    4530              :     }
    4531              : 
    4532              :   /* Search for the outermost loop we can version.  Avoid versioning of
    4533              :      non-perfect nests but allow if-conversion versioned loops inside.  */
    4534         3965 :   class loop *loop_to_version = loop;
    4535         3965 :   if (flow_loop_nested_p (outermost, loop))
    4536              :     {
    4537         1547 :       if (dump_enabled_p ())
    4538          767 :         dump_printf_loc (MSG_NOTE, vect_location,
    4539              :                          "trying to apply versioning to outer loop %d\n",
    4540              :                          outermost->num);
    4541         1547 :       if (outermost->num == 0)
    4542         1466 :         outermost = superloop_at_depth (loop, 1);
    4543              :       /* And avoid applying versioning on non-perfect nests.  */
    4544              :       while (loop_to_version != outermost
    4545          104 :              && (e = single_exit (loop_outer (loop_to_version)))
    4546           85 :              && !(e->flags & EDGE_COMPLEX)
    4547           85 :              && (!loop_outer (loop_to_version)->inner->next
    4548           52 :                  || vect_loop_vectorized_call (loop_to_version))
    4549           37 :              && (!loop_outer (loop_to_version)->inner->next
    4550            4 :                  || !loop_outer (loop_to_version)->inner->next->next)
    4551         1619 :              && can_duplicate_loop_p (loop_outer (loop_to_version)))
    4552           35 :         loop_to_version = loop_outer (loop_to_version);
    4553              :     }
    4554              : 
    4555              :   /* Apply versioning.  If there is already a scalar version created by
    4556              :      if-conversion re-use that.  Note we cannot re-use the copy of
    4557              :      an if-converted outer-loop when vectorizing the inner loop only.  */
    4558         3965 :   gcond *cond;
    4559         3965 :   if ((!loop_to_version->inner || loop == loop_to_version)
    4560         3934 :       && loop_vectorized_call)
    4561              :     {
    4562           98 :       gcc_assert (scalar_loop);
    4563           98 :       condition_bb = gimple_bb (loop_vectorized_call);
    4564          196 :       cond = as_a <gcond *> (*gsi_last_bb (condition_bb));
    4565           98 :       gimple_cond_set_condition_from_tree (cond, cond_expr);
    4566           98 :       update_stmt (cond);
    4567              : 
    4568           98 :       if (cond_expr_stmt_list)
    4569              :         {
    4570           98 :           cond_exp_gsi = gsi_for_stmt (loop_vectorized_call);
    4571           98 :           gsi_insert_seq_before (&cond_exp_gsi, cond_expr_stmt_list,
    4572              :                                  GSI_SAME_STMT);
    4573              :         }
    4574              : 
    4575              :       /* if-conversion uses profile_probability::always () for both paths,
    4576              :          reset the paths probabilities appropriately.  */
    4577           98 :       edge te, fe;
    4578           98 :       extract_true_false_edges_from_block (condition_bb, &te, &fe);
    4579           98 :       te->probability = prob;
    4580           98 :       fe->probability = prob.invert ();
    4581              :       /* We can scale loops counts immediately but have to postpone
    4582              :          scaling the scalar loop because we re-use it during peeling.
    4583              : 
    4584              :          Ifcvt duplicates loop preheader, loop body and produces an basic
    4585              :          block after loop exit.  We need to scale all that.  */
    4586           98 :       basic_block preheader = loop_preheader_edge (loop_to_version)->src;
    4587           98 :       preheader->count = preheader->count.apply_probability (prob * prob2);
    4588           98 :       scale_loop_frequencies (loop_to_version, prob * prob2);
    4589              :       /* When the loop has multiple exits then we can only version itself.
    4590              :         This is denoted by loop_to_version == loop.  In this case we can
    4591              :         do the versioning by selecting the exit edge the vectorizer is
    4592              :         currently using.  */
    4593           98 :       edge exit_edge;
    4594           98 :       if (loop_to_version == loop)
    4595           98 :        exit_edge = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    4596              :       else
    4597            0 :        exit_edge = single_exit (loop_to_version);
    4598           98 :       exit_edge->dest->count = preheader->count;
    4599           98 :       LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo) = (prob * prob2).invert ();
    4600              : 
    4601           98 :       nloop = scalar_loop;
    4602           98 :       if (dump_enabled_p ())
    4603           98 :         dump_printf_loc (MSG_NOTE, vect_location,
    4604              :                          "reusing %sloop version created by if conversion\n",
    4605              :                          loop_to_version != loop ? "outer " : "");
    4606           98 :     }
    4607              :   else
    4608              :     {
    4609         3867 :       if (loop_to_version != loop
    4610         3867 :           && dump_enabled_p ())
    4611           16 :         dump_printf_loc (MSG_NOTE, vect_location,
    4612              :                          "applying loop versioning to outer loop %d\n",
    4613              :                          loop_to_version->num);
    4614              : 
    4615         3867 :       unsigned orig_pe_idx = loop_preheader_edge (loop)->dest_idx;
    4616              : 
    4617         3867 :       initialize_original_copy_tables ();
    4618         7734 :       nloop = loop_version (loop_to_version, cond_expr, &condition_bb,
    4619         3867 :                             prob * prob2, (prob * prob2).invert (),
    4620         3867 :                             prob * prob2, (prob * prob2).invert (),
    4621              :                             true);
    4622              : 
    4623              :       /* If the PHI nodes in the loop header were reallocated, we need to fix up
    4624              :          our internally stashed copies of those.  */
    4625         3867 :       if (loop_to_version == loop)
    4626         3836 :         for (auto gsi = gsi_start_phis (loop->header);
    4627        15189 :              !gsi_end_p (gsi); gsi_next (&gsi))
    4628        11353 :           loop_vinfo->resync_stmt_addr (gsi.phi ());
    4629              : 
    4630              :       /* We will later insert second conditional so overall outcome of
    4631              :          both is prob * prob2.  */
    4632         3867 :       edge true_e, false_e;
    4633         3867 :       extract_true_false_edges_from_block (condition_bb, &true_e, &false_e);
    4634         3867 :       true_e->probability = prob;
    4635         3867 :       false_e->probability = prob.invert ();
    4636         3867 :       gcc_assert (nloop);
    4637         3867 :       nloop = get_loop_copy (loop);
    4638              : 
    4639              :       /* For cycle vectorization with SLP we rely on the PHI arguments
    4640              :          appearing in the same order as the SLP node operands which for the
    4641              :          loop PHI nodes means the preheader edge dest index needs to remain
    4642              :          the same for the analyzed loop which also becomes the vectorized one.
    4643              :          Make it so in case the state after versioning differs by redirecting
    4644              :          the first edge into the header to the same destination which moves
    4645              :          it last.  */
    4646         3867 :       if (loop_preheader_edge (loop)->dest_idx != orig_pe_idx)
    4647              :         {
    4648          347 :           edge e = EDGE_PRED (loop->header, 0);
    4649          347 :           ssa_redirect_edge (e, e->dest);
    4650          347 :           flush_pending_stmts (e);
    4651              :         }
    4652         3867 :       gcc_assert (loop_preheader_edge (loop)->dest_idx == orig_pe_idx);
    4653              : 
    4654              :       /* Kill off IFN_LOOP_VECTORIZED_CALL in the copy, nobody will
    4655              :          reap those otherwise;  they also refer to the original
    4656              :          loops.  */
    4657              :       class loop *l = loop;
    4658         3871 :       while (gimple *call = vect_loop_vectorized_call (l))
    4659              :         {
    4660            4 :           call = SSA_NAME_DEF_STMT (get_current_def (gimple_call_lhs (call)));
    4661            4 :           fold_loop_internal_call (call, boolean_false_node);
    4662            4 :           l = loop_outer (l);
    4663            4 :         }
    4664         3867 :       free_original_copy_tables ();
    4665              : 
    4666         3867 :       if (cond_expr_stmt_list)
    4667              :         {
    4668         3840 :           cond_exp_gsi = gsi_last_bb (condition_bb);
    4669         3840 :           gsi_insert_seq_before (&cond_exp_gsi, cond_expr_stmt_list,
    4670              :                                  GSI_SAME_STMT);
    4671              :         }
    4672              : 
    4673              :       /* Loop versioning violates an assumption we try to maintain during
    4674              :          vectorization - that the loop exit block has a single predecessor.
    4675              :          After versioning, the exit block of both loop versions is the same
    4676              :          basic block (i.e. it has two predecessors). Just in order to simplify
    4677              :          following transformations in the vectorizer, we fix this situation
    4678              :          here by adding a new (empty) block on the exit-edge of the loop,
    4679              :          with the proper loop-exit phis to maintain loop-closed-form.
    4680              :          If loop versioning wasn't done from loop, but scalar_loop instead,
    4681              :          merge_bb will have already just a single successor.  */
    4682              : 
    4683              :       /* When the loop has multiple exits then we can only version itself.
    4684              :          This is denoted by loop_to_version == loop.  In this case we can
    4685              :          do the versioning by selecting the exit edge the vectorizer is
    4686              :          currently using.  */
    4687         3867 :       edge exit_edge;
    4688         3867 :       if (loop_to_version == loop)
    4689         3836 :         exit_edge = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
    4690              :       else
    4691           31 :         exit_edge = single_exit (loop_to_version);
    4692              : 
    4693         3867 :       gcc_assert (exit_edge);
    4694         3867 :       merge_bb = exit_edge->dest;
    4695         3867 :       if (EDGE_COUNT (merge_bb->preds) >= 2)
    4696              :         {
    4697         3867 :           gcc_assert (EDGE_COUNT (merge_bb->preds) >= 2);
    4698         3867 :           new_exit_bb = split_edge (exit_edge);
    4699         3867 :           new_exit_e = exit_edge;
    4700         3867 :           e = EDGE_SUCC (new_exit_bb, 0);
    4701              : 
    4702         8063 :           for (gsi = gsi_start_phis (merge_bb); !gsi_end_p (gsi);
    4703         4196 :                gsi_next (&gsi))
    4704              :             {
    4705         4196 :               tree new_res;
    4706         4196 :               orig_phi = gsi.phi ();
    4707         4196 :               new_res = copy_ssa_name (PHI_RESULT (orig_phi));
    4708         4196 :               new_phi = create_phi_node (new_res, new_exit_bb);
    4709         4196 :               arg = PHI_ARG_DEF_FROM_EDGE (orig_phi, e);
    4710         4196 :               add_phi_arg (new_phi, arg, new_exit_e,
    4711              :                            gimple_phi_arg_location_from_edge (orig_phi, e));
    4712         4196 :               adjust_phi_and_debug_stmts (orig_phi, e, PHI_RESULT (new_phi));
    4713              :             }
    4714              :         }
    4715              : 
    4716         3867 :       update_ssa (TODO_update_ssa_no_phi);
    4717              :     }
    4718              : 
    4719              :   /* Split the cost model check off to a separate BB.  Costing assumes
    4720              :      this is the only thing we perform when we enter the scalar loop
    4721              :      from a failed cost decision.  */
    4722         3965 :   if (cost_name && TREE_CODE (cost_name) == SSA_NAME)
    4723              :     {
    4724         2853 :       gimple *def = SSA_NAME_DEF_STMT (cost_name);
    4725         2853 :       gcc_assert (gimple_bb (def) == condition_bb);
    4726              :       /* All uses of the cost check are 'true' after the check we
    4727              :          are going to insert.  */
    4728         2853 :       replace_uses_by (cost_name, boolean_true_node);
    4729              :       /* And we're going to build the new single use of it.  */
    4730         2853 :       gcond *cond = gimple_build_cond (NE_EXPR, cost_name, boolean_false_node,
    4731              :                                        NULL_TREE, NULL_TREE);
    4732         2853 :       edge e = split_block (gimple_bb (def), def);
    4733         2853 :       gimple_stmt_iterator gsi = gsi_for_stmt (def);
    4734         2853 :       gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
    4735         2853 :       edge true_e, false_e;
    4736         2853 :       extract_true_false_edges_from_block (e->dest, &true_e, &false_e);
    4737         2853 :       e->flags &= ~EDGE_FALLTHRU;
    4738         2853 :       e->flags |= EDGE_TRUE_VALUE;
    4739         2853 :       edge e2 = make_edge (e->src, false_e->dest, EDGE_FALSE_VALUE);
    4740         2853 :       e->probability = prob2;
    4741         2853 :       e2->probability = prob2.invert ();
    4742         2853 :       e->dest->count = e->count ();
    4743         2853 :       set_immediate_dominator (CDI_DOMINATORS, false_e->dest, e->src);
    4744         2853 :       auto_vec<basic_block, 3> adj;
    4745         2853 :       for (basic_block son = first_dom_son (CDI_DOMINATORS, e->dest);
    4746         8527 :            son;
    4747         5674 :            son = next_dom_son (CDI_DOMINATORS, son))
    4748         8495 :         if (EDGE_COUNT (son->preds) > 1)
    4749         2821 :           adj.safe_push (son);
    4750        11380 :       for (auto son : adj)
    4751         2821 :         set_immediate_dominator (CDI_DOMINATORS, son, e->src);
    4752              :       //debug_bb (condition_bb);
    4753              :       //debug_bb (e->src);
    4754         2853 :     }
    4755              : 
    4756         3965 :   if (version_niter)
    4757              :     {
    4758              :       /* The versioned loop could be infinite, we need to clear existing
    4759              :          niter information which is copied from the original loop.  */
    4760          478 :       gcc_assert (loop_constraint_set_p (loop, LOOP_C_FINITE));
    4761          478 :       vect_free_loop_info_assumptions (nloop);
    4762              :     }
    4763              : 
    4764         3965 :   if (LOCATION_LOCUS (vect_location.get_location_t ()) != UNKNOWN_LOCATION
    4765         3965 :       && dump_enabled_p ())
    4766              :     {
    4767          916 :       if (version_alias)
    4768          795 :         dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | MSG_PRIORITY_USER_FACING,
    4769              :                          vect_location,
    4770              :                          "loop versioned for vectorization because of "
    4771              :                          "possible aliasing\n");
    4772          916 :       if (version_align)
    4773           67 :         dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | MSG_PRIORITY_USER_FACING,
    4774              :                          vect_location,
    4775              :                          "loop versioned for vectorization to enhance "
    4776              :                          "alignment\n");
    4777              : 
    4778              :     }
    4779              : 
    4780         3965 :   return nloop;
    4781              : }
        

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.